Unit Ii
Unit Ii
1.Control Statements
To control the flow of program execution c programming languages uses control
statements. C provides two styles of flow control:
∙ Branching (or) Selection statements (or) Decision making statements
∙ Looping ( or ) Iterative (or) repetitive statements
Branching is deciding what actions to take and looping is deciding how many times to take a
certain action.
Selection statements
These are used to make one-time decisions in C Programming, that is, to execute some
code/s and ignore some code/s depending upon the test expression.
Simple IF STATEMENT
Syntax:
if (test expression)
{
statement/s to be executed if test expression is true;
}
The simple if statement checks whether the text expression inside parenthesis () is true or not. If
the test expression is true, statement/s inside the body of if statement is executed but if test is
false, statement/s inside body of if is ignored.
Example: write a program that prints the largest among three numbers.
#include <stdio.h>
int main()
{
int a, b, c, max;
printf(“\nEnter 3 numbers:”);
scanf(“%d %d %d”, &a, &b, &c);
max = a;
if(b > max)
max = b;
if(c > max)
max = c;
printf(“Largest No is %d”, max);
return 0;
}
Output 1
Enter 3 numbers: 4 5 8
Largest No is 8
IF...ELSE STATEMENT
The if...else statement is used if the programmer wants to execute some statement/s when the test
expression is true and execute some other statement/s if the test expression is false. Syntax of
if...else
if (test expression)
{
Statements to be executed if test expression is true;
}
else
{
Statements to be executed if test expression is false;
}
Example: Write a C program to check whether a number entered by user is even or odd
#include<stdio.h>
int main()
{
int n, r;
printf("Enter the number:\n");
scanf("%d", &n);
r=n%2;
if(r==0)
printf("%d is even.", n);
else
printf("%d is odd.", n);
return 0;
}
Output 1
Enter the number: 5
5 is odd.
Output 2
Enter the number: 2
2 is even.
The if else if statement is used when program requires more than one test expression.
Syntax:
if (test expression1)
{
statement/s to be executed if test expression1 is true;
}
else if(test expression2)
{
statement/s to be executed if test expression1 is false and 2 is true;
}
.
.
.
else
{
statements to be executed if all test expressions are false;
}
If the first test expression is true, it executes the code inside the braces { } just below it.
But if the first test expression is false, it checks the second test expression. If the second test
expression is true, it executes the statement/s inside the braces { } just below it. This process
continues. If all the test expression are false, code/s inside else is executed.
Example: Write a program to check whether a no given by the user is zero, positive or
negative.
#include<stdio.h>
int main()
{
int x;
printf(“\nEnter the number:”);
scanf(“%d”, &x);
if(x > 0)
printf(“x is positive\n”);
else if(x == 0)
printf(“x is zero\n”);
else
printf(“x is negative\n”);
return 0;
}
Output:
Nested IF statement
When the if statement is written under another simple if statement, this cluster is called as nested if.
Example: Write a program to print two integer values using nested if statement.
#include <stdio.h>
int main ()
{
int a = 100;
int b = 200;
if( a == 100 )
{
/* if condition is true then check the following */ if( b == 200 )
{
/* if condition is true then print the following */ printf("Value of a is 100 and b is
200\n" );
}
}
printf("Exact value of a is: %d\n", a );
Output:
Value of a is 100 and b is 200
Exact value of a is: 100
Exact value of b is: 200
It is possible to include an if...else statement inside the body of another if...else statement.
#include <stdio.h>
int main()
{
int a, b, c;
printf(“\nEnter the three numbers:”);
scanf(“%d %d %d”, &a, &b, &c);
if(a > b)
if(a > c)
printf(“%d”, a);
else
printf(“%d”, c);
else
if(b > c)
printf(“%d”, b);
else
printf(“%d”, c);
return 0;
}
Output:
Enter the three numbers: 4 7 6
7
SWITCH STATEMENT
Decision making are needed when, the program encounters the situation to choose a
particular statement among many statements. If a programmer has to choose one block of
statement among many alternatives, if else if can be used but, this makes programming logic
complex. This type of problem can be handled in C programming using switch statement.
Syntax:
switch (n)
{
case constant1:
code/s to be executed if n equals to constant1;
break;
case constant2:
code/s to be executed if n equals to constant2;
break;
.
.
.
default:
code/s to be executed if n doesn't match to any cases;
}
The value of n is either an integer or a character in above syntax. If the value of n matches
constant in case, the relevant codes are executed and control moves out of the switch statement. If
the n doesn't matches any of the constant in case, then the default codes are executed and control
moves out of switch statement.
Switch case checks the value of expression/variable against the list of case values and when
the match is found , the block of statement associated with that case is executed ∙ Expression
should be Integer Expression / Character
∙ Break statement takes control out of the case.
∙ Break Statement is Optional.
Example:
#include<stdio.h>
void main()
{
int roll = 3 ;
switch ( roll )
{
case 1:printf ( " I am Pankaj ");
break;
case 2:printf ( " I am Nikhil ");
break;
case 3:printf ( " I am John ");
break;
default:printf ( "No student found");
break;
}
}
Output:
I am John
CONDITIONAL OPERATOR
It executes by first evaluating expr1, which is normally a relational expression, and then evaluates
either expr2, if the first result was true, or expr3, if the first result was false.
Example: Write a program to check if the two numbers entered by user are equal or largest among
the both.
#include <stdio.h>
int main()
{
int a, b, c;
printf(“\n Enter the two numbers:”);
scanf(“%d %d”, &a, &b);
c = a>b? a : b>a ? b :-1;
if(c == -1)
printf(“\n Both numbers are equal”);
else
printf(“\n Larger number is %d”, c);
return 0;
}
Output:
Enter the two numbers: 4 4
Both are equal
The initialization statement is executed only once at the beginning of the for loop. Then the test
expression is checked by the program. If the test expression is false, for loop is terminated. But if
test expression is true then the code/s inside body of for loop is executed and then update
expression is updated. This process repeats until test expression is false.
Example: Write a program to find the sum of first n natural numbers where n is entered by
user. Note: 1,2,3... are called natural numbers.
#include<stdio.h>
int main()
{
int n, count, sum=0;
printf("\nEnter the value of n:");
scanf("%d", &n);
for(count=1;count<=n;++count)
{
sum+=count; /* this statement is equivalent to sum=sum+count */ }
printf("Sum=%d", sum);
return 0;
}
Output:
Output
Enter a number: 5
Factorial=120
Do...while loop
In C, do...while loop is very similar to while loop. Only difference between these two loops is
that, in while loops, test expression is checked at first but, in do...while loop code is executed at
first then the condition is checked. So, the code are executed at least once in do...while loops.
Syntax of do...while loops,
do
{
some code/s;
}
while (test expression);
At first codes inside body of do is executed. Then, the test expression is checked. If it is true,
code/s inside body of do are executed again and the process continues until test expression
becomes false(zero).
Notice, there is semicolon in the end of while (); in do...while loop.
Example: Write a C program to add all the numbers entered by a user until user enters 0.
Output
Enter a number: 3
Enter a number: -2
Enter a number: 0
sum=1
In this C program, user is asked a number and it is added with sum. Then, only the test
condition in the do...while loop is checked. If the test condition is true,i.e, num is not equal to 0,
the body of do...while loop is again executed until num equals to zero.
There are two statements built in C programming, break; and continue; to alter the normal
flow of a program. Loops perform a set of repetitive task until text expression becomes false but
it is sometimes desirable to skip some statement/s inside loop or terminate the loop immediately
without checking the test expression. In such cases, break and continue statements are used. The
break; statement is also used in switch statement to exit switch statement.
BREAK STATEMENT
In C programming, break is used in terminating the loop immediately after it is encountered.
The break statement is used with conditional if statement.
Syntax:
break;
The break statement can be used in terminating all three loops for, while and do...while
loops.
Example:
#include <stdio.h>
int main()
{
int c = 1;
while(c <= 5)
{
if(c == 3)
break;
printf(“\t %d”, c);
c++;
}
return 0;
}
Output:
12
CONTINUE STATEMENT
It is sometimes desirable to skip some statements inside the loop. In such cases, continue
statements are used.
Syntax:
continue;
Just like break, continue is also used with conditional if statement.
Example:
#include <stdio.h>
int main()
{
int c = 0;
while(c <= 5)
{
c++;
if(c == 3)
continue;
printf(“\t %d”, c);
}
return 0;
}
Output:
12456
GOTO STATEMENT:
In C programming, goto statement is used for altering the normal sequence of program
execution by transferring control to some other part of the program.
Syntax:
goto label;
.............
.............
.............
label:
statement;
In this syntax, label is an identifier. When, the control of program reaches to goto
statement, the control of the program will jump to the label: and executes the code below
it.
Example: The following program is used to find the factorial of a
number. #include <stdio.h>
int main()
{
int n, c;
long int f=1;
printf(“\n Enter the number:”);
scanf(“%d”,&n);
if(n<0)
goto end;
for(c=1; c<=n; c++)
f*=c;
printf(“\n FACTORIAL IS %ld”, f);
end:
return 0;
}
Output:
Enter the number: 4
FACTORIAL IS 24
Reasons to avoid goto statement
Though, using goto statement give power to jump to any part of program, using goto statement
makes the logic of the program complex and tangled. In modern programming, goto statement
is considered a harmful construct and a bad programming practice.
The goto statement can be replaced in most of C program with the use of break and continue
statements. In fact, any program in C programming can be perfectly written without the use of
goto statement. All programmers should try to avoid goto statement as possible as they can.
RETURN STATEMENT
The return type is used in the definition of a function to set its returned value and the return
statement is used to terminate execution of the function.
Syntax:
return expression;
exit
In C, exit() terminates the calling process without executing the rest code which is after the
exit() function.
Example:
// C program to illustrate exit() function.
#include <stdio.h>
#include <stdlib.h>
void main(void)
{
printf("START");
ARRAYS
In C programming, one of the frequently arising problems is to handle similar types
of data. For example: If the user wants to store marks of 100 students. This can be done by
creating 100 variables individually but, this process is rather tedious and impracticable. This
type of problem can be handled in C programming using arrays.
An array is a sequence of data item of homogeneous values (same type). C allows a user to store
the elements of same data type in the continuous memory locations using arrays.
One-dimensional arrays
Declaration of ID-arrays,
data_type array_name[array_size];
Here, the name of array is age. The size of array is 5, that is, there are 5 items
(elements) of array age. All elements in an array are of the same type (int, in this case).
Array elements
Size of array defines the number of elements in an array. Each element of array can be
accessed and used by user according to the need of program. For example:
int age[5];
Note that, the first element is numbered 0 and so on. And 0, 1, 2, 3, 4, 5 are index numbers.
Here, the size of array age is 5 times the size of int because there are 5 elements.
int age[5]={2,4,34,3,4};
int age[]={2,4,34,3,4};
In this case, the compiler determines the size of array by calculating the number of
elements of an array.
Accessing array elements In C programming, arrays can be accessed and treated like
variables in C. For example.
scanf("%d",&age[2]);
scanf("%d",&age[i]);
printf("%d",age[0]);
printf("%d",age[i]);
Example:
#include<stdio.h>
void main()
{
int array[5];
printf(“Enter 5 numbers to store them in array \n”); for(i=0;i<5;i++)
{
scanf(“%d”, &array[i]);
}
printf(“Element in the array are: \n”);
for(i=0;i<5;i++)
{
printf(“Element stored at array[%d]=%d \n”, i, array[i]); }
getch();
}
Output
Multi-dimensional arrays
Output:
a[0][0] : 0
a[0][1] : 0
a[1][0] : 1
a[1][1] : 2
a[2][0] : 2
a[2][1] : 4
a[3][0] : 3
a[3][1] : 6
a[4][0] : 4
a[4][1] : 8
Suppose there is a multidimensional array arr[i][j][k][m]. Then this array can hold
i*j*k*m numbers of data.
Example 2: Write a C program to find sum of two matrix of order 2*2 using multidimensional
arrays where, elements of matrix are entered by user.
#include <stdio.h>
int main()
{
int a[2][2], b[2][2], sum[2][2];
int i,j;
printf("Enter the elements of 1st matrix a:\n"); for(i=0;i<2;++i)
for(j=0;j<2;++j)
{
scanf("%d", &a[i][j]);
}
printf("Enter the elements of 2nd matrix b:\n");
for(i=0;i<2;++i)
for(j=0;j<2;++j)
{
scanf("%d", &b[i][j]);
}
printf("\nSum Of Matrix:");
for(i=0;i<2;++i)
for(j=0;j<2;++j)
{
sum[i][j]=a[i][j]+b[i][j];
}
for(i=0;i<2;++i)
{
printf(“\n”);
for(j=0;j<2;++j)
{
printf("\t%d", sum[i][j]);
}
printf("\n\t");
}
return 0;
}
Output:
56
Questions:
Strings
Array of characters that are used to store characters are known as Strings.
Def: Strings are defined as the character arrays in which each character is stored using one byte
in the memory. The end of the string is denoted by the null character i.e \0
2 strcat(s1, s2);
Concatenates string s2 onto the end of string s1.
3 strlen(s1);
Returns the length of string s1.
4 strcmp(s1, s2);
Returns 0 if s1 and s2 are the same; less than 0 if s1<s2; greater than 0
if s1>s2.
5 strchr(s1, ch);
Returns a pointer to the first occurrence of character ch in string s1.
6 strstr(s1, s2);
Returns a pointer to the first occurrence of string s2 in string s1.
Examples:
#include <stdio.h>
#include <string.h>
int main()
strcat(str1, str2);
puts(str1);
puts(str2);
return 0;
Output:
This is B.Sc(Honors) Class
B.Sc(Honors) Class
#include<stdio.h>
#include <string.h>
int main()
{
char str1[20],str2[20];
printf("Enter 1st string: ");
gets(str1);
printf("Enter 2nd string: ");
gets(str2);
if(strcmp(str1,str2)==0)
printf("Strings are equal");
else
printf("Strings are not equal");
return 0;
}
Output
#include <string.h>
int main()
char str2[20];
strcpy(str2, str1);
puts(str2);
return 0;
Output
C programming
#include <stdio.h>
#include <string.h>
int main()
int x;
strlen(str1);
printf(“%d”,x);
return 0;
Output:
7
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char str1[20],str2[20];
clrscr();
printf(“\nEnter string 1:”);
scanf(“%s”,str1);
printf(“Enter string 2:”);
scanf(“%s”,str2);
if(strcmp(str1,str2)< 0)
printf(“\n %s is greater than %s”, str1,str2);
else
printf(“\n %s is greater than %s”, str2,str1);
getch();
}
Output:
Enter string1: hardware
Enter string2: software
hardware is greater than software
1. Define String. How to declare and initialize the strings. Explain with an example.