Вы находитесь на странице: 1из 13

Decision Making and Branching

Introduction:
Decision making is one of the most important concepts of computer programming. Programs should be able to make logical (true/false) decisions based on the condition they are in; every program has one or few problem/s to solve; depending on the nature of the problems, important decisions have to be made in order to solve those particular problems. In C programming selection construct or conditional statement is used for decision making. Diagram 1 illustrates selection construct.

Diagram 1 simple selection construct

Conditional statement is the term used by many programming languages. The importance of conditional statements should not be ignored because every program has an example of these statements. IF statement and switch statement are the most popular conditional statements used in C.

Branching
Branch is the term given to the code executed in sequence as a result of change in the programs flow; the programs flow can be changed by conditional statements in that program. Diagram 2 shows the link between selection (decision making) and branching (acting).

Diagram 2 "branch" depends on the condition of the selection code

Branching is the process of choosing the right branch for execution, depending on the result of conditional statement.

Decision Making with IF Statement:


If statement is the selection statement used to select course of action depending on the conditions given. Therefore programmers can use this statement to control the flow of their program. If the programs condition matches if statement condition then the code will be executed otherwise it will be ignored and the rest of the program will be executed.

Syntax;
if (condition) { statement; }

Simple IF statement;

#Include <stdio.h> Void main() { Int i=2; If(i==2) { Printf(this is good); } }

The IF..ELSE Statement:


if else construct is the upgraded version of if statement. Unlike if statement where you could only specify code for when condition is true; for if else statement you can also specify code for when the condition is not True (false). So the definition for the if else statement is: Syntax; If(condition) { Statememt; } Else { Statement ; }

Nesting of IF.ELSE statement:


The if statement may itself contain another if statement is known as nested if statement. Syntax:

if (condition1) if (condition2) statement-1; else statement-2; else statement-3;

The if statement may be nested as deeply as you need to nest it. One block of code will only be executed if two conditions are true. Condition 1 is tested first and then condition 2 is tested. The second if condition is nested in the first. The second if condition is tested only when the first condition is true else the program flow will skip to the corresponding else statement.

The ELSE IF Ladder:


When a series of many conditions have to be checked we may use the ladder else if statement which takes the following general form. Syntax

if (condition1) statement 1; else if (condition2) statement2; else if (condition3) statement3; else if (condition) statement n; else default statement; statement-x; This construct is known as if else construct or ladder. The conditions are evaluated fromthe top of the ladder to downwards. As soon on the true condition is found, the statement associated with it is executed and the control is transferred to the statement x (skipping the rest of the ladder. When all the condition becomes false, the final else containing the default statement will be executed.

The Switch Statement:


Switch statement is another type of conditional statement used by programmers. Switch is widely used for menus. break statement is very important. If it is not used properly all the code after the matched condition will be executed incorrectly. For example: looking at syntax 4; if the break for case 2 was missing, all the codes after and including case 2 would be executed until the next break statement was reached. syntax

Switch (expression) { Case 1: statement break; Case 2: statement 2 break;

Case n: statement n break; Default: statement break;


}

The GOTO Statement:


A goto statement is used to branch (transfer control) to another location in a program.

#include <stdio.h> #include <conio.h> int main() { int n = 0; loop: ; printf("\n%d", n); n++; if (n<10) { goto loop; } getch(); return 0;

Decision Making and Looping:


Introduction
Loops are group of instructions executed repeatedly while certain condition remains true. There are two types of loops, counter controlled and sentinel controlled loops (repetition).

Counter controlled repetitions are the loops which the number of repetitions needed for the loop is known before the loop begins; these loops have control variables to count repetitions. Counter controlled repetitions need initialized control variable (loop counter), an increment (or decrement) statement and a condition used to terminate the loop (continuation condition). Sentinel controlled repetitions are the loops with an indefinite repetitions; this type of loops use sentinel value to indicate end of iteration. Loops are mostly used to output the data stored in arrays, however they are also used for sorting and searching of data.
The C language provides for three loop constructs for performing loop operations. They are:

1. The while statement. 2. The do statement. 3. The for statement.

The While Statement


while statement is a sentinel controlled repetition which can be iterated indefinite number of times. Number of iterations is controlled using a sentinel variable (test expression). Synax;
while (test condition) { body of the loop }

Example: #include<studio.h> Void main() { x = 10; while (x < 16) { printf("%d",x); x = x+1; }
}

------------- Initialization ------------- Test condition ------------- body of the loop

The do..while statement


do..while statement is a sentinel controlled repetition which is quite different from the other two statements we covered earlier. This statement runs the code first and then checks the test-expression, so there is always a guarantee that the code runs at least once. This type of loop is generally used for password checks and menus.
Syntax;

