0% found this document useful (0 votes)
12 views

C Programming Notes 13-09-2024

Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

C Programming Notes 13-09-2024

Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 34

Session-1:

Date: 29-08-2024

Structure of the C Program:


==========================
1) Header file include section
2) Main function
3) User defined function [Optional]

Ex:
#include<stdio.h>
int main()
{
//block of code to execute

return 0;
}

Program-01:
Program to print "Welcome to C Programming" on my screen.
FileName: FirstProgram.c
Code:
#include<stdio.h>
int main()
{
printf("Welcome to C Programming");
getch();
}

Output:
Welcome to C Programming

-----------------------------------------------------------
Program-02:
Program to print your personal information.
FileName: SelfDetails.C
#include<stdio.h>
int main()
{
printf("Name = M.Srinu");
printf("Desg = Salesforce Trainer");
printf("Company = Technicalhub");
printf("Contact = 7731981144");
printf("Mail ID = srinu@technicalhub.io");
getch();
}

==========================================================================
Session-2:
Date: 30-08-2024

Data type and Variable:


-----------------------
Variable:
Variable is the name of the memory location where the actual value is to be
stored.

Data type:
It is used to specify what type of value is to be stored inside a variable.
Syntax:
datatype variable_name; // Declaration
or
datatype variable_name=value; // Declaration with initialization

S.No Datatype Format Specifier - Purpose


1) int %d - used to store all
the integer
type of values.
Ex: 100, 105,.....

2) char %c - used to store a


character. Ex: 'a','A'

3) float %f - used to store the


fractional numbers.
Ex: 3.142f,
2.45f,.....

4) double %lf - used to store the


large fractional
numbers. Ex:
3.142345,5.6789,....

How to declare variables in C:

int x;
x=10; //Accepted
x=3.142; //Generate an Error

char ch;
ch='A';
ch='z';
ch=10; //Error
ch=3.142; //Error

float n;
n=3.142f;

double m;
m=23.45677;

Practice1:
==========
FileName:TestDatatypes.C
#include<stdio.h>
int main()
{
int x=10;
char ch='I';
float pi=3.142f;
double n=3.3333333;
printf("%d\n",x);
printf("%c\n",ch);
printf("%f\n",pi);
printf("%lf\n",n);

return 0;
}

Practice2:
=========
//Program to find addition of two numbers
FileName: Add.C

#include<stdio.h>
int main()
{
int x=10;
int y=20;
int z;
z=x+y;

printf("%d\n",x); // x = 10 => printf("x = %d",x);


printf("%d\n",y); // y = 20 => printf("y = %d",y);
printf("%d\n",z); // sum = 30 => printf("sum = %d",z);

printf("x = %d\n",x);
printf("y = %d\n",y);
printf("sum = %d\n",z);
return 0;
}

Practice-3:
==========
Program to perform all the arithmetic Operations
FileName: ArithmeticOperations.C

#include<stdio.h>
int main()
{
int x=10,y=20;
int sum,diff,prod,div;
sum=x+y;
diff=x-y;
prod=x*y;
div=x/y;
printf("X value is: %d\n",x);
printf("Y value is: %d\n",y);
printf("Sum = %d\n",sum);
printf("Difference = %d\n",diff);
printf("Multiplication = %d\n",prod);
printf("Division = %d\n",div);
return 0;
}

Practice-4:
===========
Program to find the simple interest.
Formula: I = (P*T*R)/100;
FileName: SimpleInterest.C

Code:
#include<stdio.h>
int main()
{
int P,T,R;
float I;
//Assign the Values
P=100000;
T=22;
R=2;
I=(P*T*R)/100;
printf("Principal Amount = %d\n",P);
printf("Time in Months = %d\n",T);
printf("Rate of Interest = %d\n",R);
printf("Simple Interest = %f",I);

return 0;
}

How to read the input from the user:


===================================
In C programming we have a function called "scanf" which is used to read the input
from the user. Which is available in stdio.h header file.

Syntax:
scanf("Formatted String",&v1,&v2,....);
Ex:
int x;
scanf("%d",&x);

char ch;
scanf("%c",&ch);

float m;
scanf("%f",&m);

double n;
scanf("%lf",&n);

int x,y;
scanf("%d%d",&x,&y);

int x;
float y;
scanf("%d%f",&x,&y);

int x;
char ch;
float m;
scanf("%d%c%f",&x,&ch,&m);

scanf("%d%c%f",&ch,&x,&m); //Error raised because of wrong data types


mapping.

Difference betwee scanf() and printf():


---------------------------------------
Example1: To read and print one variable
int x;
scanf("%d",&x); //Reading

printf("%d",x); //Printing

Example2: To read and print two variables


int x,y;
scanf("%d%d",&x,&y); //Reading

printf("%d %d",x,y); //Printing

Example3: To read int,char,float and double in single scanf


int x;
char ch;
float p;
double q;
scanf("%d%c%f%lf",&x,&ch,&p,&q);

