SlideShare a Scribd company logo
BPOP103/203
Principles Of Programming using C
Module 2
Branching and Loops
Prof.Rajeshwari R, AssistantProfessor
Dept. of CSE, CMRIT, Bangalore
Conditional Branching
we have a number of situations where we may have to change the order of
execution of statements based on certain conditions, or repeat a group of
statements until certain specific conditions are met. This involves a kind of
decision making to see whether a particular condition has occurred or not and
then direct the computer to execute certain statements accordingly.
C language possesses such decision-making capabilities by supporting the
following statements:
1. if statement
2. switch statement
3. Conditional operator statement
4. goto statement
•
•
•
•
•
.
Principals of Programming in CModule -5.pdfModule_2_P2 (1).pdf
Program to find even number
include<stdio.h>
void main()
{
int num=0;
printf("enter the number");
scanf("%d",&num);
if(n%2==0)
{
printf("%d number in even",num);
}
}
Principals of Programming in CModule -5.pdfModule_2_P2 (1).pdf
#include<stdio.h>
void main()
{
int num=0;
Program to find odd/even number
printf("enter the number");
scanf("%d",&num);
if(n%2==0)
{
printf("%d number in even", num);
}
else
{
printf("%d number in odd",num);
}
}
Exercise Program
Write a C program to ask the user to enter the age and based on
the input, display message “You are eligible for voting”, or
“You are not eligible for voting”.
Write a C program to check whether a number is positive or
negative
Principals of Programming in CModule -5.pdfModule_2_P2 (1).pdf
#include <stdio.h>
int main()
{
Program to find the largest number.
int A, B, C;
printf("Enter three numbers: ");
scanf("%d %d %d", &A, &B, &C);
if (A >= B && A >= C)
printf("%d is the largest number.", A);
else if (B >= A && B >= C)
printf("%d is the largest number.", B);
else
printf("%d is the largest number.", C);
return 0;
}
Exercise Program
Using cascade if-else, write a C program to check whether a
number is positive or negative or zero
Using cascade if-else, write a C Program to determine the
grade based on score obtained by student. Score is read by
keyboard. Grade is calculated as per conditions:
Score Grade
90-100 A
80-89 B
70-79 C
50-69 D
0-49 F
If(condition1)
{
If(condition2)
{
Block1
}
Else
{
Block2
}
}
Else
{
If(condition3)
{
Block3
}
Else
{
Block4
}
}
#include <stdio.h>
int main()
{
Using nested if-else statement to find the largest number.
int A, B, C;
printf("Enter three numbers: ");
scanf("%d %d %d", &A, &B, &C);
if (A >= B)
{
if (A >= C)
printf("%d is the largest number.", A);else
printf("%d is the largest number.", C);
}
else
{
if (B >= C)
printf("%d is the largest number.", B);
else
printf("%d is the largest number.", C);
}
return 0; }
Exercise Program
Using nested if-else , write a C program to find whether two
numbers are equal, not equal, greater/less than eachother
#include <stdio.h>
int main()
{
Exercise Program Solution
int var1, var2;
printf("Input the value of var1:");
scanf("%d", &var1); printf("Input
the value of var2:");
else
{
}
printf("var1 is equal to var2n");
scanf("%d",&var2);
if (var1 != var2)
{
return 0;
}
printf("var1 is not equal to var2n");
//Nested if elseif
(var1 > var2)
{
}
else
{
}
}
printf("var1 is greater than var2n");
printf("var2 is greater than var1n");
Exercise Program
Using nested if-else , write a C program to take score/marks of
5 subjects out of 100 from the user. Then calculate the
percentage of it and display grade to the user depending on the
following condition:
• if percentage is greater than or equal to 60, grade=‘A’
• if percentage is greater than or equal to 50, grade=‘B’
• if percentage is greater than or equal to 40, grade=‘C’
• if percentage is less than 40, grade=‘Fail’
#include < stdio.h >
int main()
{
Exercise Program Solution
float s1, s2, s3, s4, s5, per;
printf("Enter marks of 5 subjectn");
scanf("%f %f %f %f %f", &s1, &s2, &s3, &s4, &s5);
per = ((s1 + s2 + s3 + s4 + s5) / 5)*100;
if(per >= 60)
{
else
}
}
{
printf("Failed!n");
}
printf("GradeAn");
}
return 0;
}
else
{
if(per >= 50)
{
printf("Grade Bn");
}
else
{
if(per >= 40)
{
printf("Grade Cn");
}
A switch statement allows a variable to be tested for equality against a list of
values. Each value is called a case, and the variable being switched on is
checked for each switch case.
switch(expression)
{
case constant-expression :
statement(s);
break; /* optional */
case constant-expression :
statement(s);
break; /* optional */
/* you can have any number of case statements */
default : /* Optional */
statement(s);
}
Some important keywords:
1) Break: This keyword is used to stop the
execution inside a switch block. It helps to
terminate the switch block and break out ofit.
2) Default: This keyword is used to specify the
set of statements to execute if there is no case
match.
Important Points About Switch Case Statements:
1) The expression provided in the switch should result in a constant value otherwise itwould
not be valid. Some valid expressions for switch case will be,
// Constant expressions allowed
switch(1+2+23) switch(1*2+3%4)
// Variable expression are allowed provided
// they are assigned with fixed values
switch(a*b+c*d)
switch(a+b+c)
2) Duplicate case values are not allowed.
3) The default statement is optional. Even if the switch case statement do not have adefault
statement, it would run without any problem.
4)The break statement is used inside the switch to terminate a statement sequence. When a
break statement is reached, the switch terminates, and the flow of control jumps to the next
line following the switch statement.
5) The break statement is optional. If omitted, execution will continue on into the next case.
The flow of control will fall through to subsequent cases until a break is reached.
6)Nesting of switch statements is allowed, which means you can have switch statements
inside another switch. However nested switch statements should beavoided as it makes the
program more complex and less readable.
7) Switch statements are limited to integer values only in the check condition.
Principals of Programming in CModule -5.pdfModule_2_P2 (1).pdf
#include <stdio.h>int
main(){
char ch;
int a, b, result;
// Asking for Input
Simple Calculator using switch Statement
case '*':
result = a * b;
break;
case '/’:
if(b==0)
{
printf(“Division by zero errorn");
printf("Enter an Operator (+, *, *, /): ");
scanf("%c", &ch);
printf("Enter two operands: n");
scanf("%d %d", &a, &b);
switch(ch)
{
case '+': default:
}
else
{
}
break;
result = a / b;
result = a + b;
break;
case '-':
result = a - b;
break;
printf("n Enter correct optionn");break;
}
printf("Result = %d", result);
return 0;
}
Write a C Programs using Switch to check whether a number is equal to 5, 10 and 100
#include<stdio.h>
int main()
{
int number;
printf("enter a number:");
scanf("%d",&number);
switch(number){
case 10:
printf("number is equals to 10");
break;
case 50:
printf("number is equal to 50");
break;
case 100:
printf("number is equal to 100");
break;
default:
printf("number is not equal to 10, 50 or 100");
} return 0; }
C Program to Calculate Area of Circle, Rectangle and Triangle using a switch statement
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
{
float area, radius, s1,s2,s3,base,height,sp;int
choice;
printf("1. Area of Circlen");
printf("2. Area of Triangle(Base and Height)n");
printf("3. Area of Triangle(All three Sides)n");
printf("Select your Choicen");
scanf("%d",&choice);
switch(choice)
{
case 1:
printf("You have chosen Area of Circlen");
printf("Enter the radiusn");
scanf("%f",&radius);
area=3.14*radius*radius;
printf("Area of Circle is %.2fn",area);
break;
case 2:
printf("You have chosen Area of
Triangle(Base and Height)n");
printf("Enter base and heightn");
scanf("%f%f",&base,&height);
area=(base*height)/2; printf("Area
of Triangle is
%.2fn",area);
break;
case 3:
printf("You have chosen Area of Triangle(All three Sides)n");
printf("Enter values of all three sidesn");
scanf("%f%f%f",&s1,&s2,&s3);
sp=(s1+s2+s3)/2;
area=sqrt(sp*(sp-s1)*(sp-s2)*(sp-s3));
printf("Area of Triangle is %.2fn",area);
break;
default:
printf("Sorry, Invalid Choicen");
}
printf("Thank Youn");
return 0;
 In else if ladder, the control goes through the every else if
statement until it finds true value of the statement or it
comes to the end of the else if ladder. Incase of switch case,
as per the value of the switch, the control jumps to the
corresponding case.
 The switch case is more compact than lot of nested else if.
So, switch is considered to be more readable.
 The use of break statement in switch is essential but there is
no need of use of break in else if ladder.
 The variable data type that can be used in expression of
switch is integer only where as in else if ladder accepts
integer type as well as character.
 Another difference between switch case and else if ladder is that the
switch statement is considered to be less flexible than the elseif ladder,
because it allows only testing of a single expression against a list of
discrete values.
 Since the compiler is capable of optimizing the switch statement, they
are generally considered to be more efficient. Each case in switch
statement is independent of the previous one. In case of else if ladder, the
code needs to be processed in the order determined by the programmer.
 Switch case statement work on the basis of equality operatorwhereas else
if ladder works on the basis of true false( zero/non- zero) basis.
Principals of Programming in CModule -5.pdfModule_2_P2 (1).pdf
Principals of Programming in CModule -5.pdfModule_2_P2 (1).pdf
Conditional Operators (? :) / Ternary operator
Conditional operators are used in decision making in C programming, i.e, executes
different statements according to test condition whether it is either true or false.
Syntax of conditional operators
(Conditional expression) ? (expression1) : (expression2)
If the conditional expression is evaluated to true , then expression1 is executed.If the
conditional expression is evaluated to false , then expression2 is executed
#include<stdio.h>
int main()
{
int x, y ;
printf(“ enter the value for x”);
// x=10
scanf ( “%d”, &x ) ;
printf(“y=%d”, y);
return 0;
}
Or (using if-else)
#include<stdio.h>
int main()
{
int x, y ;
printf(“ enter the value for x”);
// x=10
scanf ( “%d”, &x ) ;
if ( x > 5 )
y = 3 ;
else
y = 4 ;
printf(“y=%d”, y);
return 0;
}
y = ( x> 5 ? 3 : 4 ) ; //y=3
//This statement will store 3 in y if
x is greater than 5, otherwise it
will store 4 in y.
Using Ternary operator to find the largest number.
#include <stdio.h>
int main()
{
int A, B, C, largest;
printf("Enter three numbers: ");
scanf("%d %d %d", &A, &B, &C);
largest = A > B ? (A > C ? A : C) : (B > C ? B : C);
printf("%d is the largest number.", largest);
return 0;
}
Principals of Programming in CModule -5.pdfModule_2_P2 (1).pdf
Principals of Programming in CModule -5.pdfModule_2_P2 (1).pdf
Output
1
2
3
4
5
Principals of Programming in CModule -5.pdfModule_2_P2 (1).pdf
Output
1
2
3
4
5
Principals of Programming in CModule -5.pdfModule_2_P2 (1).pdf
Output
1
2
3
4
5
Print numbers from 1 to 10
#include <stdio.h>
int main() {
int i;
for (i = 1; i < 11; ++i)
{
printf("%d ", i);
}
return 0;
}
Program to calculate the sum of first n natural numbers
// Positive integers 1,2,3...n are known as natural numbers
#include <stdio.h>
int main()
{
int num, count, sum = 0;
printf("Enter a positive integer: ");
scanf("%d", &num);
// for loop terminates when num is less than count
for(count = 1; count <= num; ++count)
{
sum += count;
}
printf("Sum = %d", sum);
return 0;
}
Program to add numbers until the user enters zero
#include <stdio.h>
int main()
{
double number, sum = 0;
// the body of the loop is executed at least once
do
{
printf("Enter a number: ");
scanf("%lf", &number); sum
+= number;
}
while(number != 0.0);
printf("Sum = %.2lf",sum);
return 0;
}
Difference Between for, while & do-while loop
(Write programs also for each loop)
Nested Loops
Any number of loops can be defined inside another loop, i.e., there is no
restriction for defining any number of loops. The nesting level can be defined at n
times. You can define any type of loop inside another loop; for example, you
can define 'while' loop inside a 'for' loop.
Syntax of Nested loop
Outer_loop
{
Inner_loop
{
// inner loop statements.
Outer_loop and Inner_loop are
the valid loops that can be a
'for' loop, 'while' loop or 'do-
while' loop.
}
// outer loop statements.
}
Array
int v; // regular variable, v=10
int v[5]; //1-D array, v={10,20,30,40}
int v[2][4]; //2-D array, v={
{10,20,30,40},
{50,60,70,80},
};
1D array
int A[10] = {3 ,6 ,5 ,8}; // n=4, array position = 0 to 3
A [0]
A [1] A [2] A [3]
Position of array starts with 0 & ends in n-1, where n= total count of elements
A[1] =6
2D array ( element access can be either in row major order or incol
major order)
3 6 5 8
5 3 2 1
A[1][1]
=3
3 6 5 8
5 3 2 1
A [0] A [1] A [2] A [3]
3 6 5 8
Example of nested for loop
int main()
{
int i, j;
// i= row position, j= col position
// Declare the matrix
int matrix[10][10] = {
{ 1, 2, 3 },
{ 4, 5, 6 },
{ 7, 8, 9 }
};
Output:
Given matrix is
// in each set, count of elements represents count of col
printf("Given matrix is n");
// Print the matrix using nested loopsfor
(i = 0; i <3 ; i++) // row position ,
{
for (j = 0; j <3 ; j++) //col position
printf("%d ",
matrix[i][j]);
printf("n");
} return 0; }
// each set is 1 row
1 2 3
4 5 6
7 8 9
// 3.3 iteration : matrix[ 2][ 2 ]=9
While vs do-while
When to Use Which Loop
• The for loop is appropriate when you know in advance how many timesthe
loop will be executed.
• The while and do-while loops are used when you don’t know in advancewhen
the loop will terminate.
The while loop when you may not want to execute the loop bodyeven
once without satisfying the loop condition.
The do loop when you’re sure you want to execute the loop body atleast
once without satisfying the loop condition.


Principals of Programming in CModule -5.pdfModule_2_P2 (1).pdf
Principals of Programming in CModule -5.pdfModule_2_P2 (1).pdf
Principals of Programming in CModule -5.pdfModule_2_P2 (1).pdf
Principals of Programming in CModule -5.pdfModule_2_P2 (1).pdf
#include <stdio.h>
int main() {int
i;
int number, sum = 0;
for (i = 1; i <= 10; ++i)
{
printf("Enter n%d: ", i);scanf("%d",
&number);
// if the user enters a negative number, break the loopif
(number < 0) // negative number
{
break;
}
sum += number;
Enter n1: 2
Enter n2: -3
Enter n3:
Enter n4:
Enter n5:
Enter n6:
Enter n7:
Enter n8:
Enter n9:
Enter n10:
Sum=
}
printf("Sum = %d", sum); // Sum=2
return 0;
}
// sum = sum + number// sum=0+2=2
#include <stdio.h>
int main() {
int i;
int number, sum = 0;
for (i = 1; i <= 10; ++i)
{
printf("Enter n%d: ", i);
scanf("%d", &number);
// if the user enters a negative number, break the loopif
(number < 0)
{
break;
}
sum += number; // sum = sum + number;
}
printf("Sum = %d", sum);
return 0;
}
#include <stdio.h>
int main() {int
i;
int number, sum = 0;
for (i = 1; i <= 10; ++i)
{
printf("Enter n%d: ", i);scanf("%d",
&number);
// if the user enters a negative number, break the loop
if (number < 0)
{
continue;
Enter n1: 2
Enter n2: -3
Enter n3: 4
Enter n4: -1
Enter n5: 6
Enter n6: Enter
n7: Enter n8:
Enter n9:
Enter n10:
}
sum += number; // sum = sum + number// sum=2+4=6
}
Sum=
printf("Sum = %d", sum);
return 0;
}
#include <stdio.h>
int main() {
int i;
int number, sum = 0;
for (i = 1; i <= 10; ++i)
{
printf("Enter n%d: ", i);
scanf("%d", &number);
// if the user enters a negative number, break the loop
if (number < 0)
{
// checking for negative number
continue; // escape only the particular iteration
}
sum += number; // sum = sum + number; This line will be skipped every timecontinue
statement is executed
}
printf("Sum = %d", sum);
return 0;
}
Principals of Programming in CModule -5.pdfModule_2_P2 (1).pdf
Principals of Programming in CModule -5.pdfModule_2_P2 (1).pdf
6. sum: printf(“%d”, a+b); //10+20=30
7. return 0;
Principals of Programming in CModule -5.pdfModule_2_P2 (1).pdf
Principals of Programming in CModule -5.pdfModule_2_P2 (1).pdf
#include <stdio.h>
int main()
{
Output
int sum=0, i;
for(i=0;i<=10;i++)
{
1. sum=0+0=0
2. Sum=0+1=1
sum = sum+i; 3. Sum=1+2=3
if(i==5)
{
goto addition;
}
} addition:
printf("%d", sum);
return 0;
}
4. Sum=3+3=6
5. Sum=6+4=10
6. Sum=10+5= 15
Same Previous slide program with do-while statement
#include <stdio.h>
int main()
{
int sum=0,i=0;do
{
i++;
sum = sum+i;
if(i==5)
{
Output : 15
goto addition;
}
} while(i<=10);
addition:
printf("%d", sum);
return 0;
}
Finding roots of a quadratic equation
#include<stdio.h>
#include<math.h>
int main()
{
float a,b,c,desc,r1,r2,realpart,imgpart;
printf("Enter the coefficients of a, b and c :");
scanf("%f%f%f",&a,&b,&c);
if(a==0)
{
}
printf("Coefficient of a cannot be zero... n");printf("Please try
again... n");
return 1;
desc=(b*b)-(4.0*a*c);
if(desc==0)
{
}
printf("The roots are real and equaln");
r1=r2=(-b)/(2.0*a);
printf("The two roots are r1=r2=%fn",r1);
else if(desc>0)
{
printf("The roots are real and distinctn");
r1=(-b+sqrt(desc))/(2.0*a);
r2=(-b-sqrt(desc))/(2.0*a);
printf("The roots are r1=%f and r2=%fn",r1,r2);
}
else
{
}
printf("The roots are imaginaryn");
realpart=(-b)/(2.0*a); imgpart=sqrt(-
desc)/(2.0*a);
printf("The roots are r1=%f + i %fn",realpart,imgpart);
printf("r2=%f - i %fn",realpart,imgpart);
return 0;
}
Computation of binomial coefficients
What is Binomial Coefficient
Binomial coefficient (n, k) is the order of choosing ‘k’ results from the given ‘n’
possibilities. The value of binomial coefficient of positive n and k is given by
where, n >= k
Example
The Binomial coefficient C(n,r)=n!/((n-r)!*r!) is the number of
ways of picking ‘r’ unordered outcomes from n possibilities. In this
equation, ! represents factorial of a number.
Binomial coefficient involves calculation of three values based on
factorial which can be calculated easily using user defined
function/recursive function which will be covered in module 4.
Here we are using direct calculation using separate for loop to
calculate each value namely,
x=n!
y=(n-r)!
z=r!
#include<stdio.h>
int main()
{
int i,n,r;
Code
long int x,y,z,nCr; // factorial of a number may cross the range of
the integer,so used long int data type.
printf(“enter the value of n and r”);
scanf(“%d %d”, &n, &r);
x=y=z=1;
//calculate x as factorial n
for(i=n; i>=1;i--)
{
x=x*i;
}
//calculate y as factorial (n-r)
for(i=n-r; i>=1;i--)
{
y=y*i;
}
//calculate z as factorial r
for(i=r; i>=1;i--)
{
z=z*i;
}
//Using x,y,z calculate binomial coefficient nCr
nCr=x/(y*z);
printf(“%dC%d=%d”, n,r,nCr);
return 0;
}
Plotting of Pascal’s triangle.
0 row =1
1 row = (0+1), (1+0) = 1, 1
2 row = (0+1), (1+1), (1+0) = 1, 2, 1
3 row = (0+1), (1+2), (2+1), (1+0) = 1, 3, 3, 1
4 row = (0+1), (1+3), (3+3), (3+1), (1+0) = 1, 4, 6, 4, 1
Properties of Pascal’s Triangle:
• The sum of all the elements of a row is twice the sum of all the
elements of its preceding row. For example, sum of second
row is 1+1= 2, and that of first is 1. Again, the sum of third row
is 1+2+1 =4, and that of second row is 1+1 =2, and so on. This
major property is utilized to write the code in C program for
Pascal’s triangle.
• The sequence of the product of each element is related to the
base of the natural logarithm, e.
• The left and the right edges of Pascal’s triangle are filled with
“1”s only.
• All the numbers outside the triangle are “0”s.
• The diagonals next to the edge diagonals contain natural
numbers (1, 2, 3, 4, ….) in order.
• The sum of the squares of the numbers of row “n” equals
the middle number of row “2n”.
#include<stdio.h>
int main()
{
int rows, num=1,space,i,j;
Code
for (j=0;j<=i; j++)
{
if (j==0||i==0)
num=1;
printf(“enter number of rows”);
scanf(“%d”, &rows);
for(i=0;i<rows;i++)
{
for(space=1;space<=rows-i; space++)
printf(“ “);
else
num=num*(i-j+1)/j;
printf(“%4d”, num);
}
printf(“n”);
}
return 0;
}
Additional Programs for Practice
C program to check character entered is vowel or consonant
#include <stdio.h>
int main() {
char c;
int lowercase_vowel, uppercase_vowel;
printf("Enter an alphabet: ");
scanf("%c", &c);
// evaluates to 1 if variable c is a lowercase vowel lowercase_vowel = (c
== 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u');
// evaluates to 1 if variable c is a uppercase vowel uppercase_vowel = (c
== 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U');
// evaluates to 1 (true) if c is a vowel
if (lowercase_vowel || uppercase_vowel)
printf("%c is a vowel.", c);
else
printf("%c is a consonant.", c);
return 0;
}
Additional Programs for Practice
C program to check character entered is vowel or consonant
#include <stdio.h>
int main()
{
(nested if method)
char ch;
printf("Input a charactern");
scanf("%c", &ch);
if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' &&ch <= 'Z’))
{
if (ch=='a' || ch=='A' || ch=='e' || ch=='E' || ch=='i' || ch=='I' || ch=='o' || ch=='O' || ch== 'u' || ch=='U')printf("%c is
a vowel.n", ch);
else
printf("%c is a consonant.n", ch);
}
else
printf("%c is neither a vowel nor a consonant.n", ch);
return 0;
}
Additional Programs for Practice
C program to check given year is leap year or not. Check for Century year also.
#include <stdio.h>
int main() {
int year;
printf("Enter a year: ");
scanf("%d", &year);
// leap year if perfectly divisible by 400if
(year % 400 == 0) {
printf("%d is a leap year.", year);
}
// not a leap year if divisible by 100
// but not divisible by 400
else if (year % 100 == 0) {
printf("%d is not a leap year.", year);
// leap year if not divisible by 100
// but divisible by 4 else
if (year % 4 == 0) {
printf("%d is a leap year.", year);
}
// all other years are not leap yearselse {
printf("%d is not a leap year.", year);
}
return 0;
}
}
Additional Programs for Practice
C program to check a number whether prime or not
#include <stdio.h>
main() {
int n, i, c = 0;
printf("Enter any number n:");
scanf("%d", &n);
//logic
for (i = 1; i <= n; i++)
{
if (n % i == 0)
{
c++;
}
}
if (c == 2)
{
printf("n is a Prime number");
}
else
{
printf("n is not a Prime number");
}
return 0;
}
Additional Programs for Practice
C program to Generate Fibonacci series
#include <stdio.h>
int main()
{
int number, i = 0, Next, first = 0, second = 1;
printf("n Please Enter the Range Number: ");
else{
}
Next = first + second;
first = second; second
= Next;
scanf("%d",&number);
{
while(i < number)
printf("%d t", Next);
i++;
}
if(i <= 1)
{
Next = i;
}
return 0;
Additional Programs for Practice
C program for printing a multiplication table for a given number
#include <stdio.h>
int main(){
int i, num;
/* Input a number to print table */
printf("Enter number to print table: ");
scanf("%d", &num);
for(i=1; i<=10; i++){
printf("%d * %d = %dn", num, i, (num*i));
}
return 0;
}
Additional Programs for Practice
C Program to Print Characters in a String
#include <stdio.h>
int main()
{
char str[100];
int i = 0;
printf("n Please Enter any String : ");
scanf("%s", str);
while (str[i] != '0')
{
printf("The Character at %d Index Position =
%c n", i, str[i]);
i++;
}
return 0;
}
Additional Programs for Practice
C Program to Convert Decimal to Binary
#include <stdio.h>
int main()
{
int a[10], number, i, j;
printf("n Please Enter the Number You want to Convert :
")
;scanf("%d", &number);
for(i = 0; number > 0; i++)
{
a[i] = number % 2;
number = number / 2;
}
printf("n Binary Number of a Given Number = ");
for(j = i - 1; j >= 0; j--) {
printf(" %d ", a[j]);
}
printf("n");
return 0;
}
Additional Programs for Practice
C program for finding factorial of a number
#include<stdio.h>
void main()
{
int n,i=1,f=1;
printf("n Enter The Number:");
scanf("%d",&n);
//LOOP TO CALCULATE FACTORIAL OF A NUMBER
while(i<=n)
{
f=f*i
;i++;
}
printf("n The Factorial of %d is %d",n,f);
}
Additional Programs for Practice
C program to find GCD of two numbers using Euclid’s method
#include <stdio.h>
void main()
{
int num1, num2, gcd, lcm, remainder, numerator,
denominator;
printf("Enter two numbersn");
scanf("%d %d", &num1, &num2);if
(num1 > num2)
{
numerator = num1;
denominator = num2;
}
else
{
numerator = num2;
denominator = num1;
}
remainder = numerator % denominator;
while (remainder != 0)
{
numerator = denominator;
denominator = remainder;
remainder = numerator % denominator;
}
gcd = denominator;
lcm = num1 * num2 / gcd;
printf("GCD of %d and %d = %dn", num1, num2, gcd);
printf("LCM of %d and %d = %dn", num1, num2, lcm);
}
Additional Programs for Practice
C program to check Palindrome using while loop
#include <stdio.h>
int main(){
int num, temp, rem, rev = 0;
printf("enter a number:n");
scanf("%d", &num);
temp = num; while
( temp > 0){
rem = temp %10;
rev = rev *10+ rem;
temp = temp /10;
}
printf("reversed number is = %dn", rev);if (
num == rev )
printf("n%d is Palindrome Number.n", num);
else
printf("%d is not the Palindrome Number.n", num);
return 0;
}
Additional Programs for Practice
Half Pyramid of Numbers
#include <stdio.h>int
main() {
int i, j, rows;
printf("Enter the number of rows: ");
scanf("%d", &rows);
for (i = 1; i <= rows; ++i)
{
for (j = 1; j <= i; ++j)
{
printf("%d ", j);
Output
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
}
printf("n");
}
return 0;
}
Additional Programs for Practice
Half Pyramid of Alphabets#include
<stdio.h>
int main() {
int i, j;
char input, alphabet = 'A';
printf("Enter an uppercase character you want toprint
in the last row: ");
scanf("%c", &input);
for (i = 1; i <= (input - 'A' + 1); ++i) {
for (j = 1; j <= i; ++j) {
printf("%c ", alphabet);
Output
A
B B
C C C
D D D D
E E E E E
}
++alphabet;
printf("n");
}
return 0;
}
Additional Programs for Practice
Half Pyramid of *
#include <stdio.h>
int main() {
int i, j, rows;
printf("Enter the number of rows: ");
scanf("%d", &rows);
for (i = 1; i <= rows; ++i) {
for (j = 1; j <= i; ++j) {
printf("* ");
}
printf("n");
Output
*
* *
* * *
* * * *
* * * * *
}
return 0;
}
Additional Programs for Practice
Inverted half pyramid of *
#include <stdio.h>
int main() {
int i, j, rows;
printf("Enter the number of rows: ");
scanf("%d", &rows);
for (i = rows; i >= 1; --i)
{
for (j = 1; j <= i; ++j)
{
printf("* ");
Output
* * * * *
* * * *
* * *
* *
*
}
printf("n");
}
return 0;
}
Additional Programs for Practice
Full Pyramid of *
#include <stdio.h>
int main() {
int i, space, rows, k = 0; printf("Enter
the number of rows: ");scanf("%d",
&rows);
for (i = 1; i <= rows; ++i, k = 0) {
for (space = 1; space <= rows - i; ++space)
{
printf(" ");
}
while (k != 2 * i - 1)
{
printf("* ");
++k;
Output
*
* * *
* * * * *
* * * * * *
*
* * * * * * * *
*
}
printf("n");
}
return 0; }
Question Bank
1. Explain formatted and unformatted input-output functions in C with syntax and
example.
2. Explain the various conditional branching statements with syntax and example.
3.Explain the various unconditional branching statements with syntax and example.
4. Explain the different looping statements in C with syntax and example.
5. Differentiate between while and do-while loop.
6. Explain the switch statement with syntax and example program.
7. Evaluate following programi
= 1;
L: if ( i > 2)
{
printf(“Saturday”);i
= i – 1;
goto L;
}
printf(“Sunday”);
Explain your result briefly.
Question Bank
8.State the drawback of else-if ladder. Explain how you resolve with suitable
example.
9. Explain break and continue statements with respect to do-while, while and forloop
with suitable examples.
10. Explain ternary operator with suitable examples.
11. Write a C program to simulate simple calculator that performs arithmetic operations
using switch statement. An error message should be displayed, if anyattempt is made to
divide by zero.
12. 20. An electric power distribution company charges it’s domestic consumers
as follows:
Write a C program, to compute and print amount to be paid by customer.
13. Distinguish between the following:
i. goto and if
ii. break and continue.
Consumption Units Rate of charge
0 – 200 Rs. 0.50 per units
201 – 400 Rs. 100 + Rs. 0.65 per unit excess of 200
401 – 600 Rs. 230 + Rs. 0.80 per unit excess of 400
601 – above Rs. 390 + Rs. 1.00 per unit excess of 600
Question Bank
Programming exercises
1. Using if-else statement
a. C program for largest of two numbers.
b. C program to check number is even or odd.
c. C program to check number is positive or negative.
d. C program to check person is eligible to cast his vote
e. C program to check character entered is vowel or consonant
f. C program to check given year is leap year or not
g. C program to check number is prime or not
2. Using Conditional Operator (?: )
a. C program to find largest of three numbers
Question bank
3. Using else-if ladder statement
a. C program to find largest of three numbers
b. C program to find grade of a student
c. C program to perform arithmetic operations
4. Using nested if statement
a. C program to find largest of three numbers
5. Using for loop
a. Sum of N natural numbers
b. Generate Fibonacci series
c. Finding factorial of a number
d. Write a C program to get this triangle of numbers as a result.1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
Question bank
6. Using while loop
a. Sum of N natural numbers
b. Find GCD of two numbers using Euclid’s method
c. Palindrome
d. Factorial of a number
7. Using do-while loop
a. Sum of N natural numbers
b. Factorial of a number
8. Write a C Program for:
a. Finding roots of a quadratic equation
b. computation of binomial coefficients
c. plotting of Pascal’s triangle.

More Related Content

PDF
Programming in C Conditional statements.pdf
PPTX
Basics of Control Statement in C Languages
PDF
Unit ii chapter 2 Decision making and Branching in C
PDF
3-Conditional-if-else-switch btech computer in c.pdf
PDF
Control statements-Computer programming
PPT
Decision making in C(2020-2021) statements
PPTX
Branching statements
PDF
controlflowwSoftware Development Fundamentals (SDF) – I ODD 2024 Jaypee Insti...
Programming in C Conditional statements.pdf
Basics of Control Statement in C Languages
Unit ii chapter 2 Decision making and Branching in C
3-Conditional-if-else-switch btech computer in c.pdf
Control statements-Computer programming
Decision making in C(2020-2021) statements
Branching statements
controlflowwSoftware Development Fundamentals (SDF) – I ODD 2024 Jaypee Insti...

Similar to Principals of Programming in CModule -5.pdfModule_2_P2 (1).pdf (20)

PDF
POP Unit 2.pptx.pdf for your time and gauss with example
PDF
Decision Making Statements, Arrays, Strings
PPTX
C Unit-2.ppt
PDF
C_Dayyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy 2.pdf
PPTX
Control Structures.pptx
PPT
asdasdqwdsadasdsadsadasdqwrrweffscxv wsfrt
PDF
C programming decision making
DOCX
Chapter 4(1)
PPTX
M2 (1).pptxisedepofengiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii
PPTX
C decision making and looping.
PPTX
COM1407: Program Control Structures – Decision Making & Branching
PPTX
Decision making statements in C programming
PPTX
BHARGAVISTATEMENTS.PPT.pptx
PPT
CONTROLSTRUCTURES.ppt
PPTX
presentation of data structure and algorithm
PPTX
Decision making statements in C
PPT
Control statments in c
PPTX
6 Control Structures-1.pptxAAAAAAAAAAAAAAAAAAAAA
PPTX
Decision Making and Branching
PPT
Lec 10
POP Unit 2.pptx.pdf for your time and gauss with example
Decision Making Statements, Arrays, Strings
C Unit-2.ppt
C_Dayyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy 2.pdf
Control Structures.pptx
asdasdqwdsadasdsadsadasdqwrrweffscxv wsfrt
C programming decision making
Chapter 4(1)
M2 (1).pptxisedepofengiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii
C decision making and looping.
COM1407: Program Control Structures – Decision Making & Branching
Decision making statements in C programming
BHARGAVISTATEMENTS.PPT.pptx
CONTROLSTRUCTURES.ppt
presentation of data structure and algorithm
Decision making statements in C
Control statments in c
6 Control Structures-1.pptxAAAAAAAAAAAAAAAAAAAAA
Decision Making and Branching
Lec 10
Ad

More from anilcsbs (6)

PDF
Principals of Programming in CModule -5.pdfModule-3.pdf
PDF
Module 2_PPT_P1 POP Notes module 2 fdfd.pdf
PDF
Module 1_Chapter 2_PPT (1)sasaddsdsds.pdf
PDF
Principals of Programming in CModule -5.pdfModule-4.pdf
PDF
Principals of Programming in CModule -5.pdf
PDF
Module 1 _Chapter 1_PPT (1) (1) POP .pdf
Principals of Programming in CModule -5.pdfModule-3.pdf
Module 2_PPT_P1 POP Notes module 2 fdfd.pdf
Module 1_Chapter 2_PPT (1)sasaddsdsds.pdf
Principals of Programming in CModule -5.pdfModule-4.pdf
Principals of Programming in CModule -5.pdf
Module 1 _Chapter 1_PPT (1) (1) POP .pdf
Ad

Recently uploaded (20)

PDF
PPT on Performance Review to get promotions
PDF
July 2025 - Top 10 Read Articles in International Journal of Software Enginee...
PDF
Model Code of Practice - Construction Work - 21102022 .pdf
PPTX
CH1 Production IntroductoryConcepts.pptx
PPTX
Sustainable Sites - Green Building Construction
PPT
Project quality management in manufacturing
PPTX
Welding lecture in detail for understanding
PPTX
MCN 401 KTU-2019-PPE KITS-MODULE 2.pptx
PPTX
KTU 2019 -S7-MCN 401 MODULE 2-VINAY.pptx
PPTX
Engineering Ethics, Safety and Environment [Autosaved] (1).pptx
PPT
Mechanical Engineering MATERIALS Selection
PDF
composite construction of structures.pdf
PPTX
bas. eng. economics group 4 presentation 1.pptx
PPTX
UNIT-1 - COAL BASED THERMAL POWER PLANTS
PDF
Mohammad Mahdi Farshadian CV - Prospective PhD Student 2026
PDF
PRIZ Academy - 9 Windows Thinking Where to Invest Today to Win Tomorrow.pdf
PDF
The CXO Playbook 2025 – Future-Ready Strategies for C-Suite Leaders Cerebrai...
PPTX
Geodesy 1.pptx...............................................
PDF
Well-logging-methods_new................
PPTX
Lesson 3_Tessellation.pptx finite Mathematics
PPT on Performance Review to get promotions
July 2025 - Top 10 Read Articles in International Journal of Software Enginee...
Model Code of Practice - Construction Work - 21102022 .pdf
CH1 Production IntroductoryConcepts.pptx
Sustainable Sites - Green Building Construction
Project quality management in manufacturing
Welding lecture in detail for understanding
MCN 401 KTU-2019-PPE KITS-MODULE 2.pptx
KTU 2019 -S7-MCN 401 MODULE 2-VINAY.pptx
Engineering Ethics, Safety and Environment [Autosaved] (1).pptx
Mechanical Engineering MATERIALS Selection
composite construction of structures.pdf
bas. eng. economics group 4 presentation 1.pptx
UNIT-1 - COAL BASED THERMAL POWER PLANTS
Mohammad Mahdi Farshadian CV - Prospective PhD Student 2026
PRIZ Academy - 9 Windows Thinking Where to Invest Today to Win Tomorrow.pdf
The CXO Playbook 2025 – Future-Ready Strategies for C-Suite Leaders Cerebrai...
Geodesy 1.pptx...............................................
Well-logging-methods_new................
Lesson 3_Tessellation.pptx finite Mathematics

Principals of Programming in CModule -5.pdfModule_2_P2 (1).pdf

  • 1. BPOP103/203 Principles Of Programming using C Module 2 Branching and Loops Prof.Rajeshwari R, AssistantProfessor Dept. of CSE, CMRIT, Bangalore
  • 2. Conditional Branching we have a number of situations where we may have to change the order of execution of statements based on certain conditions, or repeat a group of statements until certain specific conditions are met. This involves a kind of decision making to see whether a particular condition has occurred or not and then direct the computer to execute certain statements accordingly. C language possesses such decision-making capabilities by supporting the following statements: 1. if statement 2. switch statement 3. Conditional operator statement 4. goto statement
  • 5. Program to find even number include<stdio.h> void main() { int num=0; printf("enter the number"); scanf("%d",&num); if(n%2==0) { printf("%d number in even",num); } }
  • 7. #include<stdio.h> void main() { int num=0; Program to find odd/even number printf("enter the number"); scanf("%d",&num); if(n%2==0) { printf("%d number in even", num); } else { printf("%d number in odd",num); } }
  • 8. Exercise Program Write a C program to ask the user to enter the age and based on the input, display message “You are eligible for voting”, or “You are not eligible for voting”. Write a C program to check whether a number is positive or negative
  • 10. #include <stdio.h> int main() { Program to find the largest number. int A, B, C; printf("Enter three numbers: "); scanf("%d %d %d", &A, &B, &C); if (A >= B && A >= C) printf("%d is the largest number.", A); else if (B >= A && B >= C) printf("%d is the largest number.", B); else printf("%d is the largest number.", C); return 0; }
  • 11. Exercise Program Using cascade if-else, write a C program to check whether a number is positive or negative or zero Using cascade if-else, write a C Program to determine the grade based on score obtained by student. Score is read by keyboard. Grade is calculated as per conditions: Score Grade 90-100 A 80-89 B 70-79 C 50-69 D 0-49 F
  • 13. #include <stdio.h> int main() { Using nested if-else statement to find the largest number. int A, B, C; printf("Enter three numbers: "); scanf("%d %d %d", &A, &B, &C); if (A >= B) { if (A >= C) printf("%d is the largest number.", A);else printf("%d is the largest number.", C); } else { if (B >= C) printf("%d is the largest number.", B); else printf("%d is the largest number.", C); } return 0; }
  • 14. Exercise Program Using nested if-else , write a C program to find whether two numbers are equal, not equal, greater/less than eachother
  • 15. #include <stdio.h> int main() { Exercise Program Solution int var1, var2; printf("Input the value of var1:"); scanf("%d", &var1); printf("Input the value of var2:"); else { } printf("var1 is equal to var2n"); scanf("%d",&var2); if (var1 != var2) { return 0; } printf("var1 is not equal to var2n"); //Nested if elseif (var1 > var2) { } else { } } printf("var1 is greater than var2n"); printf("var2 is greater than var1n");
  • 16. Exercise Program Using nested if-else , write a C program to take score/marks of 5 subjects out of 100 from the user. Then calculate the percentage of it and display grade to the user depending on the following condition: • if percentage is greater than or equal to 60, grade=‘A’ • if percentage is greater than or equal to 50, grade=‘B’ • if percentage is greater than or equal to 40, grade=‘C’ • if percentage is less than 40, grade=‘Fail’
  • 17. #include < stdio.h > int main() { Exercise Program Solution float s1, s2, s3, s4, s5, per; printf("Enter marks of 5 subjectn"); scanf("%f %f %f %f %f", &s1, &s2, &s3, &s4, &s5); per = ((s1 + s2 + s3 + s4 + s5) / 5)*100; if(per >= 60) { else } } { printf("Failed!n"); } printf("GradeAn"); } return 0; } else { if(per >= 50) { printf("Grade Bn"); } else { if(per >= 40) { printf("Grade Cn"); }
  • 18. A switch statement allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable being switched on is checked for each switch case. switch(expression) { case constant-expression : statement(s); break; /* optional */ case constant-expression : statement(s); break; /* optional */ /* you can have any number of case statements */ default : /* Optional */ statement(s); } Some important keywords: 1) Break: This keyword is used to stop the execution inside a switch block. It helps to terminate the switch block and break out ofit. 2) Default: This keyword is used to specify the set of statements to execute if there is no case match.
  • 19. Important Points About Switch Case Statements: 1) The expression provided in the switch should result in a constant value otherwise itwould not be valid. Some valid expressions for switch case will be, // Constant expressions allowed switch(1+2+23) switch(1*2+3%4) // Variable expression are allowed provided // they are assigned with fixed values switch(a*b+c*d) switch(a+b+c) 2) Duplicate case values are not allowed. 3) The default statement is optional. Even if the switch case statement do not have adefault statement, it would run without any problem.
  • 20. 4)The break statement is used inside the switch to terminate a statement sequence. When a break statement is reached, the switch terminates, and the flow of control jumps to the next line following the switch statement. 5) The break statement is optional. If omitted, execution will continue on into the next case. The flow of control will fall through to subsequent cases until a break is reached. 6)Nesting of switch statements is allowed, which means you can have switch statements inside another switch. However nested switch statements should beavoided as it makes the program more complex and less readable. 7) Switch statements are limited to integer values only in the check condition.
  • 22. #include <stdio.h>int main(){ char ch; int a, b, result; // Asking for Input Simple Calculator using switch Statement case '*': result = a * b; break; case '/’: if(b==0) { printf(“Division by zero errorn"); printf("Enter an Operator (+, *, *, /): "); scanf("%c", &ch); printf("Enter two operands: n"); scanf("%d %d", &a, &b); switch(ch) { case '+': default: } else { } break; result = a / b; result = a + b; break; case '-': result = a - b; break; printf("n Enter correct optionn");break; } printf("Result = %d", result); return 0; }
  • 23. Write a C Programs using Switch to check whether a number is equal to 5, 10 and 100 #include<stdio.h> int main() { int number; printf("enter a number:"); scanf("%d",&number); switch(number){ case 10: printf("number is equals to 10"); break; case 50: printf("number is equal to 50"); break; case 100: printf("number is equal to 100"); break; default: printf("number is not equal to 10, 50 or 100"); } return 0; }
  • 24. C Program to Calculate Area of Circle, Rectangle and Triangle using a switch statement #include <stdio.h> #include <stdlib.h> #include <math.h> int main() { float area, radius, s1,s2,s3,base,height,sp;int choice; printf("1. Area of Circlen"); printf("2. Area of Triangle(Base and Height)n"); printf("3. Area of Triangle(All three Sides)n"); printf("Select your Choicen"); scanf("%d",&choice); switch(choice) { case 1: printf("You have chosen Area of Circlen"); printf("Enter the radiusn"); scanf("%f",&radius); area=3.14*radius*radius; printf("Area of Circle is %.2fn",area); break; case 2: printf("You have chosen Area of Triangle(Base and Height)n"); printf("Enter base and heightn"); scanf("%f%f",&base,&height); area=(base*height)/2; printf("Area of Triangle is %.2fn",area); break;
  • 25. case 3: printf("You have chosen Area of Triangle(All three Sides)n"); printf("Enter values of all three sidesn"); scanf("%f%f%f",&s1,&s2,&s3); sp=(s1+s2+s3)/2; area=sqrt(sp*(sp-s1)*(sp-s2)*(sp-s3)); printf("Area of Triangle is %.2fn",area); break; default: printf("Sorry, Invalid Choicen"); } printf("Thank Youn"); return 0;
  • 26.  In else if ladder, the control goes through the every else if statement until it finds true value of the statement or it comes to the end of the else if ladder. Incase of switch case, as per the value of the switch, the control jumps to the corresponding case.  The switch case is more compact than lot of nested else if. So, switch is considered to be more readable.  The use of break statement in switch is essential but there is no need of use of break in else if ladder.  The variable data type that can be used in expression of switch is integer only where as in else if ladder accepts integer type as well as character.
  • 27.  Another difference between switch case and else if ladder is that the switch statement is considered to be less flexible than the elseif ladder, because it allows only testing of a single expression against a list of discrete values.  Since the compiler is capable of optimizing the switch statement, they are generally considered to be more efficient. Each case in switch statement is independent of the previous one. In case of else if ladder, the code needs to be processed in the order determined by the programmer.  Switch case statement work on the basis of equality operatorwhereas else if ladder works on the basis of true false( zero/non- zero) basis.
  • 30. Conditional Operators (? :) / Ternary operator Conditional operators are used in decision making in C programming, i.e, executes different statements according to test condition whether it is either true or false. Syntax of conditional operators (Conditional expression) ? (expression1) : (expression2) If the conditional expression is evaluated to true , then expression1 is executed.If the conditional expression is evaluated to false , then expression2 is executed
  • 31. #include<stdio.h> int main() { int x, y ; printf(“ enter the value for x”); // x=10 scanf ( “%d”, &x ) ; printf(“y=%d”, y); return 0; } Or (using if-else) #include<stdio.h> int main() { int x, y ; printf(“ enter the value for x”); // x=10 scanf ( “%d”, &x ) ; if ( x > 5 ) y = 3 ; else y = 4 ; printf(“y=%d”, y); return 0; } y = ( x> 5 ? 3 : 4 ) ; //y=3 //This statement will store 3 in y if x is greater than 5, otherwise it will store 4 in y.
  • 32. Using Ternary operator to find the largest number. #include <stdio.h> int main() { int A, B, C, largest; printf("Enter three numbers: "); scanf("%d %d %d", &A, &B, &C); largest = A > B ? (A > C ? A : C) : (B > C ? B : C); printf("%d is the largest number.", largest); return 0; }
  • 40. Print numbers from 1 to 10 #include <stdio.h> int main() { int i; for (i = 1; i < 11; ++i) { printf("%d ", i); } return 0; }
  • 41. Program to calculate the sum of first n natural numbers // Positive integers 1,2,3...n are known as natural numbers #include <stdio.h> int main() { int num, count, sum = 0; printf("Enter a positive integer: "); scanf("%d", &num); // for loop terminates when num is less than count for(count = 1; count <= num; ++count) { sum += count; } printf("Sum = %d", sum); return 0; }
  • 42. Program to add numbers until the user enters zero #include <stdio.h> int main() { double number, sum = 0; // the body of the loop is executed at least once do { printf("Enter a number: "); scanf("%lf", &number); sum += number; } while(number != 0.0); printf("Sum = %.2lf",sum); return 0; }
  • 43. Difference Between for, while & do-while loop (Write programs also for each loop)
  • 44. Nested Loops Any number of loops can be defined inside another loop, i.e., there is no restriction for defining any number of loops. The nesting level can be defined at n times. You can define any type of loop inside another loop; for example, you can define 'while' loop inside a 'for' loop. Syntax of Nested loop Outer_loop { Inner_loop { // inner loop statements. Outer_loop and Inner_loop are the valid loops that can be a 'for' loop, 'while' loop or 'do- while' loop. } // outer loop statements. }
  • 45. Array int v; // regular variable, v=10 int v[5]; //1-D array, v={10,20,30,40} int v[2][4]; //2-D array, v={ {10,20,30,40}, {50,60,70,80}, };
  • 46. 1D array int A[10] = {3 ,6 ,5 ,8}; // n=4, array position = 0 to 3 A [0] A [1] A [2] A [3] Position of array starts with 0 & ends in n-1, where n= total count of elements A[1] =6 2D array ( element access can be either in row major order or incol major order) 3 6 5 8 5 3 2 1 A[1][1] =3 3 6 5 8 5 3 2 1 A [0] A [1] A [2] A [3] 3 6 5 8
  • 47. Example of nested for loop int main() { int i, j; // i= row position, j= col position // Declare the matrix int matrix[10][10] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }; Output: Given matrix is // in each set, count of elements represents count of col printf("Given matrix is n"); // Print the matrix using nested loopsfor (i = 0; i <3 ; i++) // row position , { for (j = 0; j <3 ; j++) //col position printf("%d ", matrix[i][j]); printf("n"); } return 0; } // each set is 1 row 1 2 3 4 5 6 7 8 9
  • 48. // 3.3 iteration : matrix[ 2][ 2 ]=9
  • 50. When to Use Which Loop • The for loop is appropriate when you know in advance how many timesthe loop will be executed. • The while and do-while loops are used when you don’t know in advancewhen the loop will terminate. The while loop when you may not want to execute the loop bodyeven once without satisfying the loop condition. The do loop when you’re sure you want to execute the loop body atleast once without satisfying the loop condition.
  • 56. #include <stdio.h> int main() {int i; int number, sum = 0; for (i = 1; i <= 10; ++i) { printf("Enter n%d: ", i);scanf("%d", &number); // if the user enters a negative number, break the loopif (number < 0) // negative number { break; } sum += number; Enter n1: 2 Enter n2: -3 Enter n3: Enter n4: Enter n5: Enter n6: Enter n7: Enter n8: Enter n9: Enter n10: Sum= } printf("Sum = %d", sum); // Sum=2 return 0; } // sum = sum + number// sum=0+2=2
  • 57. #include <stdio.h> int main() { int i; int number, sum = 0; for (i = 1; i <= 10; ++i) { printf("Enter n%d: ", i); scanf("%d", &number); // if the user enters a negative number, break the loopif (number < 0) { break; } sum += number; // sum = sum + number; } printf("Sum = %d", sum); return 0; }
  • 58. #include <stdio.h> int main() {int i; int number, sum = 0; for (i = 1; i <= 10; ++i) { printf("Enter n%d: ", i);scanf("%d", &number); // if the user enters a negative number, break the loop if (number < 0) { continue; Enter n1: 2 Enter n2: -3 Enter n3: 4 Enter n4: -1 Enter n5: 6 Enter n6: Enter n7: Enter n8: Enter n9: Enter n10: } sum += number; // sum = sum + number// sum=2+4=6 } Sum= printf("Sum = %d", sum); return 0; }
  • 59. #include <stdio.h> int main() { int i; int number, sum = 0; for (i = 1; i <= 10; ++i) { printf("Enter n%d: ", i); scanf("%d", &number); // if the user enters a negative number, break the loop if (number < 0) { // checking for negative number continue; // escape only the particular iteration } sum += number; // sum = sum + number; This line will be skipped every timecontinue statement is executed } printf("Sum = %d", sum); return 0; }
  • 62. 6. sum: printf(“%d”, a+b); //10+20=30 7. return 0;
  • 65. #include <stdio.h> int main() { Output int sum=0, i; for(i=0;i<=10;i++) { 1. sum=0+0=0 2. Sum=0+1=1 sum = sum+i; 3. Sum=1+2=3 if(i==5) { goto addition; } } addition: printf("%d", sum); return 0; } 4. Sum=3+3=6 5. Sum=6+4=10 6. Sum=10+5= 15
  • 66. Same Previous slide program with do-while statement #include <stdio.h> int main() { int sum=0,i=0;do { i++; sum = sum+i; if(i==5) { Output : 15 goto addition; } } while(i<=10); addition: printf("%d", sum); return 0; }
  • 67. Finding roots of a quadratic equation #include<stdio.h> #include<math.h> int main() { float a,b,c,desc,r1,r2,realpart,imgpart; printf("Enter the coefficients of a, b and c :"); scanf("%f%f%f",&a,&b,&c); if(a==0) { } printf("Coefficient of a cannot be zero... n");printf("Please try again... n"); return 1; desc=(b*b)-(4.0*a*c);
  • 68. if(desc==0) { } printf("The roots are real and equaln"); r1=r2=(-b)/(2.0*a); printf("The two roots are r1=r2=%fn",r1); else if(desc>0) { printf("The roots are real and distinctn"); r1=(-b+sqrt(desc))/(2.0*a); r2=(-b-sqrt(desc))/(2.0*a); printf("The roots are r1=%f and r2=%fn",r1,r2); }
  • 69. else { } printf("The roots are imaginaryn"); realpart=(-b)/(2.0*a); imgpart=sqrt(- desc)/(2.0*a); printf("The roots are r1=%f + i %fn",realpart,imgpart); printf("r2=%f - i %fn",realpart,imgpart); return 0; }
  • 70. Computation of binomial coefficients What is Binomial Coefficient Binomial coefficient (n, k) is the order of choosing ‘k’ results from the given ‘n’ possibilities. The value of binomial coefficient of positive n and k is given by where, n >= k Example
  • 71. The Binomial coefficient C(n,r)=n!/((n-r)!*r!) is the number of ways of picking ‘r’ unordered outcomes from n possibilities. In this equation, ! represents factorial of a number. Binomial coefficient involves calculation of three values based on factorial which can be calculated easily using user defined function/recursive function which will be covered in module 4. Here we are using direct calculation using separate for loop to calculate each value namely, x=n! y=(n-r)! z=r!
  • 72. #include<stdio.h> int main() { int i,n,r; Code long int x,y,z,nCr; // factorial of a number may cross the range of the integer,so used long int data type. printf(“enter the value of n and r”); scanf(“%d %d”, &n, &r); x=y=z=1; //calculate x as factorial n for(i=n; i>=1;i--) { x=x*i; }
  • 73. //calculate y as factorial (n-r) for(i=n-r; i>=1;i--) { y=y*i; } //calculate z as factorial r for(i=r; i>=1;i--) { z=z*i; } //Using x,y,z calculate binomial coefficient nCr nCr=x/(y*z); printf(“%dC%d=%d”, n,r,nCr); return 0; }
  • 74. Plotting of Pascal’s triangle. 0 row =1 1 row = (0+1), (1+0) = 1, 1 2 row = (0+1), (1+1), (1+0) = 1, 2, 1 3 row = (0+1), (1+2), (2+1), (1+0) = 1, 3, 3, 1 4 row = (0+1), (1+3), (3+3), (3+1), (1+0) = 1, 4, 6, 4, 1
  • 75. Properties of Pascal’s Triangle: • The sum of all the elements of a row is twice the sum of all the elements of its preceding row. For example, sum of second row is 1+1= 2, and that of first is 1. Again, the sum of third row is 1+2+1 =4, and that of second row is 1+1 =2, and so on. This major property is utilized to write the code in C program for Pascal’s triangle. • The sequence of the product of each element is related to the base of the natural logarithm, e. • The left and the right edges of Pascal’s triangle are filled with “1”s only. • All the numbers outside the triangle are “0”s. • The diagonals next to the edge diagonals contain natural numbers (1, 2, 3, 4, ….) in order. • The sum of the squares of the numbers of row “n” equals the middle number of row “2n”.
  • 76. #include<stdio.h> int main() { int rows, num=1,space,i,j; Code for (j=0;j<=i; j++) { if (j==0||i==0) num=1; printf(“enter number of rows”); scanf(“%d”, &rows); for(i=0;i<rows;i++) { for(space=1;space<=rows-i; space++) printf(“ “); else num=num*(i-j+1)/j; printf(“%4d”, num); } printf(“n”); } return 0; }
  • 77. Additional Programs for Practice C program to check character entered is vowel or consonant #include <stdio.h> int main() { char c; int lowercase_vowel, uppercase_vowel; printf("Enter an alphabet: "); scanf("%c", &c); // evaluates to 1 if variable c is a lowercase vowel lowercase_vowel = (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u'); // evaluates to 1 if variable c is a uppercase vowel uppercase_vowel = (c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U');
  • 78. // evaluates to 1 (true) if c is a vowel if (lowercase_vowel || uppercase_vowel) printf("%c is a vowel.", c); else printf("%c is a consonant.", c); return 0; }
  • 79. Additional Programs for Practice C program to check character entered is vowel or consonant #include <stdio.h> int main() { (nested if method) char ch; printf("Input a charactern"); scanf("%c", &ch); if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' &&ch <= 'Z’)) { if (ch=='a' || ch=='A' || ch=='e' || ch=='E' || ch=='i' || ch=='I' || ch=='o' || ch=='O' || ch== 'u' || ch=='U')printf("%c is a vowel.n", ch); else printf("%c is a consonant.n", ch); } else printf("%c is neither a vowel nor a consonant.n", ch); return 0; }
  • 80. Additional Programs for Practice C program to check given year is leap year or not. Check for Century year also. #include <stdio.h> int main() { int year; printf("Enter a year: "); scanf("%d", &year); // leap year if perfectly divisible by 400if (year % 400 == 0) { printf("%d is a leap year.", year); } // not a leap year if divisible by 100 // but not divisible by 400 else if (year % 100 == 0) { printf("%d is not a leap year.", year); // leap year if not divisible by 100 // but divisible by 4 else if (year % 4 == 0) { printf("%d is a leap year.", year); } // all other years are not leap yearselse { printf("%d is not a leap year.", year); } return 0; } }
  • 81. Additional Programs for Practice C program to check a number whether prime or not #include <stdio.h> main() { int n, i, c = 0; printf("Enter any number n:"); scanf("%d", &n); //logic for (i = 1; i <= n; i++) { if (n % i == 0) { c++; } } if (c == 2) { printf("n is a Prime number"); } else { printf("n is not a Prime number"); } return 0; }
  • 82. Additional Programs for Practice C program to Generate Fibonacci series #include <stdio.h> int main() { int number, i = 0, Next, first = 0, second = 1; printf("n Please Enter the Range Number: "); else{ } Next = first + second; first = second; second = Next; scanf("%d",&number); { while(i < number) printf("%d t", Next); i++; } if(i <= 1) { Next = i; } return 0;
  • 83. Additional Programs for Practice C program for printing a multiplication table for a given number #include <stdio.h> int main(){ int i, num; /* Input a number to print table */ printf("Enter number to print table: "); scanf("%d", &num); for(i=1; i<=10; i++){ printf("%d * %d = %dn", num, i, (num*i)); } return 0; }
  • 84. Additional Programs for Practice C Program to Print Characters in a String #include <stdio.h> int main() { char str[100]; int i = 0; printf("n Please Enter any String : "); scanf("%s", str); while (str[i] != '0') { printf("The Character at %d Index Position = %c n", i, str[i]); i++; } return 0; }
  • 85. Additional Programs for Practice C Program to Convert Decimal to Binary #include <stdio.h> int main() { int a[10], number, i, j; printf("n Please Enter the Number You want to Convert : ") ;scanf("%d", &number); for(i = 0; number > 0; i++) { a[i] = number % 2; number = number / 2; } printf("n Binary Number of a Given Number = "); for(j = i - 1; j >= 0; j--) { printf(" %d ", a[j]); } printf("n"); return 0;
  • 86. }
  • 87. Additional Programs for Practice C program for finding factorial of a number #include<stdio.h> void main() { int n,i=1,f=1; printf("n Enter The Number:"); scanf("%d",&n); //LOOP TO CALCULATE FACTORIAL OF A NUMBER while(i<=n) { f=f*i ;i++; } printf("n The Factorial of %d is %d",n,f); }
  • 88. Additional Programs for Practice C program to find GCD of two numbers using Euclid’s method #include <stdio.h> void main() { int num1, num2, gcd, lcm, remainder, numerator, denominator; printf("Enter two numbersn"); scanf("%d %d", &num1, &num2);if (num1 > num2) { numerator = num1; denominator = num2; } else { numerator = num2; denominator = num1; } remainder = numerator % denominator;
  • 89. while (remainder != 0) { numerator = denominator; denominator = remainder; remainder = numerator % denominator; } gcd = denominator; lcm = num1 * num2 / gcd; printf("GCD of %d and %d = %dn", num1, num2, gcd); printf("LCM of %d and %d = %dn", num1, num2, lcm); }
  • 90. Additional Programs for Practice C program to check Palindrome using while loop #include <stdio.h> int main(){ int num, temp, rem, rev = 0; printf("enter a number:n"); scanf("%d", &num); temp = num; while ( temp > 0){ rem = temp %10; rev = rev *10+ rem; temp = temp /10; } printf("reversed number is = %dn", rev);if ( num == rev ) printf("n%d is Palindrome Number.n", num); else printf("%d is not the Palindrome Number.n", num); return 0; }
  • 91. Additional Programs for Practice Half Pyramid of Numbers #include <stdio.h>int main() { int i, j, rows; printf("Enter the number of rows: "); scanf("%d", &rows); for (i = 1; i <= rows; ++i) { for (j = 1; j <= i; ++j) { printf("%d ", j); Output 1 1 2 1 2 3 1 2 3 4 1 2 3 4 5 } printf("n"); } return 0; }
  • 92. Additional Programs for Practice Half Pyramid of Alphabets#include <stdio.h> int main() { int i, j; char input, alphabet = 'A'; printf("Enter an uppercase character you want toprint in the last row: "); scanf("%c", &input); for (i = 1; i <= (input - 'A' + 1); ++i) { for (j = 1; j <= i; ++j) { printf("%c ", alphabet); Output A B B C C C D D D D E E E E E } ++alphabet; printf("n"); } return 0; }
  • 93. Additional Programs for Practice Half Pyramid of * #include <stdio.h> int main() { int i, j, rows; printf("Enter the number of rows: "); scanf("%d", &rows); for (i = 1; i <= rows; ++i) { for (j = 1; j <= i; ++j) { printf("* "); } printf("n"); Output * * * * * * * * * * * * * * * } return 0; }
  • 94. Additional Programs for Practice Inverted half pyramid of * #include <stdio.h> int main() { int i, j, rows; printf("Enter the number of rows: "); scanf("%d", &rows); for (i = rows; i >= 1; --i) { for (j = 1; j <= i; ++j) { printf("* "); Output * * * * * * * * * * * * * * * } printf("n"); } return 0; }
  • 95. Additional Programs for Practice Full Pyramid of * #include <stdio.h> int main() { int i, space, rows, k = 0; printf("Enter the number of rows: ");scanf("%d", &rows); for (i = 1; i <= rows; ++i, k = 0) { for (space = 1; space <= rows - i; ++space) { printf(" "); } while (k != 2 * i - 1) { printf("* "); ++k; Output * * * * * * * * * * * * * * * * * * * * * * * * * } printf("n"); } return 0; }
  • 96. Question Bank 1. Explain formatted and unformatted input-output functions in C with syntax and example. 2. Explain the various conditional branching statements with syntax and example. 3.Explain the various unconditional branching statements with syntax and example. 4. Explain the different looping statements in C with syntax and example. 5. Differentiate between while and do-while loop. 6. Explain the switch statement with syntax and example program. 7. Evaluate following programi = 1; L: if ( i > 2) { printf(“Saturday”);i = i – 1; goto L; } printf(“Sunday”); Explain your result briefly.
  • 97. Question Bank 8.State the drawback of else-if ladder. Explain how you resolve with suitable example. 9. Explain break and continue statements with respect to do-while, while and forloop with suitable examples. 10. Explain ternary operator with suitable examples. 11. Write a C program to simulate simple calculator that performs arithmetic operations using switch statement. An error message should be displayed, if anyattempt is made to divide by zero. 12. 20. An electric power distribution company charges it’s domestic consumers as follows: Write a C program, to compute and print amount to be paid by customer. 13. Distinguish between the following: i. goto and if ii. break and continue. Consumption Units Rate of charge 0 – 200 Rs. 0.50 per units 201 – 400 Rs. 100 + Rs. 0.65 per unit excess of 200 401 – 600 Rs. 230 + Rs. 0.80 per unit excess of 400 601 – above Rs. 390 + Rs. 1.00 per unit excess of 600
  • 98. Question Bank Programming exercises 1. Using if-else statement a. C program for largest of two numbers. b. C program to check number is even or odd. c. C program to check number is positive or negative. d. C program to check person is eligible to cast his vote e. C program to check character entered is vowel or consonant f. C program to check given year is leap year or not g. C program to check number is prime or not 2. Using Conditional Operator (?: ) a. C program to find largest of three numbers
  • 99. Question bank 3. Using else-if ladder statement a. C program to find largest of three numbers b. C program to find grade of a student c. C program to perform arithmetic operations 4. Using nested if statement a. C program to find largest of three numbers 5. Using for loop a. Sum of N natural numbers b. Generate Fibonacci series c. Finding factorial of a number d. Write a C program to get this triangle of numbers as a result.1 1 2 1 2 3 1 2 3 4 1 2 3 4 5
  • 100. Question bank 6. Using while loop a. Sum of N natural numbers b. Find GCD of two numbers using Euclid’s method c. Palindrome d. Factorial of a number 7. Using do-while loop a. Sum of N natural numbers b. Factorial of a number 8. Write a C Program for: a. Finding roots of a quadratic equation b. computation of binomial coefficients c. plotting of Pascal’s triangle.