C Programming: Control Statements & Arrays
C Programming: Control Statements & Arrays
UNIT-II
CONTROL STATEMENTS & ARRAYS
STATEMENTS IN C
A statement causes an action to be performed by the program. It translates directly into one or
more executable computer instructions.
C defines several types of statements.
Types of Statements
Statements in C are categorized into following types-
[Link]/Conditional Statement/Decision Making Statements - They decide the flow of
statements on based on evaluation of results of conditions. if - else and switch statements come
under this category.
2. Looping Statements/Iterative Statements- They repeat the set of statements based on the given
condition. For, While and do-while comes under this category.
Decision Making Statements/ Selection/Conditional Statement
In c programming language, the program execution flow is, line by line from top to bottom.
That means the c program is executed line by line from the main method. But this type of execution
flow may not be suitable for all the program solutions. Sometimes, we make some decisions or we
may skip the execution of one or more lines of code. Consider a situation, where we write a
program to check whether a student has passed or failed in a particular subject. Here, we need to
check whether the marks are greater than the pass marks or not. If marks are greater, then we
take the decision that the student has passed otherwise failed. To solve such kind of problems in c
we use the statements called decision making statements.
Decision making statements are the statements that are used to verify a given condition and decides
whether a block of statements gets executed or not based on the condition result.
In c programming language, there are two Selection statements they are as follows...
1. if statement
2. switch statement
if statement in c
In c, if statement is used to make decisions based on a condition. The if statement verifies the given
condition and decides whether a block of statements are executed or not based on the condition
result. In c, if statement is classified into four types as follows...
1. Simple if statement
2. if - else statement
3. Nested if statement
4. if-else-if statement (if-else ladder)
Simple if statement
Simple if statement is used to verify the given condition and executes the block of statements
based on the condition result. The simple if statement evaluates specified condition. If it is TRUE,
it executes the next statement or block of statements. If the condition is FALSE, it skips the
execution of the next statement or block of statements. The general syntax and execution flow of
the simple if statement is as follows...
Simple if statement is used when we have only one option that is executed or skipped based on a
condition.
Example Program | Test whether given number is divisible by 5.
#include <stdio.h>
void main(){
int n ;
printf("Enter any integer number: ") ;
scanf("%d", &n) ;
if ( n%5 == 0 )
printf("Given number is divisible by 5\n") ;
printf("statement does not belong to if!!!") ;
}
Output 1:
Enter any integer number: 100
Given number is divisible by 5
statement does not belong to if!!!
Output 2:
Enter any integer number: 99
statement does not belong to if!!!
if - else statement
The if - else statement is used to verify the given condition and executes only one out of the two
blocks of statements based on the condition result. The if-else statement evaluates the specified
condition. If it is TRUE, it executes a block of statements (True block). If the condition is FALSE, it
executes another block of statements (False block). The general syntax and execution flow of the
if-else statement is as follows...
The if-else statement is used when we have two options and only one option has to be executed
based on a condition result (TRUE or FALSE).
Example Program | Test whether given number is even or odd.
#include <stdio.h>
void main(){
int n ;
printf("Enter any integer number: ") ;
scanf("%d", &n) ;
if ( n%2 == 0 )
printf("Given number is EVEN\n") ;
else
printf("Given number is ODD\n") ;
}
Output 1:
Enter any integer number: 100
Given number is EVEN
Output 2:
Enter any integer number: 99
Given number is ODD
Nested if statement
Writing an if statement inside another if statement is called nested if statement. The general syntax
of the nested if statement is as follows...
In the above type first the condition checks, if the condition is true then it enter into the sub
condition and executes the statement of true part of sub condition, if the condition is true then the
statements are executed, if the condition fails then it enters into the else block, and executes the
statements in else part and follows the same process for the remaining statements till the main if
statement closes.
Nested if means if we specify an if statement in another if statement repeatedly.
#include <stdio.h>
void main(){
int a,b,c ;
printf("Enter any 3 integer numbers: \n") ;
scanf("%d%d%d%d", &a,&b,&c) ;
if ( a>b ){
if(a>c)
printf("%d is greatest Number\n",a) ;
else
printf("%d is greatest Number\n",c);
}
else
{
If(b>c)
printf("%d is greatest Number\n",b);
else
printf("%d is greatest Number\n",c)
}
}
Output 1:
Enter any 3 integer numbers: 55 66 25
66 is greatest number
Output 2:
Enter any 3 integer numbers: 15 68 125
125 is greatest number
if - else - if statement (if-else ladder)
Writing an if statement inside else of an if statement is called if - else - if statement. The general
syntax of the if-else-if statement is as follows...
In the above type first the condition checks, if the condition is true then it executes the statement
of true part, if the condition fails the it enters into the else block, in else there is another if
statement, it also checks the condition in else block and if the condition true executes the true part
or else follow the same process for the rest.
else – if ladder means if we occur more conditions on else part of each if statement repeatedly is
called else – if ladder.
Example
/* Demonstration of else – if ladder*/
main( )
{
float avg;
printf ( "Enter your average marks " ) ;
scanf ( "%f", &avg ) ;
if ( avg>=80 )
printf ( "\nYou got Distinction”);
else if (avg>=70)
The switch statement contains one or more number of cases and each case has a value associated
with it. At first switch statement compares the first case value with the switchValue, if it gets
matched the execution starts from the first case. If it doesn't match the switch statement compares
the second case value with the switchValue and if it is matched the execution starts from the
second case. This process continues until it finds a match. If no case value matches with the
switchValue specified in the switch statement, then a special case called default is executed.
When a case value matches with the switchValue, the execution starts from that particular case.
This execution flow continues with next case statements also. To avoid this, we use "break"
statement at the end of each case. That means the break statement is used to terminate the switch
statement. However, it is optional.
Example Program | Display pressed digit in words.
#include <stdio.h>
#include<conio.h>
void main(){
int n ;
printf("Enter any digit: ") ;
scanf("%d", &n) ;
switch( n ){
case 0: printf("ZERO") ;
break ;
case 1: printf("ONE") ;
break ;
case 2: printf("TWO") ;
break ;
case 3: printf("THREE") ;
break ;
case 4: printf("FOUR") ;
break ;
case 5: printf("FIVE") ;
break ;
case 6: printf("SIX") ;
break ;
case 7: printf("SEVEN") ;
break ;
case 8: printf("EIGHT") ;
break ;
case 9: printf("NINE") ;
break ;
default: printf("Not a Digit") ;
}
}
Output 1:
Enter any digit: 5
FIVE
Output 2:
The looping statements are used to execute a single statement or block of statements
repeatedly until the given condition is FALSE.
There are three methods by way of which we can repeat a part of program. They are:
1. Using a while statement
2. Using a for statement
3. Using a do-while statement
while Statement
The while statement is used to execute a single statement or block of statements repeatedly as
long as the given condition is TRUE. The while statement is also known as Entry control looping
statement. The while statement has the following syntax...
At first, the given condition is evaluated. If the condition is TRUE, the single statement or block of
statements gets executed. Once the execution gets completed the condition is evaluated again. If it
is TRUE, again the same statements get executed. The same process is repeated until the condition
is evaluated to FALSE. Whenever the condition is evaluated to FALSE, the execution control moves
out of the while block.
Example Program | Program to display even numbers up to 10.
#include <stdio.h>
void main(){
int n = 0;
printf("Even numbers upto 10\n");
while( n <= 10 )
{
if( n%2 == 0)
printf("%d\t", n) ;
n++ ;
}
}
Output 1:
Even numbers upto 10
0 2 4 6 8 10
Most Important Points to Be Remembered
When we use while statement, we must follow the following...
• while is a keyword so it must be used only in lower case letters.
• If the condition contains variable, it must be assigned a value before it is used.
• The value of the variable used in condition must be modified according to the requirement
inside the while block.
• In while statement, the condition may be a direct integer value, a variable or a condition.
• A while statement can be an empty statement.
do-while Statement
The do-while statement is used to execute a single statement or block of statements repeatedly as
long as given the condition is TRUE. The do-while statement is also known as Exit control looping
statement. The do-while statement has the following syntax...
Output 1:
Even numbers up to 10
0 2 4 6 8 10
Most Important Points to Be Remembered
When we use do-while statement, we must follow the following...
• Both do and while are keywords so they must be used only in lower case letters.
• If the condition contains variable, it must be assigned a value before it is used.
• The value of the variable used in condition must be modified according to the requirement
inside the do block.
• In do-while statement the condition may be, a direct integer value, a variable or a
condition.
• A do-while statement can be an empty statement.
• In do-while, the block of statements are executed at least once.
for Statement
The for statement is used to execute a single statement or a block of statements repeatedly as long
as the given condition is TRUE. The for statement has the following syntax and execution flow
diagram...
Enter Y / N: Y
Okay!!! Repeat again!!!
Enter Y / N: N Okay !!! Breaking the loop!!!
continue statement
The continue statement is used to move the program execution control to the beginning of
looping statement. When 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...
}
else
{
printf("You have entered ODD number!!! Bye!!!");
exit(0);
}
}
}
Output
Enter any integer numbers: 50
Entered number is EVEN!!! Try another number!!!
Enter any integer numbers: 100
Entered number is EVEN!!! Try another number!!!
Enter any integer numbers: 10
Entered number is EVEN!!! Try another number!!!
Enter any integer number: 15
You have entered ODD number!!! Bye!!!
goto statement
The goto statement is used to jump from one line to another line in the program.
Using goto statement we can jump from top to bottom or bottom to top. To jump from one line to
another line, the goto statement requires a lable. Lable is a name given to the instruction or line
in the program. When we use goto statement in the program, the execution control directly jumps
to the line with specified lable.
Example Program for goto statement.
#include <stdio.h>
#include<conio.h>
void main(){
printf("We are at first printf statement!!!\n") ;
goto last ;
printf("We are at second printf statement!!!\n") ;
printf("We are at third printf statement!!!\n") ;
last: printf("We are at last printf statement!!!\n") ;
}
Output
We are at first printf statement!!!
ARRAYS
Basic Concepts
When we work with large number of data values we need that many number of different
variables. As the number of variables increases, the complexity of the program also increases and
so the programmers get confused with the variable names. There may be situations where we need
to work with large number of similar data values. To make this work easier, C programming
language provides a concept called "Array".
An array is a collection of similar data items, that are stored under a common name.
An array is a collection of similar data items stored in continuous memory locations with single name.
A value in an array is identified by index or subscript enclosed in square brackets with array
name. The individual data items can be integers, floating point numbers, characters and so on, but
they must be the same type and same storage class. Each array element is referred by specifying the
array name with the subscript, each subscript enclosed in square brackets and each subscript must
be a non-negative integer.
For ‘5’ elements array ‘a’ and the elements are
a[0], a[1],a[2],a[3],a[4]
Array Characteristics
An array represents a group of related data.
An array has two distinct characteristics:
An array is ordered: data is grouped sequentially. In other words, here is element 0, element 1,
etc.
An array is homogenous: every value within the array must share the same data type. In other
words, an int array can only hold ints, not doubles.
HOW TO CREATE AN ARRAY
Before we create an array, we need to decide on two properties:
Element type: what kind of data will your array hold? ints, double, chars? Remember, we can
only choose one type.
Array size: how many elements will your array contain?
When we initially write our program, we must pick an array size. An array will stay this size
throughout the execution of the program. In other words, we can change the size of an array at
compile time, but cannot change it at run-time.
Using Arrays in C:
C provides for two different array types, fixed-length array and variable-length array. In a fixed
length array, the size of the array is known when the program is written. In a variable length array,
the size of the array is not known until the program is run. Both types consist of the following three
array categories.
Arrays can be classified into
a) One Dimensional Arrays
b) Two Dimensional Arrays
c) Multi-Dimensional Arrays
One-Dimensional Array: The collection of data items can be stored under a one variable name
using only one subscript, such a variable is called the one-dimensional array.
Array Declaration: Arrays are declared in the same manner as an ordinary variable
except that each array name must have the size of the array i.e., number of elements accommodated
in that array.
int a[5];
where ‘a’ is the name of the array with 5 subscripts of integer data types and the computer reserves
five storage locations as shown below.
a
a[0] a[1] a[2] a[3] a[4]
Declaration of an Array
In c programming language, when we want to create an array we must know the datatype of values
to be stored in that array and also the number of values to be stored in that array.
Here, the compiler allocates 6 bytes of continuous memory locations with single name 'a' and tells
the compiler to store three different integer values (each in 2 bytes of memory) into that 6 bytes of
memory. For the above declaration the memory is organized as follows...
In the above memory allocation, all the three memory locations has a common name 'a'. So the
accession of individual memory location is not possible directly. Hence compiler not only allocates
the memory but also assigns a numerical reference value to every individual memory location of an
array. This reference number is called as "Index" or "subscript" or "indices". Index values for the
above example is as follows...
For example, if we want to assign a value to the second memory location of above array 'a', we use
the following statement...
a [1] = 100 ;
The result of above assignment statement is as follows...
In the above example declaration, size of the array 'marks' is 6 and the size of the
array 'studentName' is 16. This is because in case of character array, compiler stores one exttra
character called \0 (NULL) at the end.
#include <stdio.h>
int main ()
{
int n[ 10 ]; /* n is an array of 10 integers */
int i,j; /* initialize elements of array n to 0 */
for ( i = 0; i < 10; i++ )
{
n[ i ] = i + 100; /* set element at location i to i + 100
*/
}
/* output each array element's value */
for (j = 0; j < 10; j++ )
{
printf("Element[%d] = %d\n", j, n[j] );
}
return 0;
}
Output
Element[0] = 100
Element[1] = 101
Element[2] = 102
Element[3] = 103
Element[4] = 104
Element[5] = 105
Element[6] = 106
Element[7] = 107
Element[8] = 108
Element[9] = 109
Features of Arrays:
• An array is a derived data type. It is used to represent a collection of elements of the
same data type.
• The elements can be accessed with base address(index) and the subscripts define the
position of the element
• In array the elements are stored in continuous memory location. The starting memory
location is represented by the array name and it is known as the base address of the
array.
• It is easier to refer the array elements by simply incrementing the value of the subscript.
Example Program to read and print an array of size 5.
#include<stdio.h>
void main()
{
int i,a[5];
printf(“enter the elements”);
for(i=0;i<5;i++)
scanf(“%d”,&a[i]);
for(i=0;i<5;i++)
printf(“%d”,a[i]);
}
Output
Enter the elements
50 20 32 69 45
50 20 32 69 45
This is an array of size 3 names [3] whose elements are arrays of size 4 [4] whose elements are
characters char.
Declaration of Two-Dimensional Array
The above figure shows the representation of elements in the two- dimensional array
Example,
int names[3][4];
in the above declaration
int(DataType) specifies type of element in each slot names(arrayName) specifies name of the array
[3](rows) specifies number of rows [4](cols) specifies number of columns.
int matrix_A [2][3] ;
The above declaration of two-dimensional array reserves 6 continuous memory locations of 2 bytes
each in the form of 2 rows and 3 columns.
Initialization of Two-Dimensional Array
We use the following general syntax for declaring and initializing a two-dimensional array with
specific number of rows and columns with initial values.
datatype arrayName [rows][colmns] = {{r1c1value, r1c2value, ...},{r2c1, r2c2,...}...} ;
Example
int matrix_A [2][3] = { {1, 2, 3},{4, 5, 6} } ;
The above declaration of two-dimensional array reserves 6 continuous memory locations of
2 bytes each in the form of 2 rows and 3 columns. And the first row is initialized with values 1, 2 &
3 and second row is initialized with values 4, 5 & 6.
We can also initialize as follows...
int matrix_A [2][3] = {
{1, 2, 3},
{4, 5, 6}
};
Accessing Individual Elements of Two-Dimensional Array
In c programming language, to access elements of a two-dimensional array we use array
name followed by row index value and column index value of the element that to be accessed. Here
SHIVAKUMAR DEPT. OF IT, CBIT 24
STATEMENTS IN C
the row and column index values must be enclosed in separate square braces. In case of two-
dimensional array, the compiler assigns separate index values for rows and columns.
We use the following general syntax to access the individual elements of a two-dimensional array...
arrayName [ rowIndex ] [ columnIndex ]
Example
matrix_A [0][1] = 10;
In the above statement, the element with row index 0 and column index 1 of matrix_A array is
assigned with value 10.
//C Program to read and print the elements of the two dimensional array.
/* Fill 2-d array, print out values, sum the array. */
#include <stdio.h>
#define M 3 /* Number of rows */
#define N 4 /* Number of columns */
void main( )
{
int a [ M ] [ N ], i, j, sum = 0;
for ( i = 0; i < M; ++i ) /* fill the array */
for (j = 0; j < N, ++j )
scanf (%d”, &a [i] [j]);
for ( i = 0; i < M; ++i )
{ /* print array values */
for (j = 0; j < N, ++j )
printf(“a [ %d ] [ %d ] = %d “, i, j, a[ i ] [ j ]);
printf (“\n”);
}
for ( i = 0; i < M; ++i ) /* sum the array */
for (j = 0; j < N, ++j )
sum += a[ i ] [ j ];
printf(“\nsum = %d\n\n”);;
}
Applications of Arrays in C
In c programming language, arrays are used in wide range of applications. Few of them are as
follows...
Arrays are used to Store List of values
In c programming language, single dimensional arrays are used to store list of values of same
datatype. In other words, single dimensional arrays are used to store a row of values. In single
dimensional array data is stored in linear form.
Arrays are used to Perform Matrix Operations
We use two dimensional arrays to create matrix. We can perform various operations on matrices
using two dimensional arrays.
Arrays are used to implement Search Algorithms
We use single dimensional arrays to implement search algorithms like ...
1. Linear Search
2. Binary Search
Arrays are used to implement Sorting Algorithms
We use single dimensional arrays to implement sorting algorithms like ...
1. Insertion Sort
2. Bubble Sort
3. Selection Sort
4. Quick Sort
5. Merge Sort, etc.,
Arrays are used to implement Data structures
We use single dimensional arrays to implement data structures like...
1. Stack Using Arrays
2. Queue Using Arrays
Arrays are also used to implement CPU Scheduling Algorithms