printf("%d %c %f %lf",x,ch,p,q); //For printing.

--------------------------------------------------------------------------
Practice-5:
==========
Program to find the simple interest by taking the input from the user.
FileName: SI.c

#include<stdio.h>
int main()
{
int P,T,R;
float I;

printf("Enter Principle, Time and Rate of interest\n");


scanf("%d%d%d",&P,&T,&R);

I=(P*T*R)/100;
printf("P = %d T = %d R = %d\n",P,T,R);
printf("Simple Interest = %f",I);
return 0;
}

================================================================================
Session-03
Date: 31-08-2024

Programs to Practice:
=====================
Program-03:
Program to find the area of Rectangle.
Formula: area= length*breadth
FileName: AreaOfRect.c
Code:
#include<stdio.h>
int main()
{
//Declare the variable
float L,B,Area;
//Reading of input
printf("Enter the L and B values\n");
scanf("%f%f",&L,&B);
//Processing
Area= L * B;
//Output
printf("Length = %f\n",L);
printf("Breadth = %f\n",B);
printf("Area of Rectangle = %.2f\n",Area);
return 0;

}
---------------------------------------------------------------
Program-04:
Program to find the Perimeter of Rectangle
Formula: Perimeter=2*(length+breadth)
FileName: Rect_Perimeter.C
Code:
#include<stdio.h>
int main()
{
int L,B,Perimeter;

printf("Enter Length and Breadth values\n");


scanf("%d%d",&L,&B);

Perimeter=2*(L+B);

printf("Length = %d\n",L);
printf("Breadth = %d\n",B);
printf("Perimeter = %d\n",Perimeter);

return 0;
}

-----------------------------------------------------------------
Program-05:
Program to find the area of Circle
Formula: area= 3.142*radius*radius
FileName: Area_Circle.C

Code:
#include<stdio.h>
int main()
{
float radius,area;
printf("Enter the radius of Circle\n");
scanf("%f",&radius);

area=3.142f*radius*radius;

printf("Radius of the Circle is: %.2f\n",radius);


printf("Area of the Circle is: %.2f\n",area);

return 0;
}
------------------------------------------------------------------------
Program-06:
Program to find the Perimeter of circle.
Formula: perimeter= 2*3.142*radius
FileName: Circle_Perimeter.C

Code:
#include<stdio.h>
int main()
{
float r,perimeter;
scanf("%f",&r);

perimeter=2*3.142f*r;

printf("Radius of the Circle is: %.2f\n",r);


printf("Perimeter of the Circle is: %.2f\n",perimeter);
return 0;
}

------------------------------------------------------------------------
Program-07:
Program-Program to find the area of Triangle.
Formula: area=1/2*b*h
FileName: AreaofTraingle.C

Code:
#include<stdio.h>
int main()
{
//Area of Triangle = 1/2*b*h
int b,h;
float area;

printf("Enter base and height\n");


scanf("%d%d",&b,&h);

area=1.0f/2*b*h;

printf("Area = %.2f",area);
return 0;
}
----------------------------------------------------------------------
Program-08:
Program to convert Fahrenheit (°F) to Celsius (°C) is.
Formula: Celsius(°C)= 5/9 ×(Fahrenheit(°F)−32)
Code:
#include <stdio.h>
int main()
{
float fahrenheit, celsius;

// Asking the user to input the temperature in Fahrenheit


printf("Enter temperature in Fahrenheit:\n");
scanf("%f", &fahrenheit);

// Converting Fahrenheit to Celsius


celsius = (fahrenheit - 32) * 5 / 9;

// Displaying the result


printf("%.2f Fahrenheit is equal to %.2f Celsius.\n", fahrenheit, celsius);

return 0;
}

----------------------------------------------------------------------
Program-09:
Program to Calculate the Area of a Triangle Using Heron's Formula
Formula: s=(a+b+c)/2, where a,b and c are the sides of the triangle.
area=sqrt(s*(s-a)*(s-b)*(s-c))
FileName: Herons_Formula.C
Code:
#include<stdio.h>
#include<math.h>
int main()
{ int a,b,c;
double s,area;
printf("Enter the sides of the Triangle\n");
scanf("%d%d%d",&a,&b,&c);

// Calculate the Area of Triangle as area=sqrt(s*(s-a)*(s-b)*(s-c))


s=(a+b+c)/2.0;
area=sqrt(s*(s-a)*(s-b)*(s-c));

printf("Sides of the Triangle are:\n");


printf("Side -1 = %d\n",a);
printf("Side -2 = %d\n",b);
printf("Side -3 = %d\n",c);
printf("Area of the Triangle is: %.2lf",area);

return 0;
}

