Lab - 5: Problems involving if-then-else structures.
(i) Aim: Write a C program to find the max and min of four numbers using if-else.
Program:
#include<stdio.h>
int main()
{
int a, b, c, d, min, max;
printf("Enter 4 numbers one by one: \n");
scanf("%d %d %d %d", &a, &b, &c, &d);
if (a >= b && a >= c && a >= d)
max = a;
else if(b >= c && b>= d)
max = b;
else if(c >= d)
max = c;
else
max = d;
printf("\nThe maximum number is: %d", max);
if (a <= b && a <= c && a <= d)
min = a;
else if(b <= c && b<= d)
min = b;
else if(c <= d)
min = c;
else
min = d;
printf("\nThe minimum number is: %d", min);
return 0;
}
(ii) Aim: Write a C program to generate electricity bill.
Program:
#include<stdio.h>
int main()
{
int custnum, units;
float charges;
printf("Enter Customer No. and Units consumed: ");
scanf("%d %d", &custnum, &units);
if (units <= 200)
charges = 0.5 * units;
else if (units <= 400)
charges = 100 + 0.65 * (units - 200);
else if (units <= 600)
charges = 230 + 0.8 * (units - 400);
else
charges = 390 + (units - 600);
printf("Customer No.: %d ", custnum);
printf("\nCharges: Rs. %.2f", charges);
return 0;
}
(iii) Aim: Find the roots of the quadratic equation.
Program:
#include<stdio.h>
#include<math.h>
int main()
{
int a, b, c;
double d, r1, r2;
printf("The quadratic equation is ax^2 + bx + c = 0. \n");
printf("Enter the values of a, b and c one by one: \n");
scanf("%d %d %d", &a, &b, &c);
d = b * b - 4 * a * c;
if (d < 0)
printf("\nThe roots are imaginary.");
else
{
if (d == 0)
printf("\nThe roots are real and equal.");
else
printf("\nThe roots are real and unequal.");
r1 = (-b + sqrt(d)) / (2 * a);
r2 = (-b - sqrt(d)) / (2 * a);
printf("\nThe roots are as follows:");
printf("\nr1 = %lf and r2 = %lf", r1, r2);
}
return 0;
}
(iv) Aim: Write a C program to simulate a calculator using switch case.
Program:
#include<stdio.h>
int main()
{
char oper;
int n1, n2;
printf("**Simple Calculator**");
printf("\nEnter any two numbers: ");
scanf("%d %d", &n1, &n2);
printf("Select an operator (+ or - or * or / or %%): ");
scanf(" %c", &oper);
switch(oper)
{
case '+':
printf("%d + %d = %d", n1, n2, n1 + n2);
break;
case '-':
printf("%d - %d = %d", n1, n2, n1 - n2);
break;
case '*':
printf("%d * %d = %d", n1, n2, n1 * n2);
break;
case '/':
printf("%d / %d = %d", n1, n2, n1 / n2);
break;
case '%':
printf("%d %% %d = %d", n1, n2, n1 % n2);
break;
default:
printf("Invalid operator...");
}
return 0;
}
(v) Aim: Write a C program to find the given year is a leap year or not.
Program:
#include<stdio.h>
int main()
{
int year;
printf("Enter a year: ");
scanf("%d", &year);
if((year % 400 == 0) || (year % 4 == 0) && (year % 100 != 0))
printf("%d is a leap year.", year);
else
printf("%d is not a leap year.", year);
return 0;
}