Do { body of the loop; } while(test condition)

For Loop
For loops is a counter controlled repetition; therefore the number iterations must be known before the loop starts.
for(control-variable; continuation-condition;increment/decrement-control) { Statement; }

Arrays
Introduction:
An array in C Programing Language can be defined as number of memory locations, each of which can store the same data type and which can be references through the same variable name. An array is a collective name given to a group of similar quantities. These similar quantities could be percentage marks of 100 students, number of chairs in home, or salaries of 300 employees or ages of 25 students. Thus an array is a collection of similar elements. These similar elements could be all integers or all floats or all characters etc. Usually, the array of characters is called a string, where as an array of integers or floats is called simply an array. All elements of any given array must be of the same type i.e we cant have

an array of 10 numbers, of which 5 are ints and 5 are floats. Arrays and pointers have a special relationship as arrays use pointers to reference memory locations.

Single Dimension Arrays

Declaring Single Dimension Arrays


Arrays can be declared using any of the data types available in C. Array size must be declared using constant value before initialization. A single dimensional array will be useful for simple grouping of data that is relatively small in size. You can declare a single dimensional array as follows:
<data type> array_name[size_of_array];

Initializing Single Dimension Arrays


Array can be initialized in two ways, initializing on declaration or initialized by assignment.

Initializing on Declaration
If you know the values you want in the array at declaration time, you can initialize an array as follows:
Syntax: <data type> array_name[size_of_array] = {element 1, element 2, ...}; Sample program
#include <stdio.h> int main() { int iMarks[4]; short newMarks[4]; iMarks[0]=78; iMarks[1]=64; iMarks[2]=66; iMarks[3]=74; for(i=0; i<4; i++) newMarks[i]=iMarks[i]; for(j=0; j<4; j++)

printf("%d\n", newMarks[j]); return 0; }

Two-dimensional Arrays
Two-dimensional array are those type of array, which has finite number of rows and finite number of columns. The declaration form of 2-dimensional array is Data_type Array_name [row size][column size]; The type may be any valid type supported by C. The rule for giving the array name is same as the ordinary variable. The row size and column size should be an individual constant.

Multi-dimensional Arrays
Arrays can have more than one dimension. Two dimensional arrays are widely used for tables, neural networks and etc. You can have as many dimensions as you would like but you have to consider the complexity of the code as you add new dimension. Multidimensional arrays allow you to store data in a spreadsheet or matrix like format.

Declaring Multidimensional Arrays


To declare a multidimensional array:
<data type> array_name[size_of_first_dimension][size_of_second_dimension] ...

Initializing Multidimensional Arrays


1. Just like single dimension array, you can initialize the multidimensional array also upon declaration as well as initialize by assignment.
2.

3. 4.

<data type> array_name[size_of_dimension1][size_of_second_dimension2] ... = { {element 1, element 2, element 3, },

5. . 6. .

7. 8.
9.

. } };

Dynamic Arrays
The dynamic array is an array data structure which can be resized during runtime which means elements can be added and removed. You can see in the given example that we prompt the user to enter the number of elements that he want to set into the array. The expression (int*)malloc(n*sizeof (int)) stores the number of elements in the memory. The malloc is basically used for memory allocation. By using the for loop the variable i reads the elements from the memory and displays the required array. Sample program; #include <stdlib.h> #include <stdio.h> #include <conio.h> int main() { int* array; int n, i; printf("Enter the number of elements: "); scanf("%d", &n); array = (int*) malloc(n*sizeof(int)); for (i=0; i<n; i++) { printf("Enter number %d: ", i); scanf("%d", &array[i]); } printf("\nThe Dynamic Array is: \n"); for (i=0; i<n; i++) { printf("The value of %d is %d\n", i, array[i]); } printf("Size= %d\n", i); getch();

Introduction to Programming &C


Program & Programming:
These programs illustrate various programming elements, concepts such as using operators, loops, functions, single and double dimensional arrays, performing operations on strings, files, pointers etc. Browse the code from simple c program to complicated ones you are looking for, every one of them is provided with output. C program download with executable files, so that you save on your computer and run programs without compiling the source code. All programs are made using c programming language and Codeblocks, most of these will work under Dev c++ compiler also. Download software you need to develop codes. The first program prints "Hello World" on screen.
#include <stdio.h> main() {

printf("Hello World\n"); return 0;

Output of above program: "Hello World"

Algorithm and Flowchart:


Flow char is a graphical representation of algorithm. It is used to represent algorithm steps into graphical format. It also gives us an idea to organize the sequence of steps or events necessary to solve a problem with the computer. In other words flow charts are symbolic diagrams of operations and the sequence, data flow, control flow and processing logic in information processing. These charts are used to understand any working sequence of the program.

Вам также может понравиться