-----------------------------------------------------------------------
Program-10:
Compute the Slope of a Line Given Two Points (x1,y1) and (x2,y2).
Formula: m=(y2-y1)/(x2-x1)
FileName: Slope.C
Code:
#include <stdio.h>
int main()
{
float x1, y1, x2, y2, slope;

// Asking the user to input the coordinates of the first point


printf("Enter coordinates of the first point (x1, y1):\n");
scanf("%f%f", &x1, &y1);

// Asking the user to input the coordinates of the second point


printf("Enter coordinates of the second point (x2, y2):\n");
scanf("%f %f", &x2, &y2);

// Calculating the slope using the formula: slope = (y2 - y1) / (x2 - x1)
slope = (y2 - y1) / (x2 - x1);

// Displaying the result


printf("The slope of the line passing through the points (%.2f, %.2f) and
(%.2f, %.2f) is %.2f.\n", x1, y1, x2, y2, slope);

return 0;
}

------------------------------------------------------------------------
Program-11:

Formula: 𝑆𝑛 = 𝑛/2(a+𝑙)
Calculate the Sum of an Arithmetic Series

FileName: Sum_AS.C

Code:
#include<stdio.h>
int main()
{
int n,a,l,Sn;

scanf("%d%d%d",&n,&a,&l);

Sn=n/2*(a+l);

printf("Sum of Arithmetic Series of first %d elements is %d",n,Sn);


return 0;
}

-----------------------------------------------------------------------
Program-12:
Find the nth Term of an Arithmetic Sequence
Formula: nth term = a+(n-1)*d
FileName: Nth_Term_AS.C

Code:
#include<stdio.h>
int main()
{
int n,a,d,Nth_term;

scanf("%d%d%d",&n,&a,&d);

Nth_term=a+(n-1)*d;

printf("%dth term of an Arithmetic Sequence is %d",n,Nth_term);


return 0;
}

-----------------------------------------------------------------------
Program-13:

Formula: Mean = ∑𝑥𝑖 / n


Compute the Mean of a List of 6 Numbers

FileName: Mean.C
Code:
#include<stdio.h>
int main()
{
//Declare the variables
int n1,n2,n3,n4,n5,n6,sum;
float mean;

printf("Enter any 6 integer numbers\n");


scanf("%d%d%d%d%d%d",&n1,&n2,&n3,&n4,&n5,&n6);

sum=n1+n2+n3+n4+n5+n6;

mean=(float)sum/n;

printf("Mean of the given 6 numbers is: %.2f\n",mean);

return 0;
}
----------------------------------------------------------------------
Program-14:
Calculate the Centroid of a Triangle
Formula: (x,y) = ((x1+x2+x3)/3, (y1+y2+y3)/3)
FileName: Centroid.C

Code:
#include<stdio.h>
int main()
{
int x1,x2,x3,y1,y2,y3;
float x,y;
printf("Enter the X and Y Coordinates of Point1 of a Triangle\n");
scanf("%d%d",&x1,&y1);
printf("Enter the X and Y Coordinates of Point2 of a Triangle\n");
scanf("%d%d",&x2,&y2);
printf("Enter the X and Y Coordinates of Point1 of a Triangle\n");
scanf("%d%d",&x3,&y3);

x=(x1+x2+x3)/3.0;
y=(y1+y2+y3)/3.0;

printf("Centroid of a Triangle (x,y) is: (%d,%d)",x,y);

return 0;
}

Output:
=======
Enter the X and Y Coordinates of Point1 of a Triangle
1 1
Enter the X and Y Coordinates of Point2 of a Triangle
2 2
Enter the X and Y Coordinates of Point1 of a Triangle
3 3
Centroid of a Triangle (x,y) is: (2.000000,2.000000)
-------------------------------------------------------------------------
Program-15:
Write a C program to enter marks of five subjects and calculate total,
average and percentage.
FileName: Percentage.C

Code:
#include<stdio.h>
int main()
{
float sub1,sub2,sub3,sub4,sub5,total,avg_marks,percentage;

printf("Enter Five Subject Marks\n");


scanf("%f%f%f%f%f",&sub1,&sub2,&sub3,&sub4,&sub5);

total=sub1+sub2+sub3+sub4+sub5;

avg_marks = total/5;
percentage=total/500*100;

printf("Sub1 Marks: %.2f\n",sub1);


printf("Sub2 Marks: %.2f\n",sub2);
printf("Sub3 Marks: %.2f\n",sub3);
printf("Sub4 Marks: %.2f\n",sub4);
printf("Sub5 Marks: %.2f\n",sub5);

printf("Average Marks = %.2f\n",avg_marks);


printf("Percentage is %.2f%\n",percentage);
return 0;
}

Output:
======
Enter Five Subject Marks
85 63 89 75 64
Sub1 Marks: 85.00
Sub2 Marks: 63.00
Sub3 Marks: 89.00
Sub4 Marks: 75.00
Sub5 Marks: 64.00
Average Marks = 75.20
Percentage is 75.20

-----------------------------------------------------------------------------------
---------
functions available in math.h header file:
==========================================
1) double sqrt(double x)
2) double cbrt(double x)
3) double floor(double x)
4) double ceil(double x)
5) double pow(double x,double y) => x^y
6) double log10(double x)
7) double round(double x)
8) double fabs(double x)

