PCE Unit – 3: Programming With C 151FY3-06
Decision Making and Branching / Control Statements
Control Statements enable us to specify the flow of program control; i.e., the order in
which the instructions in a program must be executed. Using control statements we can
control the flow of program in such a way so that it executes certain statements based on
the outcome of a condition (i.e. true or false). In C, decision control statements are:
1. if statement
2. switch statement
3. conditional operator statement
4. goto statement
These statements are popularly known as decision-making statements. Since these
statements ‘control’ the flow of execution, they are also known as control statements.
if Statement
The if statement in C is used to perform the operations based on some specific condition.
The operations specified in if block are executed if and only if the given condition is true.
if ( expression )
{
//code to be executed
}
It allows the computer to evaluate the expression first and then, depending on whether the
value of the expression is true or false.
Entry
True
Condition
False
The if statement may be implemented in different forms depending on the complexity of
conditions to be tested. The different forms are:
1. Simple if statement
2. if …. else statement
3. Nested if …. else statement
4. else if ladder
Simple if statement
The syntax of a simple if statement is
if ( expression )
{
Statements;
}
Stmt;
Subject Teacher: Bhagirath Singh Chauhan # 9829275869 Page No.: 1
PCE Unit – 3: Programming With C 151FY3-06
Entry
True
Condition
Statements
Stmt
The ‘Statements’ may be a single statement or a group of statements. If the test
expression is true, the statements will be executed, otherwise execution will jump to the
‘Stmt’.
The if…else Statement
The if…else statement is an extension of the simple if statement which, we can perform
two different operations, i.e., one is for the true of that condition, and the other is for the
false of the condition. The syntax of the if-else statement is:
if ( expression )
{
//code to be executed if condition is true
}
else
{
//code to be executed if condition is false
}
Entry
False True
Condition
Statements2 Statements1
Stmt
Example: Check whether a number is even or odd.
#include<stdio.h>
int main()
{
int number=0;
printf("enter a number:");
scanf("%d",&number);
if(number%2 == 0)
Subject Teacher: Bhagirath Singh Chauhan # 9829275869 Page No.: 2
PCE Unit – 3: Programming With C 151FY3-06
{
printf("%d is even number", number);
}
else
{
printf("%d is odd number", number);
}
return 0;
}
Output:
enter a number:4
4 is even number
enter a number:5
5 is odd number
Nested if…else Statement
When a series of decisions are involved, we may have to use more than one if…else
statement in nested form as shown below:
if ( expression 1 )
{
if ( expression 2 )
{
Statement 1;
}
else
{
Statement 2;
}
}
else
{
Statement 3;
}
Stmt;
If the expression 1 is false, the statement 3 will be executed, otherwise it continues to
perform the second test. If the expression 2 is true, the statement 1 will be evaluated,
otherwise the statement 2 will be evaluated.
Example: Write a program to determine whether the input year is a leap year or not.
#include <stdio.h>
int main()
{
int year;
printf("Enter a year: ");
scanf("%d",&year);
if(year % 100 == 0)
{
if(year % 400 == 0)
printf("\nLeap Year");
else
Subject Teacher: Bhagirath Singh Chauhan # 9829275869 Page No.: 3
PCE Unit – 3: Programming With C 151FY3-06
printf("\nNot a leap year");
}
else
{
if( year % 4 == 0)
printf("\nLeap year");
else
printf("\nNot a leap year");
}
return 0;
}
Output:
Enter a year: 2020
Leap year
The else if ladder
There is another way of putting ifs together when multipath decision are involved. A
multipath decision is a chain of ifs in which the statement associated with each else is an
if. It takes the following general form:
if ( expression-1 )
statement-1;
else if (expression-2 )
statement-2;
else if ( expression-3 )
statement-3;
else if ( expression-4 )
statement-4;
else
statement-5;
statement-n;
This construct is known as the else if ladder. The conditions are evaluated from the top,
downwards. As soon as a true condition is found, the statement associated with it is
executed and the control is transferred to the statement-n. When all the n condition
become false, then the final else containing statement-5 will be executed.
Subject Teacher: Bhagirath Singh Chauhan # 9829275869 Page No.: 4
PCE Unit – 3: Programming With C 151FY3-06
The switch Statement
C has a built-in multiway decision statement known as a switch. The switch statement
tests the value of a given variable (or expression) against a list of case values and when a
match is found, a block of statements associated with that case is executed. The general
form of the switch statement is as shown below:
switch ( expression ) {
case value1:
//code to be executed;
break; //optional
case value2:
//code to be executed;
break; //optional
…….
default: //optional
default-stmts;
}
Rules for switch statement
The switch expression must be of an integer or character type.
The case value must be an integer or character constant and are known as case
labels which ends with a colon (:).
Duplicate case value are not allowed.
The case value can be used only inside the switch statement.
The break statement at the end of each block signals the end of a particular case
and causes an exit from the switch statement. It is optional.
The default is an optional case. When present, it will be executed if the value of the
expression does not match with any of the case values.
You can have switch statements inside another switch statement (Nested switch).
The main reason for using a switch include improving clarity, by reducing otherwise
repetitive coding, and also offering the potential for faster execution through easier
compiler optimization in many cases.
Limitation of switch statement
It is good for equality comparisons but not for range comparisons.
It works well for int type data only and not good for other data types.
It works well with constants but not with variables (as case labels).
Example: Write a program to perform simple calculation (+, -, *, / and %).
void main() {
char operator;
float n1, n2;
printf("Enter an operator (+, -, *, /) : ");
scanf("%c", &operator);
printf("Enter two operands: ");
scanf("%f %f",&n1, &n2);
switch(operator) {
case '+': printf("%.2f + %.2f = %.2f", n1, n2, n1+n2);
break;
case '-': printf("%.2f - %.2f = %.2f", n1, n2, n1-n2);
Subject Teacher: Bhagirath Singh Chauhan # 9829275869 Page No.: 5
PCE Unit – 3: Programming With C 151FY3-06
break;
case '*': printf("%.2f * %.2f = %.2f",n1, n2, n1*n2);
break;
case '/': printf("%.2f / %.2f = %.2f",n1, n2, n1/n2);
break;
default: printf("Sorry!! Operator is not matched");
}
}
Difference between if-else and switch
Title if – else switch case
If statement is used to select The switch statement is used to select
Definition among two alternatives. among multiple alternatives.
It contains either logical or It contains a single expression which can
Expression equality expression. be either a character or integer variable.
It evaluates all types of data, It evaluates either an integer, or
Evaluation such as integer, floating-point, character.
character or Boolean.
If the condition is not true, If the value does not match with any
Default then by default, else block will case, then by default, default statement
execution be executed. is executed.
Editing is not easy in the if- Cases in a switch statement are easy to
else statement. maintain and modify. Therefore, we can
Editing say that the removal or editing of any
case will not interrupt the execution of
other cases.
If there are multiple choices If we have multiple choices then the
implemented then the speed switch statement is the best option as
Speed of the execution will be slow. the speed of the execution will be much
higher than if-else.
Conditional Operator ( ? : )
The C language has an unusual operator, useful for making two-way decisions. This
operator is a combination of ? and :, and takes three operands. This operator is known as
the conditional operator. The syntax of conditional operator is:
exp1 ? exp2 : exp3 ;
The exp1 is evaluated first. If the result is true, exp2 is evaluated otherwise exp3 is
evaluated and its value is returned. For example, the segment
if ( a > b )
max = a;
else
max = b;
can be written as
max = ( a > b ) ? a : b ;
Subject Teacher: Bhagirath Singh Chauhan # 9829275869 Page No.: 6
PCE Unit – 3: Programming With C 151FY3-06
Iteration / Looping and Decision Making
Loops or iterations are used when we want to execute a statement or set of statement
many times. A program loop therefore consists of two segments, one known as the body
of the loop and the other known as the control statement (test condition). The control
statement tests certain conditions and then directs the repeated execution of the
statements contained in the body of the loop.
Depending on the position of the control statement in the loop, a control structure may be
classified either as the entry-controlled loop or as the exit-controlled loop.
Entry Entry
False True Loop
Condition Body
Loop
Body
True
Condition
False
Entry Controlled Loop Exit Controlled Loop
The C language provides for three constructs for performing loop operations. They are:
1. The while statement
2. The do statement
3. The for statement
The while statement
The while is an entry-controlled loop statement. The condition is evaluated and if the
condition is true, then the body of the loop is executed. This process of repeated
execution of the body continues until the condition finally becomes false and the control is
transferred out of the loop. The basic format of the while statement is:
while ( condition )
{
//code to be executed;
}
The do statement
The do is an exit controlled loop. On some occasions it might be necessary to execute the
body of the loop before the test is performed. Such situations can be handled with the help
of the do statement. This takes the form:
do
{
//code to be executed;
} while (condition );
Subject Teacher: Bhagirath Singh Chauhan # 9829275869 Page No.: 7
PCE Unit – 3: Programming With C 151FY3-06
On reaching the do statement, the program proceeds to evaluate the body of the loop
first. At the end of the loop, the condition in the while statement is evaluated. If the
condition is true, the program continues to evaluate the body of the loop again. This
process continues as long as the condition is true.
Difference between while and do while loop
[Link]. while loop do-while loop
1 while loop is an entry controlled loop. do-while is en exit controlled loop.
Condition is checked first then Statement(s) is executed atleast once,
2
statement(s) is executed. thereafter condition is checked.
The while loop terminates when the As long as the condition is true, the
3
condition becomes false. compiler keeps executing the loop.
It might occur statement(s) is executed At least once the statement(s) is
4
zero times, if condition is false. executed.
5 No semicolon at the end of while. Semicolon at the end of while.
If there is a single statement, brackets
6 Brackets are always required.
are not required.
Variable in condition is initialized before Variable may be initialized before or
7
the execution of loop. within the loop.
while loop is not used for creating It is mostly used for creating menu-
8
menu-driven programs. driven programs.
Syntax of while loop: Syntax of do-while loop
while (condition) do
9 { {
Statement block; Statement block;
} } while (condition);
The for statement
The for loop is another entry-controlled loop that provides a more concise loop control
structure. The general form of the for loop is:
for ( initialization ; condition ; increment/decrement/update )
{
//Loop Body
}
The execution of the for statement is as follows:
1. Initialization of the control variables is done first, using assignment statements.
2. The value of the control variable is tested using the condition. If the condition is
true, the loop body is executed, otherwise the loop is terminated.
3. After executing loop body, the control variable is incremented or decremented, and
new value of the control variable is again tested.
Subject Teacher: Bhagirath Singh Chauhan # 9829275869 Page No.: 8
PCE Unit – 3: Programming With C 151FY3-06
Jumping Out of a Loop (Unconditional branching)
Jump statement makes the control jump to another section of the program
unconditionally when encountered. It is usually used to terminate the loop or switch case
instantly. It is also used to escape the execution of a section of the program. There are
following jump statements offered by C language:
1. break
2. continue
3. goto
4. return
break: When a break statement is encountered inside a loop, the loop is immediately
exited and the program continues with the statement immediately following the loop.
When the loop are nested, the break would only exit from the loop containing it.
Example: Add only positive numbers, if negative value is entered then jump out from loop.
#include <stdio.h>
int main()
{
int i, n, sum = 0;
for ( i = 1; i <= 5; i++)
{
printf(“\nEnter number: ”);
scanf(“%d”, &n);
if ( n < 0)
break;
sum += n;
}
printf(“\nSum = %d”, sum);
return 0;
}
continue: The continue causes the loop to be continued with the next iteration after
skipping any statements in between.
Example: Add only positive numbers out of 5 inputted numbers.
#include <stdio.h>
int main()
{
int i, n, sum = 0;
for ( i = 1; i <= 5; i++)
{
printf(“\nEnter number: ”);
scanf(“%d”, &n);
if ( n < 0)
continue;
sum += n;
}
printf(“\nSum = %d”, sum);
return 0;
}
Subject Teacher: Bhagirath Singh Chauhan # 9829275869 Page No.: 9
PCE Unit – 3: Programming With C 151FY3-06
The goto Statement
C supports the goto statement to branch unconditionally from one point to another in the
program. The goto requires a label in order to identify the place where the branch is to be
made. A label is any valid variable name, and must be followed by a colon. The label is
placed immediately before the statement where the control is to be transferred.
goto label;
….
label: statement;
return Statement
Return jump statement is usually used at the end of a function to end or terminate it with
or without a value. It takes the control from the calling function back to the main function
(main function itself can also have a return).
Nesting of Loops
Nesting of loops, that is, one loop statement within another loop statement, is allowed in
C. For example, two loops can be nested as follows:
for ( n = 1; n < 5; n++ )
{
while ( condition )
{
Statement(s);
}
}
The nesting may continue up to any desired level. (ANSI C allows up to 15 levels of
nesting).
Example: Print the factorial of a given number.
#include <stdio.h>
int main()
{
int i, num, fact = 1;
printf(“Enter a number: “);
scanf(“%d”, &num);
for(i = 2; i <=num; i++)
{
fact = fact * i;
}
printf(“\nFactorial of %d = %d”,num, fact);
return 0;
}
Example: Print the sum of digits of a number.
#include <stdio.h>
int main()
{
int num, temp, remainder, sum = 0;
printf(“Enter a number: ”);
Subject Teacher: Bhagirath Singh Chauhan # 9829275869 Page No.: 10
PCE Unit – 3: Programming With C 151FY3-06
scanf(“%d”, &num);
temp = num;
while(temp != 0)
{
remainder = temp % 10;
sum = sum + remainder;
temp = temp / 10;
}
printf(“\nSum of digits of %d = %d”, num, sum);
return 0;
}
Example: Print the reverse of a number.
#include <stdio.h>
int main()
{
int num, temp, reverse = 0, remainder;
printf(“Enter a number: ”);
scanf(“%d”, &num);
temp = num;
while(temp != 0)
{
remainder = temp % 10;
reverse = (reverse * 10) + remainder;
temp = temp / 10;
}
printf(“\nReverse of %d = %d”, num, reverse);
return 0;
}
Example: Calculate the sum of first n natural numbers.
#include <stdio.h>
int main()
{
int num, i, sum = 0;
printf(“Enter a positive number: “);
scanf(“%d”,&num);
for( i = 1; i <= num; i++)
{
sum = sum + i;
}
printf(“\nSum = %d”, sum);
return 0;
}
Subject Teacher: Bhagirath Singh Chauhan # 9829275869 Page No.: 11
PCE Unit – 3: Programming With C 151FY3-06
Array
An array is defined as the collection of similar type of data items stored at contiguous
memory locations. It is simply a grouping of like-type data. Arrays are the derived data
type in C language which can store the primitive type of data such as int, float, char,
double etc. In its simplest form, an array can be used to represent a list of numbers, or a
list of names.
Properties of Array
Each element of an array is of same data type and carries the same size.
Array elements are accessed by using an integer index. Array index starts with 0
and goes till size of array minus 1.
Elements of the array are stored at contiguous memory locations where the first
element is stored at the smallest memory location (base address).
Name of the array is also a constant pointer to the first element of the array.
Elements of the array can be randomly accessed since we can calculate the
address of each element of the array with the given base address and the size of
the data element.
Advantages of Array
Code Optimization: Less code to the access the data.
Ease of traversing: By using the loop, we can retrieve the elements of an array
easily.
Ease of sorting: To sort the elements of the array, we need a few lines of code
only.
Random Access: We can access any element randomly using the array.
Types of Array
We can use arrays to represent not only simple lists of values but also tables of data in
two, or more dimensions. Following are the types of an array:
1. One-dimensional arrays
2. Two-dimensional arrays
3. Multidimensional arrays
One-Dimensional Arrays
A list in which the elements are accessible by the variable name assigned to the list and
its subscript is known as a one-dimensional array.
Declaration of one-dimensional arrays
Like any other variable, arrays must be declared before they are used so that the compiler
can allocate space for them in memory. The general form of array declaration is:
Type array_name [ size ];
The Type specifies the type of element that will be contained in the array and size
indicates the maximum number of elements that can be stored inside the array. For
example:
Subject Teacher: Bhagirath Singh Chauhan # 9829275869 Page No.: 12
PCE Unit – 3: Programming With C 151FY3-06
int list [10] ;
declares the list as an array to contain a maximum of 10 integer.
The C language treats character string simply as arrays of characters. For example:
char name [15];
declares the name as a character array (string) variable that can hold a maximum of 15
characters.
Initialization of One-Dimensional Arrays
We can initialize the elements of arrays in the same way as the ordinary variables when
they are declared. For example:
int list [10] = {10, 20, 30, 40, 50, 60, 70, 80, 90, 100 }; or
int list [ ] = {10, 20, 30, 40, 50, 60, 70, 80, 90, 100 };
char name [15] = {‘B’, ‘h’, ‘a’, ‘g’, ‘I’, ‘r’, ‘a’, ‘t’, ‘h’, ‘\0’ }; or
char name [ ] = “Bhagirath”;
The values to the array elements can also be assigned as follows:
list[ 0] = 10;
list [1] = 20;
list [2] = 30;
The values to the array elements can also be initialized at run time as follows:
for( i = 0; i < 5; i++)
{
scanf(%d”, &list[i] );
}
Example:
#include <stdio.h>
int main()
{
int arr[10], i;
printf(“Enter 10 numbers: “);
for( i = 0; i < 9; i++)
scanf(“%d”, &arr[i]);
printf(“\nElements of an Array are: \n”);
for( i = 0; i < 9; i++)
printf(“%d\t”, arr[i]);
return 0;
}
Example: Print largest and second largest number of the array.
#include<stdio.h>
#define MAX 50
int main ()
{
int arr[MAX], i, size, largest, s_largest;
printf("Enter the size of the array: ");
scanf("%d",&size);
printf("Enter the elements of the array: ");
Subject Teacher: Bhagirath Singh Chauhan # 9829275869 Page No.: 13
PCE Unit – 3: Programming With C 151FY3-06
for(i = 0; i < size; i++)
{
scanf("%d",&arr[i]);
}
largest = arr[0];
s_largest = arr[1];
for(i=0;i < size; i++)
{
If ( arr[i] > largest)
{
s_largest = largest;
largest = arr[i];
}
else if (arr[i] > s_largest && arr[i] != largest)
{
s_largest = arr[i];
}
}
printf("largest = %d, second largest = %d", largest, s_largest);
return 0;
}
Example: Search an element of the array (linear search method).
#include <stdio.h>
#define MAX 100
int main()
{
int arr[MAX], n, flat = 0, item, i;
printf(“Enter the size of an array: “);
scanf(“%d”,&n);
printf(“\nEnter %d elements: ”, n);
for( i = 0; i < n; i++)
scanf(“%d”,&arr[i]);
printf(“\nEnter item to be search: ”);
scanf(“%d”,&item);
for( i = 0 ; i < n; i++)
{
if( arr[i] == item)
{
flag = 1;
break;
}
}
if( flag == 1)
printf(“\nitem is present at %d location”, i);
else
printf(“\nitem is not present in the array”);
return 0;
}
Subject Teacher: Bhagirath Singh Chauhan # 9829275869 Page No.: 14
PCE Unit – 3: Programming With C 151FY3-06
Example: Write a program to implement bubble sort in C language.
#include <stdio.h>
int main()
{
int i, j, temp;
int arr[5] = { 10, 32, 30, 12, 28 };
printf(“\nBefore sorting array elements are:\n”);
for ( i = 0; i < 5; i++)
printf(“%4d”, arr[i]);
for ( i = 0; i < 5; i++)
{
for( j = i + 1; j < n; j++)
{
If ( arr[i] > arr[j] )
{
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
printf(“\nAfter sorting array elements are:\n”);
for ( i = 0; i < 5; i++)
printf(“%4d”, arr[i]);
return 0;
}
Two-Dimensional Array
The 2D array can be defined as an array of arrays. The two-dimensional (2-D) array is
also called a matrix. C allows to define table (matrix) of items by using two-dimensional
arrays. Each dimension of the array is indexed from zero to its maximum size minus one.
Two-dimensional arrays are declared as follows:
Type arr_name [rows] [columns];
Example: int table[2][3];
We think of this table as a matrix consisting of two rows and three columns.
Initialization of Two-Dimensional Arrays
As like the one-dimensional array, two-dimensional arrays may be initialized by following
their declaration with a list of initial values enclosed in braces. For example:
int table[2][3] = { 2, 4, 6, 8, 10, 12}; or
int table[2][3] = { {2, 4, 6}, {8, 10, 12} };
Example:
#include <stdio.h>
int main()
{
int i, j;
Subject Teacher: Bhagirath Singh Chauhan # 9829275869 Page No.: 15
PCE Unit – 3: Programming With C 151FY3-06
int arr[3][3] = { {1,2,3}, {4,5,6}, {7,8,9} };
printf(“\nArray elements are:\n”);
for ( i =0; i < 3; i++)
{
printf(“\n”);
for (j = 0; j < 3; j++)
{
printf(“%4d”, arr[i][j]);
}//end of inner loop
}//end of outer loop
return 0;
}
Memory Layout
The subscripts in the definition of a two-dimensional array represent rows and columns.
This format maps the way that data elements are laid out in the memory. The elements of
all arrays are stored contiguously in increasing memory location, essentially in a single
list. If we consider the memory as a row by bytes, with the lowest address on the left and
the highest address on the right, a simple array will be stored in memory with the first
element at the left end and the last element at the right end. Similarly, a two-dimensional
array is stored “row-wise”, starting from the first row and ending with the last row, treating
each row like a simple array.
Multi-Dimensional Arrays
C allows arrays of three or more dimensions. The exact limit is determined by the
compiler. The general form of a multi-dimensional array is:
Type arr_name[s1][s2][s3];
Where s1, s2 and s3 are the size of the dimension. For example:
int report[2][2][3];
Static and Dynamic Arrays
An array created at compile time by specifying size in the source code has a fixed size
and cannot be modified at run time. The process of allocating memory at compile time is
known as static memory allocation and the arrays that receive static memory allocation
are called static arrays.
In C it is possible to allocate memory to arrays at run time. This feature is known as
dynamic memory allocation and the array created at run time are called dynamic
arrays. Dynamic arrays are created using pointer variables and memory management
functions malloc, calloc and realloc.
Subject Teacher: Bhagirath Singh Chauhan # 9829275869 Page No.: 16
PCE Unit – 3: Programming With C 151FY3-06
String-Handling Functions
The C library supports a large number of string-handling functions that can be used to
carry out many of the string manipulations. Following are the most commonly used string-
handling functions:
strlen() Function
This function counts and returns the number of characters in a string. It takes the form:
len = strlen(str);
Where len is an integer variable, which receives the value of the length of the string str.
The argument may be a string constant. For example:
printf( “Total characters = %d”, strlen(“Bhagirath”) );
will print “Total characters = 9”.
strcpy() Function
The strcpy function works almost like a string-assignment operator. It takes the following
form:
strcpy( str1, str2);
and assigns the contents of str2 to str1. str2 may be a character array variable or a string
constant. For example, the statement
strcpy(name, “Bhagirath”);
will assign the string “Bhagirath” to the string variable name.
strcat() Function
The strcat function joins two strings together. It takes the following form:
strcat (str1, str2);
str1 and str2 are character arrays. When the function strcat is executed, str2 is
appended to str1. The string at str2 remains unchanged. For example:
strcpy(name, “Bhagirath”);
strcat(name, “Singh”);
strcmp() Function
The strcmp function compares two strings identified by the arguments and has a value 0 if
they are equal. It they are not, it has the numeric difference between the first nonmatching
characters in the strings. It takes the form:
strcmp (str1, str2 );
str1 and str2 may be string variables or string constants. Examples are:
strcmp(name1, name2);
strcmp(name, “Bhagirath”);
Subject Teacher: Bhagirath Singh Chauhan # 9829275869 Page No.: 17