Fundamentals of C Programming Module 2
MODULE -2
Iterative control structures and arrays:Control structures - if, if-else,
nested if statement, and switch.
Looping structures - while, do-while, for, nested loops,
Unconditional control statements-break, continue, goto.
Array operations- insertion, deletion, searching, sorting. Two
dimensional array declaration - two dimensional array operations-
Matrix manipulations (addition, multiplication etc)
Page 1
Fundamentals of C Programming Module 2
“C” SUPPORTS MAINLY THREE TYPES OF CONTROL STATEMENTS.
1. Decision making statements
a) Simple if Statement
b) if – else Statement
c) Nested if-else statement
d) else – if Ladder
e) switch statement
2. Loop control statements
a) for Loop
b) while Loop
c) do-while Loop
3. Unconditional control statements
a) goto Statement
b) break Statement
c) continue Statement
Decision Making with if Statement
The if statement is a powerful decision making statement and is used to
control the flow of execution of statements.
It is basically a two way decision statement and is used in conjunction with
an expression.
if(test expression)
It allows the computer to evaluate the expression first and then depending
on whether the value of the expression is true(or non-zero) or false(zero),it
transfers the control to a particular statement.
Page 2
Fundamentals of C Programming Module 2
Two-way branching
Simple if statement
The general form of a simple if statement is
if(test expression)
{
statement-block;
}
statement-x;
statement block may be a single statement or a group of statements.
If the test expression is true the statement block will be executed,
otherwise the statement block will be skipped and the execution will jump
to the statement-x .
Eg:
if(category==SPORTS)
{
marks=marks + bonus_marks;
}
printf(“%f”,marks);
The program tests the type of category of the student, if the student belongs to
the SPORTS category, then additional bonus_marks are added to his marks before
they are printed. For others bonus_marks are not added.
Page 3
Fundamentals of C Programming Module 2
If-else statement
The if else statement is an extension of the simple if statement.
The general form is
if(test expression)
{
True-block Statements
}
else
{
False-block Statements
}
Statement-x;
If the test expression is true, then the true-block statements immediately
following the if statements are executed, otherwise the false-block
statements are executed.
Then the control is transferred subsequently to the statement-x.
Page 4
Fundamentals of C Programming Module 2
Write a C program to check whether an integer is odd or even
#include <stdio.h>
int main()
{
int number;
printf("Enter an integer: ");
scanf("%d", &number);
// True if the remainder is 0
if (number%2 == 0)
{
printf("%d is an even integer.",number);
}
else
{
Page 5
Fundamentals of C Programming Module 2
printf("%d is an odd integer.",number);
}
return 0;
}
Output
Enter an integer: 7
7 is an odd integer.
When the user enters 7, the test expression number%2==0 is evaluated to false.
Hence, the statement inside the body of else is executed.
Nested if -else statement
A nested if-else statement is an if statement inside another if statement.
Syntax
If the condition-1 is false, the statement-3 will be executed ; otherwise it
continues to perform the second test.
Page 6
Fundamentals of C Programming Module 2
If the condition-2 is true, the statement-1 will be evaluated; otherwise the
satement-2 is evaluated and then the control is transferred to the
statement-x.
Else- if Ladder
Page 7
Fundamentals of C Programming Module 2
This construct is known as else if ladder.
The conditions are evaluated from the top(of the ladder) downwards.
As soon as a 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 n conditions become false ,then the final else containing the
default statement will be executed.
Write a C Program to Find Largest of Two numbers
#include <stdio.h>
int main()
{
int num1, num2;
printf("Please Enter Two different values\n");
scanf("%d %d", &num1, &num2);
if(num1 > num2)
{
printf("%d is Largest\n", num1);
}
else if (num2 > num1)
{
printf("%d is Largest\n", num2);
}
else
{
printf("Both are Equal\n");
}
return 0;
}
1. First, if condition checks whether a is greater than b. If this condition is True,
then a is greater than b.
2. The first Else if condition checks whether b is greater than a. If this condition
is True, then b is greater than a.
3. If the above two conditions fail, it means they are equal.
Page 8
Fundamentals of C Programming Module 2
Please Enter Two different values
20
10
20 is Largest
Switch Statement
C has a built in multiway decision statement known as a switch.
The switch statement tests the values 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
Syntax
switch(expression)
{
case value1:
statement_1;
break;
case value2:
statement_2;
break;
.
.
.
case value_n:
statement_n;
break;
default:
default_statement;
break;
}
The expression is an integer expression or characters.
Page 9
Fundamentals of C Programming Module 2
Value1,value2,………,value n are known as case labels. Each of these values
should be unique within a switch statement.
Case labels end with semicolon(:)
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.
Example
#include <stdio.h>
int main() {
int num = 8;
switch (num)
Page 10
Fundamentals of C Programming Module 2
case 7:
printf("Value is 7");
break;
case 8:
printf("Value is 8");
break;
case 9:
printf("Value is 9");
break;
default:
printf("Out of range");
break;
}
return 0;
}
Loop Control Statements
Looping Statements in C execute the sequence of statements many times
until the stated condition becomes false.
A loop in C consists of two parts, a body of a loop and a control statement.
The control statement is a combination of some conditions that direct the
body of the loop to execute until the specified condition becomes false.
The purpose of the C loop is to repeat the same code a number of times.
Types of Loops in C
Depending upon the position of a control statement in a program, looping
statement in C is classified into two types:
1. Entry controlled loop
2. Exit controlled loop
In an entry control loop in C, a condition is checked before executing the body of
a loop.
In an exit controlled loop, a condition is checked after executing the body of a
loop.
Page 11
Fundamentals of C Programming Module 2
C’ programming language provides us with three types of loop constructs:
1. while loop
2. do-while loop
3. for loop
While Loop in C
Syntax
while (condition)
{
statements;
}
It is an entry-controlled loop.
In while loop, a condition is evaluated before processing a body of the loop.
If condition is true body of a loop is executed.
After the body of a loop is executed then control again goes back at the
beginning, and the condition is checked if it is true, the same process is
executed until the condition becomes false.
Once the condition becomes false, the control goes out of the loop.
After exiting the loop, the control goes to the statements which are
immediately after the loop.
The body of a loop can contain more than one statement. If it contains only
one statement, then the curly braces are not compulsory.
In while loop, if the condition is not true, then the body of a loop will not be
executed, not even once.
Write a C program to display numbers from 1 to 10 using while loop
#include<stdio.h>
int main()
{
int num=1; //initializing the variable
while(num<=10) //while loop with condition
{
printf("%d\n",num);
Page 12
Fundamentals of C Programming Module 2
num++; //incrementing operation
}
return 0;
}
Output:
1
2
3
4
5
6
7
8
9
10
Do-While loop in C
Syntax
do
{
body of loop
} while (expression);
In while loop, the body is executed if and only if the condition is true.
In do-while loop, the body of a loop is always executed at least once. After
the body is executed, then it checks the condition. If the condition is true,
then it will again execute the body of a loop otherwise control is
transferred out of the loop.
It is an exit-controlled Loop
Similar to the while loop, once the control goes out of the loop the
statements which are immediately after the loop is executed.
Page 13
Fundamentals of C Programming Module 2
Write a C program to print a table of number 2 using do-while loop
#include<stdio.h>
int main()
{
int num=1; //initializing the variable
do //do-while loop
{
printf("%d\n",2*num);
num++; //incrementing operation
}while(num<=10);
return 0;
}
Output:
2
4
6
8
10
12
14
16
18
20
For loop in C
A for loop is a more efficient loop structure in ‘C’ programming.
Syntax of For Loop in C
for (initial value; test-condition; incrementation or decrementation )
{
statements;
}
The initial value of the for loop is performed only once.
Page 14
Fundamentals of C Programming Module 2
The value of control variable is tested using the test condition. The test-
condition is a relational expression. If the condition is true,the body of loop
is executed;otherwise the loop is terminated and the execution continues
with the statements immediately following the loop.
It is an entry controlled loop.
The incrementation/decrementation increases (or decreases) the counter
by a set value.
C Program to print first n natural numbers using for loop
#include<stdio.h>
void main()
{
int i, n;
printf("Enter the value of n\t");
scanf("%d", &n);
printf("Printing natural numbers from 1 to %d\n", n);
for(i = 1; i <= n; i++)
printf("%d\t", i);
}
Output
Enter the value of n 8
Printing natural numbers from 1 to 8
1 2 3 4 5 6 7 8
C Program to print product of first 5 natural numbers using for loop
#include<stdio.h>
void main()
{
int i, p;
for(i = 1,p = 1; i<=5;i++)
{
p=p*i;
Page 15
Fundamentals of C Programming Module 2
}
printf(“Product of first 5 natural numbers is %d”,p);
Page 16
Fundamentals of C Programming Module 2
Unconditional control statements
In c, there are control statements that do not need any condition to control the
program execution flow. These control statements are called as unconditional
control statements. C programming language provides the following
unconditional control statements...
break
continue
goto
break statement
In C, the break statement is used to perform the following two things...
1. break statement is used to terminate the switch case statement
2. break statement is also used to terminate looping statements like while,
do-while and for.
When a break statement is encountered inside the switch case statement,
the execution control moves out of the switch statement directly.
When the break statement is encountered inside the looping statement,
the execution control moves out of the looping statements.
The break statement execution is as shown in the following figure.
Page 17
Fundamentals of C Programming Module 2
continue statement
The continue statement is used to move the program execution control to
the beginning of the looping statement.
When the continue statement is encountered in a looping statement, the
execution control skips the rest of the statements in the looping block and
directly jumps to the beginning of the loop.
The continue statement can be used with looping statements like while,
do-while and for.
When we use continue statement with while and do-while statements the
execution control directly jumps to the condition.
When we use continue statement with for statement the execution control
directly jumps to the modification portion (increment/decrement/any
modification) of the for loop.
The continue statement execution is as shown in the following figure.
Goto statement
C-language provides goto statement to transfer control unconditionally to
other part of the program.
goto statement requires a label to determine where to transfer the
control.
Page 18
Fundamentals of C Programming Module 2
A label must end with colon (:)
We can use any valid name as a label similar to variable name.
When compiler encounters goto statement with a label name then, it
transfers the control to the location where label has been defined in the
program.
When goto statement is placed after the label, control jumps backward
direction and some statement are repeated. Such type of goto jump is
called backward jump.
When goto statement is placed before the label in the program, control
transfers to the label and some statements are skipped. Such type of jump
is called forward jump.
Page 19
Fundamentals of C Programming Module 2
ARRAYS
An array is a collection of variables of the same data type that are
referenced by a common name.
The array name acts as a pointer to the zeroth element of the array.
TYPE OF ARRAYS
One dimensional arrays
Two- dimensional arrays
Multi- dimensional arrays
One dimensional arrays
Syntax of Array Declaration
data_type array_name [size];
o datatype specifies the data type of the array. It can be any valid data type
in C programming language, such as int, float, char, double, etc.
o array_name is the name of the array
o arraysize specifies the number of elements in the array. It must be
a positive integer value.
Eg: int Arr [5];
Page 20
Fundamentals of C Programming Module 2
An array is a collection of similar elements.
The first element in the array is numbered 0, so the last element is 1
less than the size of the array.
An array is also known as a subscripted variable. The element numbers
in [ ] are called index or subscript.
C language treats character strings simply as arrays of characters. The size in a
character string represents the maximum number of characters that the string
can hold.
Eg char name[10];
Suppose we read the following string constant into the string variable name.
“Character”
Page 21
Fundamentals of C Programming Module 2
When the compiler sees a character string,it terminates it with an
additional null character.
While declaring character arrays, we must allow one extra element space
for null character(\0).
Entering Data into an Array
Here is the section of code that places data into an array:
for ( i = 0 ; i <= 49 ; i++ )
{
printf ( "\n Enter marks " ) ;
scanf ( "%d", &marks[i] ) ;
}
The first time through the loop, i has a value 0, so the scanf ( ) function will
cause the value typed to be stored in the array element marks [0], the first
element of the array. This process will be repeated until i become 49
Reading Data from an Array
The for loop is much the same, but now the body of the loop causes each
student’s marks to be added to a running total stored in a variable called
sum. When all the marks have been added up, the result is divided by 50,
the number of students, to get the average.
for ( i = 0 ; i <= 49 ; i++ )
{
sum = sum + marks[i] ;
}
avg = sum / 50 ;
printf ( "\n Average marks = %d", avg ) ;
INITIALIZATION OF 1D ARRAY
An array can be initialized at either of the following stages.
• At compile time.
• At run time.
Compile time initialization:
Syntax
type array_name[size]= {list of values};
Eg: int number [3] = {9, 5, 2};
float total [5] = {0.0, 15.75,-10.9};
Page 22
Fundamentals of C Programming Module 2
The size may be omitted. In such cases, the compiler allocates enough
space for all initialized elements.
Eg: int counter [ ] = {1, 1, 1, 1};
Character arrays may be initialized in a similar manner.
Eg: char name [ ] = {‘j’,’o’,’h’,’n’,’\0’};
If we have more initializers than the declared size, the compiler
will produce an error. That is the statement
int number [3] = {10, 20, 30, 40}; will not work. It is illegal in C.
Run time initialization:
We can use scanf ( ) to initialize an array.
int x [25],i;
for (i=0;i<25;i++)
scanf (“%d”,&x[i]);
Array Operations
An array supports the following operations:
Traversal
Insertion
Deletion
Search
Sorting
Traversal:
Visiting every element of an array once is known as traversing the array.
Insertion:
An element can be inserted in an array at a specific position.
For this operation to succeed, the array must have enough capacity
Page 23
Fundamentals of C Programming Module 2
Suppose we want to add an element 10 at index 2 in the below-illustrated
array, then the elements after index 1 must get shifted to their adjacent
right to make way for a new element.
Deletion:
An element at a specified position can be deleted, creating a void that needs to
be fixed by shifting all the elements to their adjacent left, as illustrated in the
figure below.
Page 24
Fundamentals of C Programming Module 2
Searching:
Searching can be done by traversing the array until the element to be searched is
found.
Sorting:
Sorting means arranging an array in an orderly fashion (ascending or descending).
Page 25
Fundamentals of C Programming Module 2
Page 26
Fundamentals of C Programming Module 2
Page 27