Example:
=======
#include<stdio.h>
#include<math.h>
int main()
{
int n;
scanf("%d",&n);

double res=sqrt(n);
printf("Square root of %d is %lf",n,res);

return 0;
}

================================================================================
Session-04
Date: 05-09-2024

Working with scanf and printf (\n -> newLine)


=============================
Variable Declaration Reading
Printing
-------------------- --------------------- ------------------------
------
1) int x; scanf("%d",&x);
printf("%d",x);
2) int x,y; scanf("%d%d",&x,&y); printf("%d
%d\n",x,y);
3) char ch; int x; scanf("%c%d",&ch,&x); printf("ch =
%c and x = %d\n",ch,x);
4) float p; double q; scanf("%f%lf",&p,&q); printf("Float p =
%.2f\nDouble q = %.2lf",p,q);

Operators:
==========
An operator is a symbol which is used to perform some operation.

int c = a+b;

here a,b and c are called operands.


+ and = are called operators.

Types of operators:
====================
1) Arithmetic Operators [+, -, *, /, %]
Ex:
int x=20,y=5;

Operator Expresssion Output


-------- ----------- --------
1) + x+y 25

2) - x-y 15

3) * x*y 100

4) / x/y 4 [Integers
division gives always an integer]
20/3 6
20/3.0 6.6666...

5) %[remainder] x%y 0
20%3 2

2) Relational Operators or Comparitive Operators [>, >=, <, <=, ==, !=]
#include<stdio.h>
int main()
{
int x,y;
scanf("%d%d",&x,&y);

printf("%d == %d => %d\n",x,y,x==y);


printf("x > y => %d\n",x>y);
printf("x >= y => %d\n",x>=y);
printf("x < y => %d\n",x<y);
printf("x <= y => %d\n",x<=y);
printf("x != y => %d\n",x!=y);

return 0;
}
3) Logical Operators [&&(and), ||(or), !(not)]
Logical operators are used to connect two or more expressions into one single
complex expression.

int a=20,b=10,c=15;

a>b && a>c => a is bigger

a>b || a>c => a is bigger than any one of the other numbers

4) Assignment Operators [=, +=, -=, *=, /=, %=,...]

5) Bitwise Operators [&, |, ~, >>, <<, >>>]

6) Conditional Operator [?:]

Conditions based basic programs:


================================
Control Statements:
The statements which are used to control the flow of execution of a program are
called control statements.
Control Statements are classified into 2 types
1) Conditional Statements
i) simple if
ii) if else
iii)if else if
iv) nested if
v) switch

2) Looping Statements
i) for
ii)while
iii)do while

Conditional Statements:
=======================
1) simple if:
if the condition is true then only the block of code associated with that
condition will be executed.
Syntax:
if(condition)
{
//block of code. // it executed only when the condition is true
}

2) if else:
if the condition is true then the true block will execute other wise false block
will execute.

Syntax:
if(condition)
{

//true block
}
else
{
//false block
}
Practice:
#include<stdio.h>
int main()
{
int a=6,b=15;
if(a>b)
{
printf("a is bigger than b");
}
else
{
printf("b is bigger than a");
}
printf("Task completed");
return 0;
}

1) Write a program to find the given number is even or odd. [Solve]


Program-016:
FileName: EvenorOdd.C

Code:
#include<stdio.h>
int main()
{
int n;
printf("Enter any number\n");
scanf("%d",&n);
if(n%2==0)
{
printf("%d is a Even Number\n",n);
}
else
{
printf("%d is a Odd Number\n",n);
}
return 0;
}

----------------------------------------------------------------------------
2) Write a program to find the given number is positive or not.
Program-017:
FileName: PositiveOrNot.c

#include<stdio.h>
int main()
{
int n;

scanf("%d",&n);

if(n>0){
printf("%d is a positive number",n);
}
else{
printf("%d is a negative number",n);
}
}

----------------------------------------------------------------------------
3) Write a program that checks if a person is eligible to vote based on their age
(must
be 18 or older). [Solve]
Input:
25
Output:
You are Eligible for Voting.

Program-018
FileName: VotingEligibility.C

#include<stdio.h>
int main()
{
int age;

printf("Enter your Age:\n");


scanf("%d",&age);

if(age>=18)
{
printf("Hi! You are eligible for Voting\n");
printf("Thank you for using my applicaiton\n");
}
else
{
printf("Sorry! You are not eligible for Voting\n");
printf("You need to wait %d more years to get the vote\n",18-age);
}

return 0;
}

----------------------------------------------------------------------------
4) Write a program that checks whether a triangle is valid or not based on the
angles provided (sum of angles should be 180 degrees).
Input:
45 45 90
Output:
Valid Triangle

Program-019
FileName: ValidTriangle1.C

#include<stdio.h>
int main()
{
float a,b,c,sum;

printf("Enter angles of the Triangle\n");


scanf("%f%f%f",&a,&b,&c);
sum=a+b+c;
if(sum==180)
{
printf("It is a Valid Triangle");
}
else
{
printf("It's not a Valid Triangle");
}
return 0;
}

