PPS Unit-2
PPS Unit-2
CONTROL STATEMENTS
ARRAYS
STRINGS
Control Statements, Arrays, and Strings C Programming
Decision Making Statements / Control Statements
In C, until so far, in all the programs, the control is flowing from one instruction to next instruction. Such flow
of control from one instruction to next instruction is known as sequential flow of control. But, in most of the C
programs, while writing the logic, the programmer might want to skip some instructions or repeat a set of
instructions again and again. This is can be called as non-sequential flow of control. The statements in C, which
allows the programmers to make such decisions, are known as decision making statements or control statements.
In C, there are two types of decision making statements. One type is used to branch the control into
different ways and the other type is used to repeat a set of instructions again and again. The two types of decision
making statements are:
1. Selection statements or Branching statements
2. Looping statements
if Statement
The if statement allows the programmer to select a set of instructions to be executed, based on a condition.
If the condition is evaluated to true, then one set of instructions will be executed or if the condition is evaluated to
false, another set of instructions will be executed. The general from of if statement is as shown below:
if…else Statement
The if…else is a two way decision making selection statement. If the condition evaluates to true, one set of
instructions will be executed. If the condition evaluates to false, another set of instructions will be executed. The
if…else statement can be represented diagrammatically as shown below:
Nested if
The nested if can also be called as cascaded if. In nested if statement, one if statement is nested within
another if statement. A nested if statement can be used as an alternative to logical AND operator. If the condition is
evaluated to true in the first if statement, then the condition in the second if statement is evaluated and so on. The
nested if statement can be represented diagrammatically as shown below:
if(cond/expr)
{
Stmt(s);
}
else if(cond/expr)
{
Stmt(s);
}
else if(cond/expr)
{
Stmt(s);
}
….
else
{
Stmt(s);
}
Stmt(s);
As seen in the above diagram, the switch statement switches between the blocks based on the value of the
expression. Each block will have a value associated with it. The expression in the switch statement must always
reduce to an integer value. So the expression in the switch statement can be either an integer value or a character
constant or an expression which reduces to an integer value. The label for each block can be either an integer value
or a character constant.
Syntax for the switch statement is as shown below:
switch(expression)
{
case label1:
Stmt(s);
break;
case label2:
Stmt(s);
break;
case label3:
Stmt(s);
break;
…
case labelN:
Stmt(s);
break;
default:
Stmt(s);
break;
}
As seen in the above syntax, each block is represented using the case keyword and the case keyword follows with
the label of the block. In a switch statement, both the default block and the break statement are optional. If none of
the blocks are matched, then the statements in the default block are executed. Every block is ended with a break
statement. If we remove the break statement from a particular block, all the subsequent blocks are also executed
until the next break statement is encountered.
P. S. Suryateja startertutorials.com [short domain - stuts.me] 9
Control Statements, Arrays, and Strings C Programming
#include<stdio.h>
#include<conio.h>
main()
{
char ch;
printf("\nEnter a character: ");
scanf("%c",&ch);
switch(ch)
{
case 'a':
printf("Entered character is a vowel!");
break;
case 'e':
printf("Entered character is a vowel!");
break;
case 'i':
printf("Entered character is a vowel!");
break;
case 'o':
printf("Entered character is a vowel!");
break;
case 'u':
printf("Entered character is a vowel!");
break;
default:
printf("Entered character is not a vowel!");
break;
}
}
As shown in the above syntax, when the condition evaluates to true, expr1 is executed. Otherwise, if the
condition is false, expr2 is executed. The conditional operator statement can be represented diagrammatically as
shown below:
Every conditional operator statement can be converted into an if…else statement. But the vice versa is not true.
--- ---
--- ---
goto label; label:
--- ---
--- ---
label: goto label;
--- ---
--- ---
As shown in the above syntax, if the label is after the goto statement, then it is known as forward jump and if the
label is before the goto statement, it is known as backward jump.
#include<stdio.h>
#include<conio.h>
main()
{
int number;
read:
printf("\nEnter a number: ");
scanf("%d",&number);
if(number>0)
{
printf("Number is +ve\n");
}
else if(number<0)
{
printf("Number is -ve\n");
}
else
{
goto end;
P. S. Suryateja startertutorials.com [short domain - stuts.me]
12
Control Statements, Arrays, and Strings C Programming
}
goto read;
end:
printf("You entered zero!");
}
Based on the nature of the loops, the loops can be categorized into two types namely:
1. Definite loops (Ex: for)
2. Indefinite loops (Ex: while and do…while)
Definite loops: If the programmer exactly knows how many times he/she is going to repeat the set of instructions
(loop), such loops are known as definite loops.
Indefinite loops: If the programmer does not know exactly how many times he/she is going to repeat the set of
instructions (loop), such loops are known as indefinite loops.
The variable used in the condition inside of a definite loop is known as a counter and such loops are also known as
counter controlled loops. The variable used in the condition inside of a indefinite loop is known as sentinel and such
loops are also known as sentinel loops.
while Loop
In C, the while loop is an entry controlled loop. The body of the while loops is only executed when the
condition evaluates to true. If the condition evaluates to false, the body of the loop is not executed. The while loops
are generally used when there is a need for repeating a set of instructions for indefinite amount of times. The syntax
of a while loop is as shown below:
while(cond/expr)
-----
-----
-----
do
----
----
----
}while(cond/expr);
for Loop
In C, the for loop is an entry controlled loop. The for is generally used while implementing definite loops in C
programs. The for loop’s syntax is a little bit different from the other loops. In the syntax of the for loop, first the
counter is initialized, and then the condition is evaluated. If the value of the condition is true, the body of the for
loop is executed. Otherwise, the body of the loop is not executed. After the execution of the for loop’s body, the
counter is either incremented or decremented. Then the condition is evaluated again and so on. The syntax of the
for loop is as shown below:
----
----
----
break Statement
The break statement is used inside the looping statements to break the execution of the loop. When the
break statement is encountered inside the loop, the execution of the body of the loop stops and the control is given
to the next instruction after the body of the loop. The syntax of the break statement is as shown below:
continue Statement
The continue statement is used inside the looping statements to skip the execution of a set of instructions
and return the control back to the loop. When a continue statement is encountered within the body of the loop, the
statements after the continue statement are skipped and the control is passed back to the loop. The syntax of the
continue statement is as shown below:
#include<stdio.h>
#include<conio.h>
main()
{
int n1,n2;
char op,option;
clrscr();
n1 = 3, n2 = 2;
do
{
printf("Enter the operator: ");
scanf("%c",&op);
fflush(stdin);
switch(op)
{
case '+':
printf("Sum of n1 and n2 is: %d",(n1+n2));
break;
case '-':
printf("Subtracting n2 from n1 gives: %d",(n1-n2));
break;
case '*':
printf("Multiplication of n1 and n2 gives: %d",(n1*n2));
break;
case '/':
printf("Dividing n1 by n2 gives: %d",(n1/n2));
P. S. Suryateja startertutorials.com [short domain - stuts.me]
27
Control Statements, Arrays, and Strings C Programming
break;
case '%':
printf("n1 mod n2 gives: %d",(n1%n2));
break;
default:
printf("Invalid Operator!");
break;
}
printf("\n\nDo you want to proceed (y/n)?: ");
scanf("%c",&option);
fflush(stdin);
}while(option=='y');
printf("Program Terminated!");
getch();
}
Arrays
In all the programs we have done until now, to store and operate on values we have used variables. But at a
point in time, a variable can hold only a single value. For example, in the following syntax: int a = 10; we are able to
store only 10 in the variable a, which is a single value. It is normal in programming to work with a list of values or a
group of values at once. For such purposes, variables cannot be used. So, C language provides the construct array for
holding multiple values at once.
Definition: “An array is a sequential collection/group of homogeneous (same type) elements which are referred by
the same name”. The type refers to the data types like int, char, float etc. All the elements/values in the array are of
the same type (data type). We cannot store values of different data types in the same array.
Uses:
1. To maintain a list of values.
2. To maintain a table of values.
Example:
int a[10];
In the above example, int is the data type, a is the array name and size is the number of elements that we can store
in the array. So, in the above example a is an integer array, which can hold 10 integer values. All the 10 elements in
the array will be stored sequentially one after another inside the main memory (RAM). The one dimensional array
declared above will be maintained in the memory as shown below:
Example:
int a[5];
a[0] = 10;
In the above syntax, index refers to the element in the array. The index of an array always starts with zero.
So, the index values for the array a in the above example are: 0, 1, 2, 3, 4. If we want to access nth element in the
array, the index value will be n-1. For example, if we want to refer first element in the array, the index value will be
1-1=0. In, the above example, we are assigning value 10 to the first element of the array.
Note: If the array elements are not initialized, the values stored in the elements of the array will be garbage values.
Generally, there are two types of initializing an array. They are: 1) Static Initialization (at compile time) and 2)
Dynamic Initialization (at run time). In static initialization, the elements of an array are assigned values when the
program is compiled. In dynamic initialization, the elements of an array are assigned values when the program is
executed (runtime). The above way of initialization is static initialization. We can also perform static initialization in
other ways as shown below:
Or
Example:
int a[10] = {1,2,3,4,5,6,7,8,9,10};
or
int a[ ] = {1,2,3,4,5,6,7,8,9,10};
In the above example, in the first line, the size is specified as 10. But, in the second line, the size was not
specified. In such cases, the size is automatically calculated. In this example, the size is automatically computed as 10
by the compiler. The array will be represented in the memory as shown below:
In dynamic initialization, the values are assigned to the elements of the array during the execution of the
program. Let’s see the following piece of code:
int a[10], i;
for(i = 0; i < 10; i++)
{
scanf(“%d”,&a[i]);
}
P. S. Suryateja startertutorials.com [short domain - stuts.me]
33
Control Statements, Arrays, and Strings C Programming
In the above example, the user will be storing the values into the array while executing the program. Until then,
garbage values will be stored in the array.
Note: If we use braces i.e., { and }, for initializing the array, the default values for all the elements in the array will be
zero.
Programs:
/* C program to declare an integer array and initialize the elements in the array
*/
#include<stdio.h>
#include<conio.h>
main()
{
int a[5];
clrscr();
a[0] = 1;
a[1] = 2;
a[2] = 3;
a[3] = 4;
a[4] = 5;
printf("a[0]: %d\n",a[0]);
printf("a[1]: %d\n",a[1]);
printf("a[2]: %d\n",a[2]);
printf("a[3]: %d\n",a[3]);
printf("a[4]: %d",a[4]);
getch();
}
/* C program to declare an integer array and initialize the elements in the array
*/
#include<stdio.h>
#include<conio.h>
main()
{
int a[5] = {1,2,3,4,5};
P. S. Suryateja startertutorials.com [short domain - stuts.me]
34
Control Statements, Arrays, and Strings C Programming
clrscr();
printf("a[0]: %d\n",a[0]);
printf("a[1]: %d\n",a[1]);
printf("a[2]: %d\n",a[2]);
printf("a[3]: %d\n",a[3]);
printf("a[4]: %d",a[4]);
getch();
}
/* C program to declare an integer array and initialize the elements in the array
*/
#include<stdio.h>
#include<conio.h>
main()
{
int a[ ] = {5,2,1,9,10};
clrscr();
printf("a[0]: %d\n",a[0]);
printf("a[1]: %d\n",a[1]);
printf("a[2]: %d\n",a[2]);
printf("a[3]: %d\n",a[3]);
printf("a[4]: %d",a[4]);
getch();
}
type arrayname[rows][columns];
Example:
int a[3][3];
In the above example, int refers to the data type, a refers to the array name, first set of square brackets represents
the number of rows and the second set of square brackets represents the number of columns. So, our two
dimensional array contains 9 elements in total.
arrayname[rowindex][columnindex] = value;
(or)
Example:
a[0][0] = 10;
(or)
The memory representation of the two dimensional array will be as shown below:
The values will be assigned starting with the first element in the first row and so on. If insufficient values are
provided, then the remaining elements will be initialized to zero. There is another way of initializing a two
dimensional array in which we can specify the values for each row separately. We can see the example below:
int a[3][3] = {{1,1,1},{2,2,2},{3,3,3}};
P. S. Suryateja startertutorials.com [short domain - stuts.me]
41
Control Statements, Arrays, and Strings C Programming
Programs:
The size refers to the number of characters in the string. When the compiler assigns a character string to a character
array, it appends a ‘\0’ to the end of the array. So, the size of the character array should always be number of
characters plus 1.
Like numeric arrays and variables, character arrays can also be initialized when they are declared. Some of
the examples for initializing the string are as shown below:
or
If less number of characters are provided than the size of the string, the rest of the characters are initialized to ‘\0’. If
we try to assign more characters then the size of the string, compiler gives an error.
Note: The string termination character ‘\0’, is used to terminate a string. In C, there is no data type provided
available. We maintain strings using character arrays. A string is a variable length structure stored inside a fixed size
array. The size of the array is often larger than the number of characters in the string. So, the compiler must have
some means to detect the end of the string. For this purpose we use ‘\0’.
Note: If ‘\0’ is not provided then the compiler will treat the array as a normal character array. Only when we provide
the ‘\0’ character, compiler treats it as a string.
char str[10];
scanf(“%s”, str);
There is a downside of using scanf function for reading strings. The downside is, scanf cannot read strings with white
spaces. For example, if we provide “New Delhi” as the string, scanf will read only “New” and the rest of the
characters are neglected or not processed. So, to read “New Delhi”, we have to declare two character arrays and
read “New” and “Delhi” separately.
}while(ch != '\n');
line[i] = '\0';
printf("%s",line);
getch();
}
In the above program we are reading characters until a new line character (\n) is encountered. So, by using
the above approach we can read a line of text. There is a more efficient way for reading a line of text with white
spaces. We can use the gets function which is available in the stdio.h header file. The purpose of gets function is to
read a line of text from the terminal/keyboard. The usage of gets function is as shown below:
gets(arrayname);
printf(“%s”, str);
The output of the above piece of code is “hai”. The second way is to print the string character by character. For this
purpose we can use the format specifier %c for printing each character or we can use the predefined function
putchar. The usage of this function is as shown below:
putchar(ch);
In the above code, ch is the character that we want to print on the screen. By using the putchar function we can
print a line of text or string as shown below:
The last alternative for printing a string or a line of text is by using the predefined function puts. This function is
available in the stdio.h header file. By using the puts function we can rewrite the above program as shown below:
Functions Purpose
scanf, gets, getchar To read a string
printf, puts, putchar To print a string
strcat To concatenate two strings
strcmp To compare two strings
strcpy To copy one string into another string
strstr To locate a substring in the string
strlen To calculate the length of the string
strrev To reverse the given string
Note: The difference between scanf and gets is, scanf can read strings which does not contain any white spaces.
Whereas gets can read strings both without spaces and with spaces.
strcat( )
The strcat predefined function is used to concatenate/join two strings together. The syntax of the strcat
function is shown below:
strcat(string1, string2)
The strcat function accepts two parameters which are strings. The string2 parameter can be either a character array
or a string constant. The strcat function takes the content of string2 and merges it with the content in string1 and
the final result will be stored in string1. Let us see an example:
strcmp( )
The strcmp predefined function is used to compare two strings. After comparison, if the two strings are
equal, then the function returns a 0. Otherwise if the first string comes before the second string in alphabetical
As seen from the above example, the strcmp function the first letter in both the strings and since they are equal,
now it compares the second letter in both the strings, which are e and a. Since, e comes after a according to
dictionary order, the result will be 1 which means, the string hello comes after (greater than) the string hai.
strcpy( )
The strcpy function is used to copy one string into another string. This function can be used for creating a
copy of an existing string. The syntax of strcpy function is as shown below:
strcpy(string1, string2)
In the above syntax, the string2 can be either a string or string constant. The string in string2 is copied into string1
and the result will be stored in string1. Let us consider an example:
strlen( )
The strlen function is used to retrieve the length of a given string. The return type of this function will be an
integer. The syntax of strlen function is as shown below:
strlen(string)
strtstr( )
The strstr function returns a character pointer of the first occurrence of the given substring in the string. If
the substring is not found in the string, the function strstr returns NULL. The syntax for strstr function is shown
below:
strstr(string1, string2)
In the above syntax, strstr searches for string2 in the string1. If found, it returns a pointer to the first occurrence of
the string2 in string1. If not found, it returns NULL. Let us consider an example:
strrev( )
The strrev function is used to reverse a given string. We can use this predefined function to check whether a
given string is a palindrome or not. The syntax for using the strrev function is as shown below:
strrev(string)
In the above syntax, the strrev function reverses the given string and returns it back. The content of the string also
changes. Let us see an example: