C Program-Module 2
C Program-Module 2
Introduction
All statements written in a program are executed from top to bottom one by one.
Control statements are used to execute/transfer the control from one part of the program to the another
depending on condition.
These statements are also called conditional statement. There are two types of control statements-
Decision-making structures require that the programmer specifies one or more conditions to be evaluated or
tested by the program, along with a statement or statements to be executed if the condition is determined to
be true, and optionally, other statements to be executed if the condition is determined to be false.
C programming language assumes any non-zero and non-null values as true, and if it is either zero or
null, then it is assumed as false value.
if (test expression)
{
statement 1;
…...............
statement n;
}
statement x;
Example:
Write a program to print the higher number than 100.
#include <stdio.h>
void main()
{
int n;
printf("Enter a number:");
scanf("%d", &n);
printf ("The entered number %d", n);
if (n>100)
printf ("You entered a higher number");
}
In the above program, a number is accepted as an input from the user and the output is given. The
expression (n>100) is given. If the user gives a number higher than 100 then only will the message be
printed else the statement will be skipped.
2. if-else statement: There are times where we would like to write that if the expression is true an action
should be taken and if the expression is false there would be no action. We can also include an action for
both the conditions.
✔ If the Expression is true (or non-zero) then Statement1 will be executed; otherwise if it is false (or zero),
then Statement2 will be executed
✔ In this case either true block or false block will be executed, but not both.
✔ This is illustrated in Figure 2. In both the cases, the control is transferred subsequently to the Statement x.
Figure 2: Flow chart of if-else statement
Example:
Program to check voting eligibility
#include
<stdio.h>void
main()
{
int yr;
printf("Enter a
year:");scanf("%d",
&yr);
if (yr >=18)
{
printf("Eligible to vote...!!!!");
}
else
{
printf ("Not Eligible to vote !!!");
}
}
Output:
Enter a year: 1997
It's not a leap year...!!!
3. if-else-if statement :
• This statement works in the normal way as the if statement.
• After the first if branch the program can have many other else-if branches depending on
the expressions that need to be tested.
if (test expression 1)
{
statement block 1;
}
else if (test expression 2)
{
statement block 2;
}
....................
else
{
statement block 3;
}
statement y;
Output:
75 is the largest number.
4. Switch Statement
✔ C language provides a multi-way decision statement so that complex else-if statements can be easily
replaced by it. C language’s multi-way decision statement is called switch.
General syntax of switch statement is as follows:
switch(choice)
{
case label1: block1;
break;
case label2: block2;
break;
case label3: block-3;
break;
default: default-block;
break;
}
✔ Here switch, case, break and default are built-in C language words.
✔ If the choice matches to label1 then block1 will be executed else if it evaluates to label2 then block2 will
be executed and so on.
✔ If choice does not matches with any case labels, then default block will be executed.
✔ The choice is an integer expression or characters.
✔ The label1, label2, label3,…. are constants or constant expression evaluate to integer constants.
✔ Each of these case labels should be unique within the switch statement. block1, block2, block3, … are
statement lists and may contain zero or more statements.
✔ There is no need to put braces around these blocks. Note that case labels end with colon(:).
✔ Break statement at the end of each block signals end of a particular case and causes an exit from switch
statement.
✔ The default is an optional case when present, it will execute if the value of the choice does not match
with any of the case labels.
Example:
Label Number Label Character
#include<stdio.h> #include<stdio.h>
#include<stdlib.h> #include<stdlib.h>
void main( ) void main( )
{ {
int ch,a,b,res; int a,b,res;
float div; char ch;
printf(“Enter two numbers:\n”); float div;
scanf(“%d%d”,&a,&b); printf(“Enter two numbers:\n”);
printf(“1.Addition\n 2.Subtraction\n scanf(“%d%d”,&a,&b);
3.Multiplication\n 4.Division\n printf(“a.Addition\n b.Subtraction\n
5.Remainder\n”); printf(“Enter your c.Multiplication\n d.Division\n
choice:\n”); e.Remainder\n”); printf(“Enter your
scanf(“%d”,&ch); choice:\n”);
switch(ch) scanf(“%c”,&ch);
{ switch(ch)
case 1: res=a+b; {
break; case ‘a’: res=a+b;
case 2: res=a-b; break;
break; case ‘b’: res=a-b;
case 3: res=a*b; break;
break; case ‘c’: res=a*b;
case 4: div=(float)a/b; break;
break; case ‘d’: div=(float)a/b;
case 5: res=a%b; break;
break; case ‘e’ : res=a%b;
default: printf(“Wrong choice!!\n”); break;
} default: printf(“Wrong choice!!\n”);
printf(“Result=%d\n”,res); }
} printf(“Result=%d\n”,res);
In this program if ch=1 case ‘1’ gets executed and if ch=2, case ‘2’ gets executed and so on.
Iterative 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 repeatthe same code a number of times.
Three important components of any loop are:
1. Initialization (example: ctr=1, i=0 etc)
2. Test Condition (example: ctr<=500, i != 0 etc)
3. Updating loop control values (example: ctr=ctr+1, i =i-1)
LOOPS IN C
C language provides 3 looping structures namely:
1. while loop
2. do….while loop
3. for loop
Sr. Loop
Description
No. Type
While In while loop, a condition is evaluated before processing a body of the loop. If a condition is
1.
Loop true then and only then the body of a loop is executed.
Do-While In a do…while loop, the condition is always executed after the body of a loop. It is also called
2.
Loop an exit-controlled loop.
3. For Loop In a for loop, the initial value is performed only once, then the condition tests and compares the
counter to a fixed value after each iteration, stopping the for loop when false is returned.
i. while loop:
✔ It is a pre-test loop (also known as entry controlled loop).
✔ In the syntax given above ‘while’ is a key word and condition is at beginning of the loop.
✔ If the test condition is true the body of while loop will be executed.
✔ After execution of the body, the test condition is once again evaluated and if it is true, the body is
executed once again.
✔ This process is repeated until condition finally becomes false and control comes out of the body of the
loop.
✔ In this loop the body of the loop is executed first and then test condition is evaluated. ✔ If the
condition is true, then the body of loop will be executed once again. This process continues as
long ascondition is true.
✔ When condition becomes false, the loop will be terminated and control comes out of the loop
Flowchart:
There is no semi colon at the end of while. The semi colon is compulsory at the end of while.
Here, the body of loop gets executed if and only if Here, the body of loop gets executed at least once
condition is true. even if condition is false.
Nested for loops
#include<stdio.h>
int main()
{
int i, j;
for(i=1; i<=5; i++)
{
for(j=1; j<=3; j++)
printf("*");
printf("\n");
}
return 0;
output
***
***
***
***
***
Example 2
#include<stdio.h>
int main()
{
int i, j;
for(i=1; i<=5; i++)
{
for(j=1; j<=3; j++)
printf("%d", j);
printf("\n");
}
return 0;
output
123
123
123
123
123
Example 3
Example 2
#include<stdio.h>
int main()
{
int i, j;
for(i=1; i<=5; i++)
{
for(j=1; j<=i; j++)
printf("%d", j);
printf("\n");
}
return 0;
output
1
12
123
1234
12345
Note: If updation is not present in loops then, it will execute infinite times.
If initialization is not given then, program prints nothing.
Break and continue
• break and continue are unconditional control construct.
4. Break
Syntax Example
while(condition) #include<stdio.h>
{ void main( )
Statements; {
if(condition) int i;
break; for(i=1; i<=5; i++)
Statements; {
} if(i==3)
break;
printf(“%d”, i)
}
}
OUTPUT 1 2
5. Continue
hile(condition) #include<stdio.h>
void main( )
{
{
Statements;
if(condition) int i;
continue; for(i=1; i<=5; i++)
Statements;
{
}
if(i==3)
continue;
printf(“%d”, i)
}
}
OUTPUT 1 2 4 5
#include<stdio.h>void
main()
{
int num,flag;
printf("Enter the Number");
scanf("%d",&num);
flag = (num%2)?1:0;
if(flag==0)
printf("\nEven");else
printf("\nOdd");
}
2. Write a program to determine the character entered by the user.
Function Test
isalnum(c) Is c alphanumeric character?
isalpha(c) Is c alphabetic character?
isdigit(c) Is c a digit?
islower(c) Is c a lower case letter?
isupper(c) Is c a upper case letter?
isspace(c) Is c a white case character?
ispunct(c) Is c a punctuation mark?
isprint(c) Is c a printable character?
#include<stdio.h>
#include<ctype.h> void
main( )
{
char key;
printf(“Enter any key\n”);
scanf("%c",&key);
if(isalpha(key))
printf("The entered key is a letter\n");else
if(isdigit(key))
printf("The entered key is a digit\n");else
printf("The entered key is not alphanumeric\n");
}
OUTPUT:
The Quadratic Formula uses the "a", "b", and "c" from "ax2 + bx + c", where "a", "b", and "c" are just
numbers; they are the "numerical coefficients" of the quadratic equation they've given you to solve.
#include<stdio.h>
#include<math.h> void
main()
{
float a, b, c, root1, root2, rpart, ipart, disc;printf("Enter
the 3 coefficients:\n"); scanf("%f%f%f", &a,&b,&c);
if((a*b*c)==0)
{
printf("Roots cannot be Determined:\n");exit(0);
}
disc=(b*b) - (4*a*c);if(disc
== 0)
{
printf("Roots are equal\n");root1= -
b / (2*a); root2=root1;
printf ("root1 = %f \n", root1);printf
("root2 = %f \n", root2);
}
else if(disc>0)
{
1
12
123
1234
#include<stdio.h>void
main( )
{
int n, i, j;
printf("Enter the number of rows\n");
scanf("%d",&n);
for(i=1 ;i<=n; i++)
{
for(j=1; j<=i; j++)
{
printf("%d\t", j);
}
printf("\n");
}
}
#include<stdio.h>void
main( )
{
int marks;
printf(“Enter the marks\n”);
scanf("%d", &marks);
if(marks >= 0 && marks <= 39)
printf("F");
else if(marks >= 40 && marks <= 49)printf("E");
else if(marks >= 50 && marks <= 59)
printf("D");
else if(marks >= 60 && marks <= 69)printf("C");
else if(marks >= 70 && marks <= 79)printf("B");
else if(marks >= 80 && marks <= 89)printf("A");
else
printf("O");
6. Write a program to find the sum of natural numbers from 1 to N using awhile loop.
#include<stdio.h>void
main()
{
int n, i=1, sum=0; printf("Enter the
value of n");scanf("%d",&n);
while (i<=n)
{
sum=sum+i;i++;
}
printf("%d",sum);
}
printf(“saturday”);i
= i-1;
goto l;
printf(“sunday”);
Explain your result briefly.
Output Sunday
The i is initialized to 1 and in if condition when checked 1 > 2 returns false. Hence, it
doesn’t enter inside loop and just prints the Sunday.
2. Write a C program that prints the following output:
#include<stdio.h>
void main( )
{
printf(“\”I am\n”);
printf(“an\” \t
‘Engineering\n”);
printf(“student’\n”);
}
3 State the drawback of ladder if-else. Explain how do you resolve with suitable with
suitable example.
✔ If there are more than one if statement and only one else occurs, this situation is called as
dangling else problem.
✔ This problem is created when no matching else exists for every if.
Ex: if(condition1)
{
}
if(condition2)
{
}
if(condition3)
{
}
else
printf(“Dangling Problem\n”);
Solutions:
1. The first approach is to follow simple rule i.e., “Always pair on else to most recent unpaired
if the current block.”
if (condition1)
if (condition2)
if(condition3)
else
printf(“Dangling Problem\n”);
2. The second approach is a compound statement. Here, we make else to belong for the desired
if statement using brackets. (In the below example else belongs to first if statement) if
(condition1)
{
if (condition2)
if (condition3)
}
else
printf(“Dangling Problem\n”);