UNIT 3 - > CONTROL STRUCTURE BRANCHING:
1) If-else
, if statement ,Multiway decision
2) Looping
– while ,do – while , for loop
3) N ested
control Structure – Switch Statement ,Continue Statement , Break Statement,
4) Goto
Statement
If Statement:
The if statement is a powerful decision making
statement which can handle a single condition or group of statements. These
have either true or false action....
When only one
condition occurs in a statement, then simple if statement is used having one
block.
/*Any Number is input through the keyboard.
write a If program.*/
#include< stdio.h >
int main()
{
int
n;
n=1;
printf("Enter the Number");
scanf("%d",&n);
if(n>0)
{
printf("It is If Statement");
}
Return 0;
}
|
This
statement also has a single condition with two different blocks. One is true
block and other is false block...
/*Any Number is input through the
keyboard. write a program to find out whether It is and Odd Number or Even
Number.*/
#include< stdio.h >
int main()
{
int n;
printf("Enter the Number");
scanf("%d",&n);
if(n%2==0)
{
printf("This is Even
Number");
}
else
{
printf("This is Odd
Number");
}
return 0;
}
|
Nested if statement
When an if statement occurs within
another if statement, then such type of is called nested if statement.
/*If the ages of Ram, sham and Ajay are input
through the keyboard, write a program to determine the youngest of the
three*/
#include< stdio.h >
int
main()
{
int
ram,sham,ajay;
printf("Enter the Three Ages of Ram,Sham and Ajay\n");
scanf("%d%d%d",&ram,&sham,&ajay);
if(ram < sham)
{
if(ram < ajay)
{
printf("Ram is Youngest");
}
else
{
printf("Ajay is Youngest");
}
}
else
{
if(sham < ajay)
{
printf("Sham is Youngest");
}
else
{
printf("Ajay is Youngest");
}
}
return 0;
}
|
When in
a complex problem number of condition arise in a sequence, then we can use
Ladder-if or else if statement to solve the problem in a simple manner.
The marks obtained by a student in
5 different subjects are input through the keyboard. The student gets a
division as per the following rules:
=> Percentage above or equal to 60 - First Division
=> Percentage between 50 and 59 - Second Division
=> Percentage between 40 and 49 - Third Division
=> Percentage less than 40 - Fail
Method-1
/*Write a program to calculate the division
obtained by the student. There are two ways in which we can write a program
for this example. These methods are given below: */
//Method-1
#include< stdio.h >
int main()
{
int
eng,math,com,sci,ss,total;
float
per;
clrscr();
printf("Enter Five Subjects Marks\n");
scanf("%d%d%d%d%d",&eng,&math,&com,&sci,&ss);
total
= eng + math + com + sci + ss ;
printf("Toal Marks : %d",total);
per =
total * 100.00 / 500;
printf("\n Percentage : %f", per);
if(per >= 60)
{
printf("\n 1st Division");
}
else
if(per >= 50)
{
printf("\n 2nd Division");
}
else
if(per >= 40)
{
printf("\n 3rd Division");
}
else
{
printf("\n Sorry Fail");
}
return 0;
}
|
Method-2
//Method-2
#include< stdio.h >
int main()
{
int
eng,math,com,sci,ss,total;
float
per;
printf("Enter Five Subjects Marks\n");
scanf("%d%d%d%d%d",&eng,&math,&com,&sci,&ss);
total
= eng + math + com + sci + ss ;
printf("Toal Marks : %d",total);
per =
total * 100.00 / 500;
printf("\n
Percentage : %f", per);
if(per >= 60)
{
printf("\n 1st Division");
}
if(per >= 50 && per < 60)
{
printf("\n 2nd Division");
}
if(per >= 40 && per < 50)
{
printf("\n 3rd Division");
}
if(per < 40)
{
printf("\n Sorry Fail");
}
return 0;
}
|
When
number of conditions (multiple conditions) occurs in a problem and it is very
difficult to solve such type of complex problem with the help of ladder if
statement, then there is need of such type of statement which should have
different alternatives or different cases to solve the problem in simple and
easy way. For this purpose switch
statement is used. .
/*WAP to print the four-days of week from
monday to thrusday which works upon the choice as S,M,T,H using switch case*/
#include< stdio.h >
int main()
{
char
n;
printf("Enter the Choice from Four Days...\n")
printf("S = Sunday \n")
printf("M = Monday \n")
printf("T = Tuesday \n")
printf("H = Thursday \n\n")
scanf("%c",&n);
switch(n)
{
case 'S':
printf("Sunday");
break;
case 'M':
printf("Monday");
break;
case 'T':
printf("Tuesday");
break;
case 'H':
printf("Thursday");
break;
default:
printf("Out of Choice");
break;
}
return 0;
}
|
Output is as :
Enter the Choice from Four Days...
S = Sunday
M = Monday
T = Tuesday
H = Thursday
S=Sunday
C LOOPING STATEMENTS
When a single
statement or a group of statements will be executed again and again in a
program (in an iterative way), then such type processing is called loop. Loop
is divided into two parts:
(a) Body of the loop
(b) Control of loop
While statement or while loop is an
entry control loop. In this, first of all condition is checked and if it is
true, then group of statements or body of loop is executed. It will execute
again and again till condition becomes false.
The general syntax is :
while (test condition)
{
block of statements;
}
/*The easiest way to use while statement or while loop*/
#include< stdio.h >
#include< conio.h >
void main()
{
int i,s=0;
clrscr();
i=1;
while(i<=10)
{
printf("\n
I=%d",i);
s = s + i;
i++;
}
getch(); }
|
Output is as :
I=1,i=2,i=3,i=4,i=5,i=6,i=7,i=8,i=9,i=10
**** do Statement or do
loop
Do statement is exit control loop. It
is also called do-while statement. In this statement, first body of the loop is
executed and then the condition is checked. If condition is true, then the body
of the loop is executed. When condition becomes false, then it will exit from
the loop.
Note : do while
loop always give one output although given condition is true or false.
The syntax of do-loop is as follow:
do
{
block of statements;
}
while (condition);
statement-x;
/*Write a Program to print the 1 To
10 Numbers using do loop*/
#include< stdio.h >
Int main()
{
int i,n=10;
do
{
printf("I=%d",i);
i++;
}
while(i<=n);
return 0;
}
|
Output is as :
I=1,i=2,i=3,i=4,i=5,i=6,i=7,i=8,i=9,i=10
It is a looping statement, which repeat again and again till it
satisfies the defined condition. It is one step loop, which initialize, check
the condition and increment / decrement the step in the loop in a single
statement.
The general syntax is as :
for(initial value; test condition; increment/decrement)
{
body of the loop;
}
statement-x;
/*Write a Program to print the 1 To 10 Numbers using for loop*/
#include< stdio.h >
Int main()
{
int i;
clrscr();
for(i=1;i<=10;i++) //initial value;test
condition;increment/decrement
{
printf("\n
I=%d",i);
}
return 0;
}
|
When a for statment is executed
within another for statement, then it is called nested for statement. We can
apply number of nested for statement in C-Language.
The general syntax is as : for(initial value1; test
condition1; increment/decrement1)
{
for (initial value2; test condition2; increment/decrement2)
{
inner-body of the loop;
}
outer-body of the loop;
statement-x;
}
/*Write a Program to print the below output using nested for loop
*
**
***
****
*****
*/
#include< stdio.h >
Int main()
{
int r,c;
for(r=1;r<=5;r++)
{
for(c=1;c<=r;c++)
{
printf("*");
}
printf("\n");
}
getch();
}
|
C JUMPING STATEMENTS
There are three
different controls used to jump from one C program statement to another and
make the execution of the programming procedure fast. These three Jumping
controls are:
a) goto statment
b) break statment
c) continue statment
goto statement
The powerful Jumping statement in
C-Language is goto statement. It is sometimes also called part of branching
statement. The go to moves the control on a specified address called label or
label name. The goto is mainly of two types. One is conditional and the other
is unconditional.
/*The following program using goto statement*/
#include< stdio.h >
#include< conio.h >
void main()
{
int l;
clrscr();
Laura: //here Laura is the
name of goto Label
printf("Enter any
No.");
scanf("%d",&l);
if(l==5)
{
goto Laura;
}
printf("\n%d",l);
getch();
}
|
Break is always used with then
decision-making statement like if and switch statments. The statement will quit
from the loop when the condition is true.
The general syntax for break statement is as:
break;
/*The following program using break statement*/
#include< stdio.h >
#include< conio.h >
void main()
{
int i=1;
clrscr();
while(i<=10)
{
if(i==6)
{
break;
}
printf("\n
I=%d",i);
i++;
}
getch();
}
|
Continue statement also comes with if
statement. This statment is also used within any loop statement like do loop,
while loop and for statement.
The general syntax for continue statement is as:
continue;
This statement is skip some part of iteration (loop) and comes to the next
looping step i.e. it will increment / decrement the loop value, when continue
occurs.
/*The
following program using continue statement*/
#include<
stdio.h >
#include<
conio.h >
void
main()
{
int i=1;
clrscr();
while(i<=10)
{
if(i==6)
{
continue;
}
printf("\n I=%d",i);
i++;
}
getch();
}
|
Output is as :
I=1,i=2,i=3,i=4,i=5,i=6,i=7,i=8,i=9,i=10
IMPORTANT PROGRAMS
Logic of convert number in words
Step by step descriptive logic to convert number in words.
1.
Input number from user. Store it in some variable say num.
3.
Switch the value of digit found
above. Since there are 10 possible values of digit i.e. 0, 1, 2,
3, 4, 5, 6, 7, 8, 9 hence, write 10 cases. Print corresponding word
for each case.
4.
Remove last digit from num by
dividing it by 10 i.e. num = num / 10.
5. Repeat step 2
to 4 till number becomes 0.
The above logic is correct however it print the words in reverse
order. For example, suppose number is 1234, if you apply above logic the output
printed is - "Four Three Two One" instead of "One Two Three
Four". To overcome this, you must reverse the number.
#include
<stdio.h>
#include
<math.h>
int main()
{
int n, num = 0,
digits;
/* Input number from user */
printf("Enter
any number to print in words: ");
scanf("%d", &n);
/* Find total digits in n */
digits = (int) log10(n);
/* Store reverse of n in num */
while(n != 0)
{
num = (num * 10) + (n % 10);
n /= 10;
}
/* Find total trailing zeros */
digits = digits - ((int) log10(num));
/*
* Extract last digit of
number and print corresponding number in words
* till num becomes 0
*/
while(num != 0)
{
switch(num % 10)
{
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;
}
num /= 10;
}
/* Print all trailing zeros */
while(digits)
{
printf("Zero
");
digits--;
}
return 0;
}
2.Write a C program to input a
number and calculate its factorial using for loop.
What is
factorial?
Factorial of
a number n is product of all positive integers less than or equal
to n. It is denoted as n!.
For example factorial of 5 = 1 * 2 * 3 * 4 * 5 = 120
Logic to find factorial of a
number
Step by step descriptive logic to find factorial of a number.
1.
Input a number from user. Store it in some variable say num.
2.
Initialize another variable that will store factorial say fact = 1.
Why initialize fact with 1 not with 0? This is because you
need to perform multiplication operation not summation. Multiplying 1 by any
number results same, same as summation of 0 and any other number results same.
3.
Run a loop from 1 to num, increment 1
in each iteration. The loop structure should look like for(i=1;
i<=num; i++).
4.
Multiply the current loop counter value i.e. i with fact. Which
is fact = fact * i.
#include
<stdio.h>
int main()
{
int i, num;
unsigned long long fact=1LL;
/* Input number from user */
printf("Enter
any number to calculate factorial: ");
scanf("%d", &num);
/* Run loop from 1 to num */
for(i=1; i<=num; i++)
{
fact = fact * i;
}
printf("Factorial
of %d = %llu", num, fact);
return 0;
}
4. Write a C program input two numbers from
user and find the HCF using for loop.
HCF (Highest
Common Factor) is the
greatest number that divides exactly two or more numbers. HCF is also known as
GCD (Greatest Common Divisor) or GCF (Greatest Common Factor)
Logic to find HCF of two numbers
Step by step descriptive logic to find HCF.
1.
Input two numbers from user. Store them in some variable
say num1 and num2.
2.
Declare and initialize a variable to hold hcf i.e. hcf = 1.
4.
Run a loop from 1 to min, increment
loop by 1 in each iteration. The loop structure should look like for(i=1;
i<=min; i++).
.
#include
<stdio.h>
int main()
{
int i, num1, num2, min, hcf=1;
/* Input two numbers from user */
printf("Enter
any two numbers to find HCF: ");
scanf("%d%d", &num1, &num2);
/* Find minimum between two numbers */
min = (num1<num2) ? num1 : num2;
for(i=1; i<=min; i++)
{
/* If i is factor of both number */
if(num1%i==0 &&
num2%i==0)
{
hcf = i;
}
}
printf("HCF
of %d and %d = %d\n", num1, num2, hcf);
return 0;
}
5. Write a C program to print
Fibonacci series up to n terms using loop.
Example
Input
Input number of terms: 10
Output
Fibonacci series:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34
What is Fibonacci
series?
Fibonacci series is a series of numbers where the current number is the sum
of previous two terms. For Example: 0, 1, 1, 2, 3, 5, 8, 13, 21
, ... , (n-1th + n-2th)
Logic to print Fibonacci series
upto n terms
Step by step descriptive logic to print n Fibonacci terms.
1.
Input number of Fibonacci terms to print from user. Store it in
a variable say terms.
2.
Declare and initialize three variables, I call it as Fibonacci
magic initialization. a=0, b=1 and c=0.
Here c is the current term, b is
the n-1th term and a is
n-2th term.
3.
Run a loop from 1 to terms, increment
loop counter by 1. The loop structure should look like for(i=1;
i<=term; i++). It will iterate through n terms
4.
Inside the loop copy the value of n-1th term to
n-2th term i.e. a = b.
Next, copy the value of nth to n-1th term b = c.
Finally compute the new term by adding previous two terms
i.e. c = a + b.
5.
Print the value of current Fibonacci term i.e. c.
#include
<stdio.h>
int main()
{
int a, b, c, i, terms;
/* Input number from user */
printf("Enter
number of terms: ");
scanf("%d", &terms);
/* Fibonacci magic initialization */
a = 0;
b = 1;
c = 0;
printf("Fibonacci
terms: \n");
/* Iterate through n terms */
for(i=1; i<=terms; i++)
{
printf("%d,
", c);
a = b; // Copy n-1 to n-2
b = c; // Copy current to n-1
c = a + b; // New term
}
return 0;
}
STAR PATTERN PROGRAMMING
1.Write a C program to print right triangle
star pattern series using for loop
*
**
***
****
*****
Step
by step descriptive logic to print right triangle star pattern.
1. Input number of rows to print from user. Store it
in a variable say N.
2. To iterate through rows run an outer loop from 1
to N with loop
structure for(i=1; i<=N; i++).
3. To iterate through columns run an inner loop from 1
to i with loop
structure for(j=1; j<=i; j++). Inside the inner loop print star.
4. After printing all columns of a row move to next
line i.e. print new line.
#include
<stdio.h>
int main()
{
int i, j, n;
/* Input number of rows from user */
printf("Enter
value of n: ");
scanf("%d", &n);
for(i=1; i<=n; i++)
{
/* Print i number of stars */
for(j=1; j<=i; j++)
{
printf("*");
}
/* Move to next line */
printf("\n");
}
return 0;
}
*
**
* *
* *
*****
Step
by step descriptive logic to print hollow right triangle star pattern.
1. Input number of rows to print from user. Store it
in a variable say rows.
2. To iterate through rows, run an outer loop from 1
to rows.
The loop structure should look like for(i=1;
i<=rows; i++).
3. To iterate through columns, run an inner loop from
1 to i. The loop
structure should look like for(j=1;
j<=i; j++).
4. Inside inner loop print star for first or last
column or last row otherwise print space.
5. After printing all columns of a row, move to next
line i.e. print new line.
#include
<stdio.h>
int main()
{
int i, j, rows;
/* Input rows from user */
printf("Enter
number of rows: ");
scanf("%d", &rows);
for(i=1; i<=rows; i++)
{
for(j=1; j<=i; j++)
{
/*
* Print star for
first column(j==1),
* last column(j==i)
or last row(i==rows).
*/
if(j==1 || j==i || i==rows)
{
printf("*");
}
else
{
printf("
");
}
}
printf("\n");
}
return 0;
}
*
**
***
****
*****
#include
<stdio.h>
int main()
{
int i, j, rows;
/* Input rows from user */
printf("Enter
number of rows: ");
scanf("%d", &rows);
/* Iterate through rows */
for(i=1; i<=rows; i++)
{
/* Print spaces in decreasing order of row */
for(j=i; j<rows; j++)
{
printf("
");
}
/* Print star in increasing order or row */
for(j=1; j<=i; j++)
{
printf("*");
}
/* Move to next line */
printf("\n");
}
return 0;
}
Step
by step descriptive logic to print mirrored right triangle star pattern.
1. Input number of rows to print from user. Store it
in some variable say rows.
2. To iterate through rows run an inner loop from 1
to rows.
The loop structure should look like for(i=1;
i<=rows; i++).
3. To print spaces, run an inner loop from i to rows with loop structure for(j=i;j<=rows;j++). Inside this loop print single space.
4. To print stars run another inner loop from 1
to i, with loop
structure for(j=1; j<=i; j++).
5. After printing all columns of a row, move to next
line i.e. print new line.
*****
****
***
**
*
1. Input
number of rows to print from user. Store it in a variable say rows.
2. To iterate through rows run an outer loop from 1
to rows.
The loop structure should look like for(i=1;
i<=rows; i++).
3. To iterate through columns run an inner loop
from i to rows. The loop structure should look like for(j=i; j<=rows; j++). Inside this loop print star.
#include
<stdio.h>
int main()
{
int i, j, rows;
/* Input number of rows from user */
printf("Enter
number of rows : ");
scanf("%d", &rows);
/* Iterate through rows */
for(i=1; i<=rows; i++)
{
/* Iterate through columns */
for(j=i; j<=rows; j++)
{
printf("*");
}
/* Move to the next line */
printf("\n");
}
return 0;
}
*
***
*****
*******
*********
Step
by step descriptive logic to print Pyramid star pattern.
1. Input number of rows to print from user. Store it
in a variable say rows.
2. To iterate through rows, run an outer loop from 1
to rows.
The loop structure should look like for(i=1;
i<=rows; i++).
3. To print spaces, run an inner loop from i to rows
- 1. The loop structure should look
like for(j=i; j<rows;
j++). Inside this loop print single
space.
Note: Iterating from 1 to N - i or i to rows
- 1 both are equal.
4. To print star, run another inner loop from 1
to 2 * i - 1. The loop structure should look like for(j=1; j<=(2*i - 1); j++). Inside this loop print star.
5. After printing stars for current row, move to next
line i.e. print new line
#include
<stdio.h>
int main()
{
int i, j, rows;
/* Input number of rows to print */
printf("Enter
number of rows : ");
scanf("%d", &rows);
/* Iterate through rows */
for(i=1; i<=rows; i++)
{
/* Print leading spaces */
for(j=i; j<rows; j++)
{
printf("
");
}
/* Print star */
for(j=1; j<=(2*i-1); j++)
{
printf("*");
}
/* Move to next line */
printf("\n");
}
return 0;
}
*********
*******
*****
***
*
#include
<stdio.h>
int main()
{
int i, j, rows;
/* Input rows to print from user */
printf("Enter
number of rows : ");
scanf("%d", &rows);
for(i=1; i<=rows; i++)
{
/* Print leading spaces */
for(j=1; j<i; j++)
{
printf("
");
}
/* Print stars */
for(j=1; j<=(rows*2 -(2*i-1)); j++)
{
printf("*");
}
/* Move to next line */
printf("\n");
}
return 0;
}
*
***
*****
*******
*********
*******
*****
***
*
Step by step descriptive logic to print
diamond star pattern.
1. Input number of rows to print from user (in real
number of rows/2). Store it in a variable say rows.
2. Declare two variables to keep track of total
columns to print each row, say stars=1 and spaces=N-1.
3. To iterate through rows, run an outer loop from 1
to rows*2-1. The loop structure should look like for(i=1; i<rows*2; i++).
4. To print spaces, run an inner loop from 1 to spaces. The loop structure should look like for(j=1; j<=spaces; j++). Inside this loop print single space.
5. To print stars, run another inner loop from 1
to stars*2-1. The loop structure should look like for(j=1; j<=stars; j++). Inside this loop print star.
6. After printing all columns of a row, move to next
line i.e. print new line.
7. Check if(i
< rows) then increment stars and decrement spaces. Otherwise increment spaces and decrement stars.
#include
<stdio.h>
int main()
{
int i, j, rows;
int stars,
spaces;
printf("Enter
rows to print : ");
scanf("%d", &rows);
stars = 1;
spaces = rows - 1;
/* Iterate through rows */
for(i=1; i<rows*2; i++)
{
/* Print spaces */
for(j=1; j<=spaces; j++)
printf("
");
/* Print stars */
for(j=1; j<stars*2; j++)
printf("*");
/* Move to next line */
printf("\n");
if(i<rows)
{
spaces--;
stars++;
}
else
{
spaces++;
stars--;
}
}
return 0;
}
1
22
333
4444
55555
#include
<stdio.h>
int main()
{
int i, j, N;
printf("Enter
N: ");
scanf("%d", &N);
for(i=1; i<=N; i++)
{
for(j=1; j<=i; j++)
{
printf("%d", i);
}
printf("\n");
}
return 0;
}
===========================================
// C program for Armstrong Number //
#include<stdio.h>
int main()
{
int a,sum=0,r=0,c=0,temp;
printf("enter the value of a");
scanf("%d",&a);
temp=a;
while(a!=0)
{
r=a%10;
c=r*r*r;
sum=sum+c;
a=a/10;
}
if(sum==temp)
printf("given number is armstrong \n");
else
printf("not armstrong \n");
return 0;
}