0% found this document useful (0 votes)
2 views100 pages

Module_2_P2 (1)

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 100

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




.
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);
}
}
Program to find odd/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);
}
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
Program to find the largest number.
#include <stdio.h>
int main()
{
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
Exercise Program Solution
#include <stdio.h>
int main()
{
int var1, var2; else
printf("Input the value of var1:"); {
scanf("%d", &var1); printf("Input
printf("var1 is equal to var2\n");
the value of var2:"); }
scanf("%d",&var2); return 0;
if (var1 != var2)
}
{
printf("var1 is not equal to var2\n");
//Nested if elseif
(var1 > var2)
{
printf("var1 is greater than var2\n");
}
else
{
printf("var2 is greater than var1\n");
}
}
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 > Exercise Program Solution
int main()
{
float s1, s2, s3, s4, s5, per; else
printf("Enter marks of 5 subject\n"); {
scanf("%f %f %f %f %f", &s1, &s2, &s3, &s4, &s5); printf("Failed!\n");
per = ((s1 + s2 + s3 + s4 + s5) / 5)*100; }
}
if(per >= 60) }
{
printf("Grade A\n"); return 0;
} }
else
{
if(per >= 50)
{
printf("Grade B\n");
}
else
{
if(per >= 40)
{
printf("Grade C\n");
}
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) Some important keywords:
{
case constant-expression : 1) Break: This keyword is used to stop the
statement(s); execution inside a switch block. It helps to
break; /* optional */ terminate the switch block and break out ofit.

case constant-expression : 2) Default: This keyword is used to specify the


statement(s); set of statements to execute if there is no case
break; /* optional */ match.

/* you can have any number of case statements */


default : /* Optional */
statement(s);
}
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 be avoided as it makes the
program more complex and less readable.