-----------------------------------------------------------------------------
5) Write a C program to list the speeds of all the qualified racers in a race.
Take 3 racers speed as an input and find the racer is qualified or not.
Note: If a racer is said to be qualified the speed of racer is greater than the
average speed of the race. [Solve]
Explanation:
============
150 250 200

avg=150+250+200/3 => 200

Output:
250

Program-020
FileName: QualifiedRacers.C
#include<stdio.h>
int main()
{
int r1,r2,r3;
float avg;

scanf("%d%d%d",&r1,&r2,&r3);

avg=(r1+r2+r3)/3;
printf("Average speed is: %.2f\n",avg);
printf("Qualified Racers Speeds are:\n");

if(r1>avg)
{
printf("%d\n",r1);
}
if(r2>avg)
{
printf("%d\n",r2);
}
if(r3>avg)
{
printf("%d\n",r3);
}
return 0;
}
Output:
248
247
292
Average speed is: 262.00
Qualified Racers Speeds are:
292

------------------------------------------------------------------------------
6) Write a program to check if a given number falls within a specified range (e.g.,

between 10 and 50). [Solve]


Program-019
FileName: Range.C

--------------------------------------------------------------------------------
7) Write a program that checks if a number is divisible by both 5 and 11 or not.
Program-020
FileName: Divisibleby5and11.C

#include<stdio.h>
int main()
{
int n;

scanf("%d",&n);

if(n%5==0 && n%11==0)


{
printf("%d is divisible by both 5 and 11",n);
}
else
{
printf("%d is not divisible by both 5 and 11",n);
}
}

--------------------------------------------------------------------------------
8) Create a program that takes a character as input and checks whether it is
uppercase
or lowercase. [Solve]
Input:
a
Output:
Lowercase
Explanation:
Input:
'U' => UpperCase
'i' => Lowercase
'A' => UpperCase
UpperCase Characters:
'A' - 65
'B' - 66
'C' - 67
......
'Y' - 89
'Z' - 90
Lowercase Characters:
'a' - 97
'b' - 98
....
'z' - 122
Digits:
'0' - 48
'1' - 49
...
'9' - 57

Program-021
FileName: UpperorLowerCase.C
#include<stdio.h>
int main()
{
char ch;
scanf("%c",&ch);
//Assume the input contains only Alphabets
if(ch>='A' && ch<='Z')
{
printf("%c is a Uppercase Character\n",ch);
}
else
{
printf("%c is a Lowercase Character\n",ch);
}
return 0;
}
Output:
U
U is a Uppercase Character

----------------------------------------------------------------------------------
9) Program to input sides of a triangle and check whether triangle is valid or not.
Input:
2
3
4
Output:
Valid
Hint:
A triangle is valid if sum of its two sides is greater than the third side.
If three sides are a, b and c, then three conditions should be met.
1. a + b > c
2. a + c > b
3. b + c > a

Program-022
FileName: ValidTriangle2.C

#include<stdio.h>
int main()
{
int a,b,c;
scanf("%d%d%d",&a,&b,&c);

if(a+b>c && a+c>b && b+c>a)


{
printf("Valid Triangle");
}
else
{
printf("Invalid Triangle");
}
}

-------------------------------------------------------------------------------
Working with if else if:
------------------------
If we want to check for multiple conditions on a single variable then we have to go
for if else if statement.
Syntax:
======
if(condition1)
{
//block of Code
}
else if(condition2)
{
//block of code
}
else if(condition3)
{
//block of code
}
.........
else if(condition-n)
{
//block of code
}
else
{
//default case
}

10)Write a program to display the given digit(0 to 9) in words as follows [Solve]


Input: 9
Output: Nine
Program-023
FileName: DigitInWords.C

#include<stdio.h>
int main()
{
int n;
printf("Enter a digit\n");
scanf("%d",&n);

if(n==0)
{
printf("ZERO\n");
}
else if(n==1)
{
printf("ONE\n");
}
else if(n==2)
{
printf("TWO\n");
}
else if(n==3)
{
printf("THREE\n");
}
else if(n==4)
{
printf("FOUR\n");
}
else if(n==5)
{
printf("FIVE\n");
}
else if(n==6)
{
printf("SIX\n");
}
else if(n==7)
{
printf("SEVEN\n");
}
else if(n==8)
{
printf("EIGHT\n");
}
else if(n==9)
{
printf("NINE\n");
}
else
{
printf("Enter a Valid Digit(0 - 9 Only)\n");
}
printf("Task Completed");
return 0;
}
Output:
Case=1:
Enter a digit
5
FIVE
Task Completed

Case-2:
Enter a digit
10
Enter a Valid Digit(0 - 9 Only)
Task Completed

-------------------------------------------------------------------------------
11)Program to check whether a triangle is equilatoral, Isosceles or Scalence.
Input:
2
3
4
Output:
Scalence

