Module_2_P2 (1)
Module_2_P2 (1)
Module_2_P2 (1)
Module 2
Prof.Rajeshwari R, AssistantProfessor
Dept. of CSE, CMRIT, Bangalore
Conditional Branching
.
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”.
else
printf("%d is the largest number.", C);
return 0;
}
Exercise Program
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,
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.
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;
#include <stdio.h>
int main()
{
int num, count, sum = 0;
return 0;
}
Program to add numbers until the user enters zero
#include <stdio.h>
int main()
{
double number, sum = 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.
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
• 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>
return 0;
}
#include <stdio.h>
int main() {
int i;
int number, sum = 0;
return 0;
}
#include <stdio.h>
return 0;
}
#include <stdio.h>
int main() {
int i;
int number, sum = 0;
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;
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
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
#include <stdio.h>
int main() {
char c;
int lowercase_vowel, uppercase_vowel;
printf("Enter an alphabet: ");
scanf("%c", &c);
if (lowercase_vowel || uppercase_vowel)
else
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
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
#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;
#include <stdio.h>
void main()
{
int num1, num2, gcd, lcm, remainder, numerator,
denominator;
#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
#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
#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”);
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