7) Switch statements are limited to integer values only in the check condition.
Simple Calculator using switch Statement
case '*':
#include <stdio.h>int result = a * b;
main(){ break;
char ch; case '/’:
int a, b, result; if(b==0)
{
// Asking for Input printf(“Division by zero error\n");
printf("Enter an Operator (+, *, *, /): "); }
scanf("%c", &ch); else
printf("Enter two operands: \n"); {
scanf("%d %d", &a, &b); result = a / b;
switch(ch) }
{ break;
case '+': default:
result = a + b; printf("\n Enter correct option\n");break;
break; }
case '-': printf("Result = %d", result);
result = a - b; return 0;
break; }
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>
case 2:
#include <stdlib.h>
printf("You have chosen Area of
#include <math.h>
Triangle(Base and Height)\n");
int main()
printf("Enter base and height\n");
{
scanf("%f%f",&base,&height);
float area, radius, s1,s2,s3,base,height,sp;int
area=(base*height)/2; printf("Area
choice;
of Triangle is
printf("1. Area of Circle\n");
%.2f\n",area);
printf("2. Area of Triangle(Base and Height)\n");
break;
printf("3. Area of Triangle(All three Sides)\n");
printf("Select your Choice\n");
scanf("%d",&choice);
switch(choice)
{
case 1:
printf("You have chosen Area of Circle\n");
printf("Enter the radius\n");
scanf("%f",&radius);
area=3.14*radius*radius;
printf("Area of Circle is %.2f\n",area);
break;
case 3:
printf("You have chosen Area of Triangle(All three Sides)\n");
printf("Enter values of all three sides\n");
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 %.2f\n",area);
break;
default:
printf("Sorry, Invalid Choice\n");
}
printf("Thank You\n");
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. In case 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 else if 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.
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
Or (using if-else)
#include<stdio.h>
int main() #include<stdio.h>
{ int main()
int x, y ; {
printf(“ enter the value for x”); int x, y ;
// x=10 printf(“ enter the value for x”);
scanf ( “%d”, &x ) ; // x=10
scanf ( “%d”, &x ) ;
y = ( x> 5 ? 3 : 4 ) ; //y=3 if ( x > 5 )
//This statement will store 3 in y if y=3;
x is greater than 5, otherwise it else
will store 4 in y. y=4;
printf(“y=%d”, y); printf(“y=%d”, y);
return 0; return 0;
} }
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;
}
Output

1
2
3
4
5
Output

1
2
3
4
5
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 Outer_loop and Inner_loop are


{ the valid loops that can be a
Inner_loop 'for' loop, 'while' loop or 'do-
{ while' loop.
// inner loop statements.
}
// 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

3 6 5 8
A [1] A [2] A [3]
A [0]

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)
3658
5321

3 6 5 8
A[1][1]
5 3 2 1
=3
A [0] A [1] A [2] A [3]
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
// each set is 1 row
// in each set, count of elements represents count of col
1 2 3
printf("Given matrix is \n");
4 5 6
// Print the matrix using nested loopsfor 7 8 9
(i = 0; i <3 ; i++) // row position ,
{
for (j = 0; j <3 ; j++) //col position

printf("%d ", } return 0; }


matrix[i][j]);
printf("\n");
// 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.



#include <stdio.h>

int main() {int


i;
int number, sum = 0;

for (i = 1; i <= 10; ++i) Enter n1: 2


{ Enter n2: -3
printf("Enter n%d: ", i);scanf("%d", Enter n3:
Enter n4:
&number);
Enter n5:
// if the user enters a negative number, break the loopif
Enter n6:
(number < 0) // negative number Enter n7:
{ Enter n8:
break; Enter n9:
} Enter n10:
sum += number; // sum = sum + number// sum=0+2=2 Sum=
}
printf("Sum = %d", sum); // Sum=2

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 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;
Enter n1: 2
for (i = 1; i <= 10; ++i) Enter n2: -3
{ Enter n3: 4
printf("Enter n%d: ", i);scanf("%d", Enter n4: -1
&number); Enter n5: 6
Enter n6: Enter
// if the user enters a negative number, break the loop n7: Enter n8:
if (number < 0) Enter n9:
{ Enter n10:
continue;
}
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;
}
6. sum: printf(“%d”, a+b); //10+20=30
7. return 0;
#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) 4. Sum=3+3=6
{ 5. Sum=6+4=10
goto addition;
} 6. Sum=10+5= 15
} addition:
printf("%d", sum);
return 0;
}
Same Previous slide program with do-while statement
#include <stdio.h>
int main()
{
int sum=0,i=0;do
{
i++; Output : 15
sum = sum+i;

if(i==5)
{
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 equal\n");
r1=r2=(-b)/(2.0*a);
printf("The two roots are r1=r2=%f\n",r1);
}
else if(desc>0)
{
printf("The roots are real and distinct\n");
r1=(-b+sqrt(desc))/(2.0*a);
r2=(-b-sqrt(desc))/(2.0*a);
printf("The roots are r1=%f and r2=%f\n",r1,r2);
}
else
{
printf("The roots are imaginary\n");
realpart=(-b)/(2.0*a); imgpart=sqrt(-
desc)/(2.0*a);
printf("The roots are r1=%f + i %f\n",realpart,imgpart);
printf("r2=%f - i %f\n",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> Code
int main()
{
int i,n,r;
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”.
Code

for (j=0;j<=i; j++)


#include<stdio.h>
{
int main()
{ if (j==0||i==0)
int rows, num=1,space,i,j; num=1;
else
printf(“enter number of rows”);
num=num*(i-j+1)/j;
scanf(“%d”, &rows);
printf(“%4d”, num);
for(i=0;i<rows;i++)
}
{
printf(“\n”);
for(space=1;space<=rows-i; space++)
}
printf(“ “);
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>
(nested if method)
int main()
{
char ch;
printf("Input a character\n");
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() { // leap year if not divisible by 100
int year; // but divisible by 4 else
printf("Enter a year: "); if (year % 4 == 0) {
scanf("%d", &year); printf("%d is a leap year.", year);
}
// leap year if perfectly divisible by 400if // all other years are not leap yearselse {
(year % 400 == 0) { printf("%d is not a leap year.", year);
}
printf("%d is a leap year.", year);
} return 0;
// 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);
}
Additional Programs for Practice
C program to check a number whether prime or not

#include <stdio.h>
main() {
int n, i, c = 0; if (c == 2)
printf("Enter any number n:"); {
scanf("%d", &n); printf("n is a Prime number");
}
//logic else
for (i = 1; i <= n; i++) {
{ printf("n is not a Prime number");
if (n % i == 0) }
{ return 0;
c++; }
}
}
Additional Programs for Practice

C program to Generate Fibonacci series

else{
#include <stdio.h> Next = first + second;
int main() first = second; second
{ = Next;
int number, i = 0, Next, first = 0, second = 1; }
printf("\n Please Enter the Range Number: ");
printf("%d \t", Next);
scanf("%d",&number); i++;
while(i < number) }
{
return 0;
if(i <= 1)
{
Next = i;
}
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 = %d\n", 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 numbers\n");


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 = %d\n", num1, num2, gcd);
printf("LCM of %d and %d = %d\n", 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 = %d\n", 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; Output
printf("Enter the number of rows: "); 1
scanf("%d", &rows);
12
for (i = 1; i <= rows; ++i)
{ 123
for (j = 1; j <= i; ++j) 1234
{ 12345
printf("%d ", j);
}
printf("\n");
}
return 0;
}
Additional Programs for Practice

Half Pyramid of Alphabets#include


<stdio.h>
int main() {
int i, j;
char input, alphabet = 'A'; Output
printf("Enter an uppercase character you want toprint A
in the last row: "); BB
scanf("%c", &input);
for (i = 1; i <= (input - 'A' + 1); ++i) {
CCC
for (j = 1; j <= i; ++j) { DDDD
printf("%c ", alphabet); EEEEE
}
++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: "); Output
scanf("%d", &rows); *
for (i = 1; i <= rows; ++i) { **
for (j = 1; j <= i; ++j) {
printf("* ");
***
} ****
printf("\n"); *****
}
return 0;
}
Additional Programs for Practice
Inverted half pyramid of *

#include <stdio.h>
int main() {
int i, j, rows; Output
printf("Enter the number of rows: ");
scanf("%d", &rows);
*****
for (i = rows; i >= 1; --i) ****
{ ***
for (j = 1; j <= i; ++j) **
{ *
printf("* ");
}
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); Output
for (i = 1; i <= rows; ++i, k = 0) { *
for (space = 1; space <= rows - i; ++space) ***
{
*****
printf(" ");
} ******
while (k != 2 * i - 1) *
{ ********
printf("* "); *
++k;
}
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: 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

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.
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
12
123
1234
12345
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.

You might also like