Hint:
Equilatoral -> All the sides of the Triangle are equal
Isosceles -> Any two sides of the Triangle are equal
Scalence -> All the sides of the Triangle are different

Program-024
FileName: TriangleType.C

------------------------------------------------------------------------------
12)Write a Program to print the color name by taking the Color code as input.
V -> Violet
I -> Indigo
B -> Blue
G -> Green
Y -> Yellow
O -> Orange
R -> Red
Input:
G
Output:
Green
Note: Implement by using both if else if and switch case.
Program-025
FileName: FindColor.C

-------------------------------------------------------------------------
13)Write a program to read temperature in centigrade and display a suitable message
according to temperature state below: [Solve]
Temp < 0 then Freezing weather
Temp 0-10 then Very Cold weather
Temp 10-20 then Cold weather
Temp 20-30 then Normal in Temp
Temp 30-40 then Its Hot
Temp >=40 then Its Very Hot

Explanation:
Assume the temp=35; => Its Hot

if(temp < 0)
printf("Freezing Weather");
else if(temp>=0 && temp<=10)
printf("Very Cold Weather");
else if(temp>10 && temp<=20)
printf("Cold Weather");
else if(temp>20 && temp<=30)
printf("Normal temp");
else if(temp>30 && temp<=40)
printf("Its Hot");
else
printf("Tis very Hot");

Program-026
FileName: DisplayTemprature.C

-------------------------------------------------------------------------
14)Write a program to display season by taking the input as month.
Assume:
3, 4, 5 – Summer
6, 7, 8, 9 – Rainy
10, 11, 12, 1, 2 - Winter

Input: 9
Output: Rainy

---------------------------------------------------------------------------
15)Program to input basic salary of an employee and calculate its gross salary
according to following.
Basic Salary <=10000 ==> HRA=20%, DA=80%
Basic Salary <=20000 ==> HRA=25%, DA=90%
Basic Salary >20000 ==> HRA=30%, DA=95%

Program-028
FileName: FindGrossSalary.C
#include<stdio.h>
int main()
{
int salary;
double hra,da,gs;
scanf("%d",&salary);
if(salary<=10000)
{
hra=0.2*salary;
da=0.80*salary;
}
else if(salary>10000 && salary<=20000)
{
hra=0.25*salary;
da=0.9*salary;
}
else
{
hra=0.3*salary;
da=0.95*salary;
}
gs=salary+hra+da;
printf("Basic Salary = %d\n",salary);
printf("HRA = %.2lf\n",hra);
printf("DA = %.2lf\n",da);
printf("Gross Salary = %.2lf",gs);
return 0;

-----------------------------------------------------------------------------
16)Program to input electricity unit charges and calculate total electricity bill
according to the given condition: [Solve]
for first 50 units Rs - 0.50/unit
for next 100 units Rs - 0.75/unit
for next 100 units Rs - 1.20/unit
for units above 250 Rs - 1.50/unit
An additional surcharge of 20% is added to the bill.

Input:
150
Output:
120

150 Units => 50 X 0.50 + 100 x 0. 75 => 25 + 75 => 100

175 Units => 50 X 0.50 + 100 X 0.75 + 25 X 1.20 => 25 + 75 + 30 => 130

270 Units => 50 X 0.50 + 100 X 0.75 + 100 X 1.20 + 20 X 1.50 => ....

Program-029
FileName: FindElectricityBill.C
#include<stdio.h>
int main()
{
int units;
double bill,surcharge,tot_bill;

scanf("%d",&units);

if(units<=50)
{
bill=units*0.50;
}
else if(units>50 && units<=150)
{
bill = 50 * 0.50 + (units-50) * 0.75;
}
else if(units>150 && units<=250)
{
bill=50*0.50 + 100 * 0.75 + (units-150) * 1.20;
}
else
{
bill=50*0.50 + 100 * 0.75 + 100*1.20 + (units-250)*1.50;
}

tot_bill = bill + 0.2*bill;


printf("No of Units = %d\n",units);
printf("Bill = %.2lf\n",bill);
printf("Net Bill = %.2lf\n",tot_bill);

return 0;
}

----------------------------------------------------------------------------------
17)Program to implement simple calculator by using switch case.
Input:
Enter any two Numbers
20 10
1) + - Addition
2) - - Subtraction
3) * - Multiplication
4) / - Division
5) % - Modulous
Enter your Choice
+

Sum of 20 and 10 is: 30

Program-030
FileName: SimpleCalculator.C

----------------------------------------------------------------------------------
18)Write a program to find the roots of a Quadratic Equations. [Solve]
Note:
Assume the equation is ax^2 + bx + c=0 then find the (descriminent)d =(b*b -
4*a*c)
if d = 0 => Roots are equal and print the roots.
d >0 => Roots are Real Values.
d < 0 => Roots are Imaginary.
Equation: ax^2 + bx +c = 0

roots = -b +- sqrt(b^2 - 4ac)


---------------------
2a

