Module 2 (Programs)
Module 2 (Programs)
• The basic decision statement in the computer is the two way selection.
• The decision is described to the computer as conditional statement that can be answered TRUE or
FALSE.
• If the answer is TRUE, one or more action statements are executed.
• If answer is FALSE, the different action or set of actions are executed.
• Regardless of which set of actions is executed, the program continues with next statement.
• C language provides following two-way selection statements:
• if statement
• if – else statement
• Nested if else statement
• Cascaded if else (also called else-if ladder)
IF STATEMENT
IF...ELSE STATEMENT
NESTED IF .. ELSE STATEMENT
ELSE-IF LADDER OR CASCADED IF ELSE:
SWITCH STATEMENT
int main()
else
else
}
4. The else if ladder
if(condition_expression_One)
{
statement1;
}
else if (condition_expression_Two)
{
statement2;
}
else if (condition_expression_Three)
{
statement3;
}
else
{
statement4;
}
C Program to print grade of a student using else-if Ladder
int main(){
int marks;
printf("Enter your marks between 0-100\n");
scanf("%d", &marks);
if(marks >= 90){ Output1:
printf("YOUR GRADE : A\n"); Enter your marks
}
96
else if (marks >= 70 && marks < 90)
{ YOUR GRADE : A
printf("YOUR GRADE : B\n"); Output 2:
}
Enter your marks
else if (marks >= 50 && marks < 70)
{ 35
printf("YOUR GRADE : C\n"); YOUR GRADE : Failed
}
else
printf("YOUR GRADE : Failed\n");
}
APPLICATION
PROGRAM
An electricity board charges the following rates for the use of electricity: for the first 200 units 80
paise per unit: for the next 100 units 90 paise per unit: beyond 300 units Rs. 1 per unit. All users are
charged a minimum of Rs. 100 as meter charge. If the total amount is more than 400, then an
additional surcharge of 15% of total amount is charged. Write a program to read the name of the
user, number of units consumed and print out the charges.
Algorithm
Step 1: [Start]
Begin Step 5:[Calculate the amount]
Step 2: [Input customer name] amount = amount/100
Read name amount = amount+100
Step 3: [Input unit consumed] Step 6: [Check if amount is greater than
Read n 400 then calculate additional charge of
15%]
Step 4: [Check units consumed to calculate the
amount] if amount > 400 then
if n < = 200 calculate amount amount + amount *
15/100
amount = n*80
end if
otherwise check if n > 200 and n <= 300 then
calculate Step 7: [Print total amount to be paid by
amount = 200 * 80
the customer]
Bhagya
275
switch(expression)
{
case label 1 : block1;
break;
case label 2 : block2;
break;
…………..
…………..
case label n : block n;
break;
default : default block;
break;
}
Lab Program
Design and Develop a program to solve simple computational problems using
arithmetic expressions and use of each operator leading to simulation of a
commercial calculator. (No built-in math function)
Algorithm
Step 1: Start the program
Step 4: if the entered case option is invalid code the print “Wrong Choice”
Eg :
#include<stdio.h>
#include<math.h>
void main()
{
int n,sum,d1,d2,d3; OUTPUT:
d3= n%10;
d2= (n/10)%10;
d1=n/100;
sum= pow(d1,3)+pow(d2,3)+pow(d3,3);
if(sum==n)
printf(“Armstrong number");
else
printf(" Not an armstrong number");
}
C Loop Constructs
Difference between the 3 loop constructs
void main()
Output
{
enter n : 4
int n ,sum=0,i=0;
sum of the series is 10
printf("enter n : ");
scanf("%d",&n);
while(i<=n)
{
sum = sum+i;
i++;
}
printf("sum of the series is
%d",sum);
}
LAB PROGRAM – 4
{ int n; enter n 4
scanf("%d",&n); number is 2
{ number is 4
Output: 1 2
JUMPS IN LOOPS
Break and continue: break and continue are unconditional control construct.
ii. Continue
Statement is helpful to skip particular set of statements in loop body and to
continue execution from the beginning of loop.
Following syntax clearly depicts how control shifts to beginning of a loop on
finding continue statement
Example program for continue statement
main() {
int i;
for(i=1;i<=5;i++)
{
if(i==3)
{
continue;
}
printf(“%d ”,i);
}
Output: 1 2 4 5
goto statement
Syntax
goto label ;
……
……
……
label : statement;
Forward Jump Backward Jump
Write a C program to find sum of 10
natural numbers using goto
#include<stdio.h> Output :
void main() Sum= 55
{
int sum=0,i=0;
top : sum= sum+i;
i++;
if(i<=10)
goto top;
printf("sum = %d",sum);
}
return statement
► The return statement is used in a function to return a value to the calling function.
► The return statement can be written anywhere and often inside the function definition.
► Still, after the execution of the first return statement, all the other return statements will be terminated
and will be of no use.
► The reason why we have the two syntaxes for the return statement is that the return statement can be used
in two ways.
► First is that you can use it to terminate the execution of the function when the function is not returning any
value.
return;
⮚ Second, it is to return a value with function calls, and here, the datatype of expression should be the same
as the datatype of function.
⮚ return expression;
⮚ Here the expression can be any variable, number, or expression. All the return examples given below are
valid in C.
• return x;
• return 0;
• return x++;
• return(x+y);
Example: Using the return statement in void functions
#include<stdio.h>
void main()
{
Output:level1
printf("level1\n");
return;
printf("level2\n");
}
C Loop Constructs
Loop (Iterative) Statements
► In the syntax given above ‘while’ is a key word and condition is at beginning of the loop.
► If the test condition is true the body of while loop will be executed.
► After execution of the body, the test condition is once again evaluated and if it is true, the body
is executed once again.
► This process is repeated until condition finally becomes false and control comes out of the body
of the loop.
While loop
Output
#include <stdio.h>
int main () { value of a: 10
int a = 10; value of a: 11
while( a < 20 ) { value of a: 12
printf("value of a: %d\n", a); value of a: 13
a++; value of a: 14
} value of a: 15
return 0; value of a: 16
} value of a: 17
value of a: 18
value of a: 19
C program to print digits from 1 to 5
#include <stdio.h>
main()
{
int N=5, i=1; Output
1
2
3
while (i<=N) 4
{ 5
BMS
printf("%d\n", i);
i=i+1;
}
printf("BMS");
}
C program to calculate the sum from 1 to 5 using While
loop
#include <stdio.h> Output
main() Sum=15
{
int N=5, i=1, sum=0;
while (i<=N)
{
sum=sum+i;
i=i+1;
}
printf("Sum=%d",sum);
}
C program to calculate the sum from m to n using While loop
#include <stdio.h>
main()
{
int m, n, sum=0;
Input
Enter the value of m and n: 5 10
printf("Enter the value of m and n: "); Output
scanf("%d%d",&m,&n); Sum=45
while (m<=n)
{
sum=sum+m;
m=m+1;
}
printf("Sum=%d",sum);
}
Write a C program to find factorial of given number
#include <stdio.h>
main() {
int i, fact, n;
i=1;
fact=1;
printf("Enter the number to find Factorial: ");
scanf("%d",&n);
while(i<=n)
{
fact=fact*i;
i=i+1;
}
printf("Factorial=%d",fact);
}
Input
Enter the number to find Factorial: 4
Output
Factorial=24
Write a C program to find largest of five numbers
using ternary operator and while loop.
#include <stdio.h>
main()
Input
{
int i=1,large=-32768, num;
Enter the number: 12
Enter the number: 45
while (i<=5)
Enter the number: 38
{
Enter the number: 150
printf("\nEnter the number: ");
Enter the number: -2
scanf("%d",&num);
large=(num>large)?num:large;
Output
i++;
}
Largest=150
printf("Largest=%d",large);
}
Write a C program to read the numbers until -1 is encountered. Also
count the negative, positive and zeros entered by user.
#include <stdio.h> else
main()
zeros++;
{
printf("\nEnter the number: ");
int num;
int neg=0, pos=0, zeros=0;
scanf("%d",&num);
}
printf("\nEnter -1 to exit");
printf("\nEnter the number: "); printf("Count of Postive Numbers=%d\n",pos);
scanf("%d",&num); printf("Count of Negative Numbers=%d\n",neg);
while (num!=-1)
printf("Count of Zeros=%d",zeros);
{
}
if(num>0)
pos++;
else if (num<0)
neg++;
Write a program to accept a name and print
the name for a specified number of times
#include<stdio.h>
void main()
{ enter name
char name[30]; jim
int n ,i=0; enter the number of times to print the name
printf("enter name \n"); 3
scanf("%s",name); name is : jim
printf("enter the number name is : jim
of times to print the name \n");
name is : jim
scanf("%d",&n);
while(i<n)
{
printf("name
is : %s \n",name);
i++;
}
}
Write a C program to find sum of given
series using while loop (1+2+3+… +n)
#include<stdio.h>
void main()
Output
{
enter n : 4
int n ,sum=0,i=0;
sum of the series is 10
printf("enter n : ");
scanf("%d",&n);
while(i<=n)
{
sum =
sum+i;
i++;
}
printf("sum of the
series is %d",sum);
}
Design and develop a C program to find the reverse of
an integer number NUM and check whether it is
PALINDROME or NOT. Implement a C program for the
developed algorithm that takes an integer number as
input and output the reverse of the same with
suitable messages. Ex: Num: 1234, Reverse: 4321, Not
a Palindrome.
#include <stdio.h> if (temp == rev)
int main() printf(“This number %d is a palindrome\n”,temp);
{ else
int n, rev = 0, digit, temp, rev; printf(“This number %d is not a palindrome\n”,temp);
printf("Enter an integer: \n”); return 0;
scanf("%d", &n); }
temp= n;
while( n!=0 ) OUTPUT
{ digit = n%10; Enter an integer :
rev = rev*10 + digit; 5678
n /= 10; Given number is 5678
} It‟s reverse is 8765
printf(“Given number is %d\n”,temp); This number 5678 is not a palindrome
printf(“It‟s reverse is %d\n”,rev);
Write a program to compute GCD & LCM
of 2 numbers
#include <stdio.h> while (remainder != 0)
void main() {
{ numerator = denominator;
int num1, num2, gcd, lcm, remainder, denominator = remainder;
numerator, denominator;
remainder = numerator % denominator;
}
printf("Enter two numbers\n");
gcd = denominator;
scanf("%d %d", &num1, &num2); lcm = num1 * num2 / gcd;
if (num1 > num2) printf("GCD of %d and %d = %d\n", num1, num2, gcd);
{ printf("LCM of %d and %d = %d\n", num1, num2, lcm);
numerator = num1; }
denominator = num2;
} OUTPUT
else
Enter two numbers
{ 30
numerator = num2;
40
denominator = num1; GCD of 30 and 40 = 10
}
LCM of 30 and 40 = 120
remainder = numerator % denominator;
do…. while loop
do…. while loop: It is a post-test loop (also
called exit controlled loop) it has two keywords
do and while.
printf("BMS");
}
Program to print the value of a from 10
to 19 using do while
#include <stdio.h> value of a: 10
int main () { value of a: 11
i=1; Input
fact=1; Enter the number to find
printf("Enter the number to find Factorial: Factorial: 4
");
scanf("%d",&n);
Output
do
{ Factorial=24
fact=fact*i;
i=i+1;
}
while(i<=n);
printf(“factorial= %d\n”,fact);
Write a C program to find sum of digits
in a given number
Write a C program to find sum of digits in a given number
#include <stdio.h>
void main()
{
int n, sum = 0, remainder;
printf("Enter an integer\n");
scanf("%d", &n);
do {
remainder = n % 10;
sum = sum + remainder;
n= n / 10;
}while (n != 0);
It is another pre-test loop (also called entry controlled loop) that provides concise loop
control structure.
It has one keyword for.
One important aspect of for loop is all the three components of a loop (viz. initializing,
testing condition and updation (increment/decrement)) is given in the head of for loop.
General Syntax:
#include <stdio.h>
int main()
{
char ch;
//Print characters from 'A' to 'Z'
for (ch = 'A'; ch <= 'Z'; ch++)
//there is a whitespace after %c so that the
//characters have spaces in between.
printf("%c ", ch);
return 0;
}
Program to generate multiplication table
#include <stdio.h> Output
int main()
{
Int number, i;
printf("Enter an integer: ");
scanf("%d", &number);
printf("Multiplication table of %d: \n", number);
for (i = 1; i <= 10; ++i) {
printf("%d * %d = %d \n", number, i, number * i);
}
return 0;
}
C program to print digits from 1 to 5
#include <stdio.h>
main()
{ Output
int N=5, i; 1
2
for(i=1;i<=N;i++) 3
{ 4
printf("%d\n", i); 5
} BMS
printf("BMS");
}
Write a C program to find factorial of given number
#include <stdio.h>
main() {
int i, fact, n;
Input
printf("Enter the number to find Factorial: "); Enter the number to find Factorial: 4
scanf("%d",&n);
fact=1; Output
for(i=1;i<=n;i++) Factorial=24
{
fact=fact*i;
}
printf("Factorial=%d",fact);
}
Write a program to print n numbers
using for loop
Write a program to print n numbers
#include<stdio.h>
{ int n; enter n 4
scanf("%d",&n); number is 2
{ number is 4
printf("\n number is
%d",i);
}
}
Write a C program to generate a fibonacci
series for a user entered value of n using for
loop
#include<stdio.h>
int main()
{
int n = 9;
int a = 0, b = 1;
int nextTerm;
printf("%d, ",nextTerm);
}
return 0;
Difference between While, Do-While and For loop
Nested Loops
► A nested loop means a loop statement inside another loop statement. That is why
nested loops are also called “loop inside loops“.
► We can define any number of loops inside another loop.
Nested for Loop
► Nested for loop can be used to control the number of times that a particular set of
statements will be executed.
► Another outer loop could be used to control the number of times that a whole loop is
repeated.
NOTE:
⮚ Loops should be properly indented so that a reader can easily determine which
statements are contained within each of the statement.
⮚ Although this feature will work with any loop such as while,do-while and for,it is most
commonly used with the for loop,because this is easiest to control.
Nested for Loops(Contd…)
for(initialization;condition;increment)
{
for(initialization;condition;increment)
{
//Statement of inside loop
}
// Statement of outer loop
}
C Program to Print Pyramids and Patterns
Half Pyramid of *
#include <stdio.h>
int main()
{
*
int i, j;
**
for (i = 1; i <=5; i++)
***
{
****
for (j = 1; j <= i; j++) {
*****
printf("* ");
}
printf("\n");
}
return 0;
}
Half Pyramid of Numbers
#include <stdio.h>
int main()
1 {
12 int i, j;