Program-031
FileName: RootsofQuadraticEquation.C
#include<stdio.h>
#include<math.h>
int main()
{
double a,b,c;
double d,r1,r2;
scanf("%lf%lf%lf",&a,&b,&c); //Reading of input
d=b*b-4*a*c; //decriminent value
if(d==0)
{
printf("Roots are Equal\n");
r1=-b/(2*a);
r2=-b/(2*a);
}
else if(d>0)
{
printf("Roots are Real Numbers\n");
r1=(-b+sqrt(d))/(2*a);
r2=(-b-sqrt(d))/(2*a);
}
else
{
printf("Roots are imaginary\n");
}

printf("Root1 = %.2lf\n",r1);
printf("Root2 = %.2lf\n",r2);

return 0;
}

---------------------------------------------------------------------------------
Grading System:
Write a program to accept a student's marks and determine the grade using if-else
if.
The grading criteria are:
Marks >= 90:
Grade A
Marks >= 80:
Grade B
Marks >= 70:
Grade C
Marks >= 60:
Grade D
Marks < 60:
Grade F

Program-032:
FileName: FindGrade.C

-----------------------------------------------------------------------------------
----------
Body Mass Index (BMI) Calculator:
Write a program to calculate the BMI of a person and display their weight category
using if-else if. The categories are:
BMI < 18.5: Underweight
18.5 <= BMI < 24.9: Normal weight
25 <= BMI < 29.9: Overweight
BMI >= 30: Obesity
Note:
Formula: BMI = Weight * Height;

Program-033:
FileName: FindBMI.C
-----------------------------------------------------------------------------------
-----
Discount Calculation:
Write a program that calculates the discount based on the purchase amount:
If the purchase amount is greater than $500, apply a 20% discount.
If the purchase amount is between $300 and $500, apply a 10% discount.
If the purchase amount is less than $300, no discount is applied.

Program-034:
FileName: FindDiscount.C

-----------------------------------------------------------------------------------
--------
Traffic Light System:
Write a program to simulate a traffic light system using if-else if. Depending on
the light color input (Red, Yellow, Green), display the action for the driver
(Stop, Slow down, Go).

Program-035:
FileName: TrafficLight.C

-----------------------------------------------------------------------------------
--------
Day of the Week:
Write a program that accepts a number (1-7) from the user and prints the
corresponding day of the week using switch case. For example, 1 for Sunday, 2 for
Monday, etc.

Program-036:
FileName: DayOftheWeek.C

-----------------------------------------------------------------------------------
-----------
Menu-Driven Program for Temperature Conversion:
Write a program that provides a menu to convert temperature between Celsius,
Fahrenheit, and Kelvin. The user should choose from a menu (1 for Celsius to
Fahrenheit, 2 for Fahrenheit to Celsius, 3 for Celsius to Kelvin, etc.), and the
program should perform the appropriate conversion using switch case.
Input:
1. Celsius to Fahrenheit
2. Fahrenheit to Celsius
3. Celsius to Kelvin
Enter you Choice:
2
Enter the Fahrenheit Value
34

Output:
Print Celsius converted Value.

Program-037
FileName: TemperatureConversion.C
-----------------------------------------------------------------------------------
-------------
Working with Nested If:
Check Eligibility for Voting and Senior Citizen Benefits
This example checks if a person is eligible to vote and if they are also a senior
citizen using nested if.

Program-038:
FileName: CheckforVoterEligibility.C

-----------------------------------------------------------------------------------
----
Triangle Type Based on Side Lengths
This example checks if the three sides form a valid triangle, and if they do, it
further checks if the triangle is equilateral, isosceles, or scalene using nested
if.

Program-039:
FileName: TypeofTriangle.C

-----------------------------------------------------------------------------------
-
Check for Leap Year
Program to check the given year is leap year or not.

Program-040:
FileName: LeapYearorNot.C

--------------------------------------------------------------------------------
Date: 12-09-2024
=================
1) Simple if
if(condition)
{
//block of code to be execute if the condition is true.
}
2) if else
if(condition)
{
//block of code will execute if the condition is true.
}
else
{
//block of code will execute if the condition is false
}

3) if else if:
if(condition1)
{
//block of code will execute if the condition1 is true
}
else if(condition2)
{
//block of code will execute if the condition2 is true.
}
else if(condition3)
{

}
........
else if(condition-n)
{

}
else
{
//block of code will execute if any of the condition not met.
}

4) nested if:
if you write an if statement in another if statements such type of statements
are called nested if.
Syntax:
-------
if(condition1) //Outer If
{
if(condition2) //Inner If
{
if(condition3) // Inner If
{
.....
}
}
}
else
{
if(condition4)
{
}
else
{
}
}

---------------------------------------------
Practice Prog:
Program to find the biggest of three numbers.

Program-041:
FileName: BiggestofThreeNums.C

#include<stdio.h>
int main()
{
int a,b,c;

scanf("%d%d%d",&a,&b,&c);
if(a>b)
{
if(a>c)
{
printf("%d is bigger",a);
}
else
{
printf("%d is bigger",c);
}
}
else
{
if(b>c)
{
printf("%d is bigger",b);
}
else
{
printf("%d is bigger",c);
}
}

return 0;
}

-----------------------------------------------------------------------------------
----------

Date: 13-09-2024
=================
Switch:
=======
The switch statement in C is used to perform different actions based on different
conditions.

It's an alternative to using multiple if-else statements when you have many
conditions based on the value of a single variable.

The switch evaluates the variable and executes the corresponding block of code that
matches the value.

Syntax:
=======
switch(expression/variable)
{
case label1:
statements;
break;
case label2:
statements;
break;
case label3:
statements;
break;
........

case labeln:
statements;
break;
default:
statements;
break;
}

Example:
=========
Program to print the week day name based on the day number.
Assumption: 1 - sunday , 2 - Monday, .....,7- Saturday

Input:
2
Output:
Monday

Program-042:
FileName: WeekDayName.C

#include<stdio.h>
int main()
{
int day_num;
scanf("%d",&day_num);

switch(day_num)
{
case 1:
printf("Sunday");
break;
case 2:
printf("Monday");
break;
case 3:
printf("Tuesday");
break;
case 4:
printf("Wednsday");
break;
case 5:
printf("Thursday");
break;
case 6:
printf("Friday");
break;
case 7:
printf("Saturday");
break;
default:
printf("Enter a valid week day number(1-7)");
break;
}
printf("Task Completed");
return 0;
}

How It Works:
=============
1) The expression inside the switch is evaluated.
2) The value of the expression is compared with the constants provided in each
case.
3) If a match is found, the code block associated with that case is executed.
4) The break statement ends the switch statement. If break is not used, the
execution will continue to the next case (known as fall-through behavior).
5) If no matching case is found, the default block (if present) is executed.

Rules Followed in C Switch Case:


================================
1) Only Integer and Character Values Allowed:

2) The expression in a switch must evaluate to an integer or character value.


Floating-point and strings are not allowed.

3) Case Labels Must Be Constant and Unique:

4) Variables are not allowed in case labels.

5) Break Statement: The break statement is used to exit the switch once a matching
case is
executed. Without break, the code will continue executing the next case even if
the value does not match (fall-through).

6) Default Case: The default case is optional and is executed when none of the
other case values
match. It acts like a catch-all for unhandled values.

7) Fall-Through Behavior:
In C, if there is no break after a case, the program continues executing the
next case. This is known as fall-through behavior and can be used intentionally if
multiple cases share the same code block.

-----------------------------------------------------------------------------------
-
Programs on Switch Case:

Traffic Light System:


Write a program to simulate a traffic light system using if-else if. Depending on
the light color input (Red, Yellow, Green), display the action for the driver
(Stop, Slow down, Go).

Program-043:
FileName: TrafficLight.C

#include<stdio.h>
int main()
{
char color_Code;

scanf("%c",&color_Code);
switch(color_Code)
{
case 'R':
case 'r':
printf("STOP......");
break;
case 'Y':
case 'y':
printf("SLOW DOWN.....");
break;
case 'G':
case 'g':
printf("GO......");
break;
default:
printf("Enter Valid Color Code");
break;
}
return 0;
}

----------------------------------------------------------

Write a program to display season by taking the input as month.


Assume:
3, 4, 5 – Summer
6, 7, 8, 9 – Rainy
10, 11, 12, 1, 2 - Winter

Input: 9
Output: Rainy

Program-043
FileName: PrintSeasons.C
#include<stdio.h>
int main(){
int season;
printf("give a no");
scanf("%d",&season);
switch(season){
case 3:
case 4:
case 5:
printf("summer");
break;
case 6:
case 7:
case 8:
case 9:
printf("rainy");
break;
case 10:
case 11:
case 12:
case 1:
case 2:
printf("winter");
break;
default :
printf("give a valid number");
}
printf("task completed");
return 0;
}

--------------------------------------------------------------------
Write a Program to print the color name by taking the Color code as input.
V -> Violet
I -> Indigo
B -> Blue
G -> Green
Y -> Yellow
O -> Orange
R -> Red
Input:
G
Output:
Green
Note: Implement by using both if else if and switch case.

Program-044
FileName: FindColor.C

By using Switch Case:


=====================
#include<stdio.h>
int main()
{
char code;
scanf("%c",&code);
switch(code)
{
case 'V':
case 'v':
printf("Violet");
break;

case 'I':
case 'i':
printf("Indigo");
break;
case 'B':
case 'b':
printf("Blue");
break;
case 'G':
case 'g':
printf("Green");
break;
case 'Y':
case 'y':
printf("Yellow");
break;
case 'O':
printf("Orange");
break;
case 'R':
case 'r':
printf("Red");
break;
default:
printf("Enter a valid Color Code");
break;
}
return 0;
}

-----------------------------------------------------------------------

You might also like