The document contains summaries of several C programming examples:
1. Programs to calculate the area and circumference of a circle, find simple interest, convert temperatures between Celsius and Fahrenheit, calculate subject marks and percentages, and calculate gross salary.
2. Additional programs demonstrate swapping values with and without a third variable, finding the greatest of three numbers, determining if a year is a leap year, and identifying integers as odd or even, positive or negative.
3. Further programs check if an integer is divisible by 5 and 11, compare two integers for equality, use a switch statement to print days of the week, and perform arithmetic operations using a switch case.
Introduction to Casting Processes in Manufacturing
Cs291 assignment solution
1. Page 1 of 20
Assignment – 1
Fundamental C Programming
1. Program to find area and circumference ofcircle.
#include<stdio.h>
int main(){
int rad;
float PI = 3.14, area, ci;
printf("nEnter radiusof circle:");
scanf("%d",&rad);
area= PI * rad* rad;
printf("nArea of circle:%f ", area);
ci= 2 * PI * rad;
printf("nCircumference:%f ", ci);
return (0);
}
Output:
Enter radiusof a circle:1
Area of circle:3.14
Circumference : 6.28
Explanationof Program :
In this program wehave to calculatetheareaandcircumferenceofthecircle.Wehave following2formulasfor
findingcircumferenceandareaofcircle.
Area of Circle= PI * R * R
andCircumferenceofCircle=2 * PI * R
In the above program wehave declaredthefloatingpointvariable PI whosevalue is defaultedto 3.14. We are
acceptingtheradiusfrom user.
printf("nEnter radiusof circle:");
scanf("%d",&rad);
2. Program to find the simple interest.
#include<stdio.h>
int main(){
int amount,rate, time, si;
2. Page 2 of 20
printf("nEnter PrincipalAmount: ");
scanf("%d",&amount);
printf("nEnter Rate of Interest : ");
scanf("%d",&rate);
printf("nEnter Periodof Time : ");
scanf("%d",&time);
si = (amount* rate * time)/ 100;
printf("nSimpleInterest : %d", si);
return(0);
}
Output:
Enter PrincipalAmount: 500
Enter Rate of interest : 5
Enter Periodof Time : 2
SimpleInterest : 50
Explanation ofProgram:
In this program weare calculatingthesimpleinterestbytaking the Principalamount,rateof Interest and Periodof
timeas user input. After taking the user inputswe are calculatingthesimpleinterestandstoringit in si variableby
si = (amount* rate * time)/ 100;
Program to converttemperature from degree centigrade to Fahrenheit.
#include<stdio.h>
int main(){
float celsius,fahrenheit;
printf("nEnter tempinCelsius: ");
scanf("%f", &celsius);
fahrenheit= (1.8 * celsius)+32;
printf("nTemperatureinFahrenheit:%f ", fahrenheit);
return (0);
}
Output:
Enter tempin Celsius: 32
TemperatureinFahrenheit: 89.59998
Explanation ofProgram:
3. Page 3 of 20
In this program weare calculatingtheuserenteredCelsiustemperatureto Fahrenheit.Temperatureconversion
formulafrom degreeCelsiusto Fahrenheitisgiven by -
Apply formulato convert the temperatureto Fahrenheit
Program to calculate sum of 5 subjects and find percentage
#include<stdio.h>
int main(){
int s1, s2, s3, s4, s5, sum, total = 500;
float per;
printf("nEnter marksof 5 subjects: ");
scanf("%d%d %d%d %d", &s1, &s2, &s3, &s4, &s5);
sum = s1 + s2 + s3 + s4 + s5;
printf("nSum : %d", sum);
per = (sum * 100) / total;
printf("nPercentage: %f", per);
return (0);
}
Output:
Enter marks of 5 subjects : 80 70 90 80 80
Sum : 400
Percentage : 80.00
Explanation ofProgram:
In this program weare calculatingthe sum andpercentageofuser entered marksin 5 subjects.Very simple
program.The scanf("%d%d%d %d %d", &s1, &s2, &s3, &s4, &s5); statementtaking the user inputof 5
subjects.Thestatementsum = s1 + s2 + s3 + s4 + s5; calculatingthesum of5 subjects.
per = (sum * 100) / total; this C statementis findingthe percentage.
Program to find gross salary.
#include<stdio.h>
int main() {
int gross_salary,basic, da, ta;
4. Page 4 of 20
printf("Enter basic salary : ");
scanf("%d",&basic);
da = (10 * basic) / 100;
ta = (12 * basic) / 100;
gross_salary = basic + da + ta;
printf("nGross salary : %d",gross_salary);
return (0);
}
Output:
Enter basic Salary : 1000
Gross Salart : 1220
Program to show swap of two numbers by using third variable.
#include <stdio.h>
intmain()
{
intx, y,temp;
printf("Enterthe value of x andyn");
scanf("%d%d",&x,&y);
printf("Before Swappingnx =%dny= %dn",x,y);
temp= x;
x = y;
y = temp;
printf("AfterSwappingnx =%dny= %dn",x,y);
return0;
}
Output:
5. Page 5 of 20
Program to show swap of two numbers without using third variable
#include<stdio.h>
int main()
{
int a, b;
printf("Input two integers(a & b) to swapn");
scanf("%d%d",&a, &b);
a = a + b;
b = a - b;
a = a - b;
printf("a = %dnb = %dn",a,b);
return 0;
}
You can also swap two numbers without using temp or temporary or third variable.
To understand the logic choose the variables 'a' and 'b' as '7' and '9' respectively and then do
what is being done by the program. You can choose any other combinationof numbers as
well. Sometimes it's an excellent way to understand a program.
Program to find greatestin 3 numbers.
#include<stdio.h>
int main(){
int a, b, c;
printf("nEnter value of a, b & c : ");
scanf("%d%d %d", &a, &b, &c);
if ((a > b) && (a > c))
printf("na is greatest");
6. Page 6 of 20
if ((b > c)&& (b > a))
printf("nb is greatest");
if ((c > a) && (c > b))
printf("nc is greatest");
return(0);
}
Output:
Enter value for a,b & c : 15 17 21
c is greatest
Program to find that entered year is leap year or not.
#include <stdio.h>
intmain()
{
int year;
printf("Enterayear:");
scanf("%d",&year);
if(year%4== 0)
{
if( year%100== 0)
{
//year isdivisibleby400, hence the yearis a leapyear
if ( year%400 == 0)
printf("%disaleapyear.",year);
else
printf("%disnota leap year.",year);
}
else
printf("%disaleapyear.",year);
}
else
printf("%disnotaleapyear.",year);
return0;
}
Output:
Enter a year:1900
7. Page 7 of 20
1900 isnot a leapyear.
Enter a year:2012
2012 isa leapyear.
Explanation ofProgram:
A leapyear is exactlydivisibleby 4 exceptfor centuryyears (years endingwith00). Thecenturyyear is a leap
year onlyif it is perfectlydivisibleby 400.
Program to check ifa given Integer is odd or even.
#include<stdio.h>
int main()
{
int number;
printf("Enter aninteger: ");
scanf("%d", &number);
// Trueif the numberisperfectlydivisibleby 2
if(number% 2 == 0)
printf("%d is even.", number);
else
printf("%d is odd.", number);
return 0;
}
Output:
Enter an integer:-7
-7 is odd.
Enter an integer:10
10 is odd.
Explanation ofProgram:
An even numberisaninteger that is exactlydivisibleby 2. Example:0, 8, -24
An oddnumberis aninteger that is not exactlydivisibleby 2. Example:1, 7, -11, 15
In the program,integerenteredby the user is stored in variablenumber.
Then,whetherthenumberis perfectlydivisible by 2 or not is checkedusingmodulusoperator.
If the numberisperfectlydivisibleby 2, test expressionnumber%2==0 evaluates to 1 (true) and the numberis
even.
However, if the test expressionevaluates to 0 (false), the numberis odd.
8. Page 8 of 20
Program to check ifa given Integer is Positive or Negative
#include <stdio.h>
intmain()
{
double number;
printf("Enteranumber:");
scanf("%lf",&number);
if (number<= 0.0)
{
if (number== 0.0)
printf("Youentered0.");
else
printf("Youenteredanegative number.");
}
else
printf("Youenteredapositivenumber.");
return0;
}
Output :
Enter a number:12.3
You enteredapositive number.
Enter a number:0
You entered0.
Enter a number:-2.3
You enteredanegative number.
Explanation ofProgram:
This program takes a number from the user and checks whether that number is either positive
or negative or zero.
Program to find a user entered Integer Divisible by 5 and 11 or not.
#include<stdio.h>
int main()
{
int num;
printf("Enter anynumber:");
scanf("%d", &num);
9. Page 9 of 20
/*If num modulodivision5is 0 andnum modulodivision11is 0 then the numberisdivisibleby 5 and 11both*/
if((num % 5 == 0) && (num % 11 == 0))
{
printf("Numberisdivisibleby 5 and 11");
}
else
{
printf("Numberisnot divisibleby 5 and 11");
}
return 0;
}
Output:
Enter anynumber:55
Numberisdivisible by5and 11
Explanation ofProgram:
Logic tocheckdivisibilityof a number
A numberis exactlydivisible by some othernumberif it gives 0 as remainder.Tocheckifa numberisexactly
divisibleby somenumberweneedto test if it leaves 0 as remainderornot.
C supports a modulooperator%,that evaluates remainderondivisionof two operands.You canuse this to check
if a numberis exactlydivisible by somenumberornot. Forexample - if(8 % 2), if the given expressionevaluates
0, then 8 is exactlydivisibleby 2.
Step by step descriptivelogic to checkwhetheranumberisdivisibleby 5 and11 or not.
Input a numberfrom user. Store it in somevariablesay num.
Tocheckdivisibilitywith5, checkif(num %5 == 0) thennum is divisibleby 5.
Tocheckdivisibilitywith11, checkif(num %11== 0) then num is divisibleby 11.
Nowcombinetheabovetwo conditionsusinglogical ANDoperator&&. Tocheckdivisibilitywith5 and 11 both,
checkif((num %5 == 0) && (num % 11 == 0)), then numberisdivisibleby both 5 and11.
Program to accepttwo Integers and Check if they are Equal
#include<stdio.h>
void main()
{
int m, n;
printf("Enter the values for M and Nn");
scanf("%d%d", &m,&n);
10. Page 10 of 20
if (m == n)
printf("M and N areequaln");
else
printf("M and N arenot equaln");
}
Output:
Case:1
Enter the valuesforMand N
3 3
M and N are equal
Case:2
Enter the valuesforMand N
5 8
M and N are not equal
Explanation ofProgram:
1. Takethe two integersas inputand store it in the variablesm andn respectively.
2. Usingif,else statementscheckif m is equalto n.
3. If they areequal,then print the output as “M and N areequal”.
4. Otherwiseprint it as “M and N are not equal”.
Program to use switch statement display Monday to Sunday
#include<stdio.h>
int main()
{
int week;
/* Input weeknumberfrom user */
printf("Enter weeknumber(1-7):");
scanf("%d", &week);
switch(week)
{
case1:
printf("Monday");
break;
case2:
printf("Tuesday");
break;
case3:
printf("Wednesday");
break;
case4:
printf("Thursday");
break;
case5:
printf("Friday");
11. Page 11 of 20
break;
case6:
printf("Saturday");
break;
case7:
printf("Sunday");
break;
default:
printf("Invalid input! Pleaseenter weeknumberbetween1-7.");
}
return 0;
}
Output:
Enter weeknumber(1-7):1
Monday
Explanation ofProgram:
Step by step descriptivelogic to printday nameof week.
Input day numberfrom user. Store it in somevariablesay week.
Switchthe value of week i.e. use switch(week)andmatchwithcases.
Therecanbe7possiblevalues(choices)ofweek i.e. 1 to 7. Thereforewrite7caseinsideswitch.In addition,add
defaultcaseas an elseblock.
Forcase1: print"MONDAY", for case2: print "TUESDAY" and so on. Print "SUNDAY" for case7:.
If any casedoesnot matchesthen,for default: caseprint "Invalid week number".
You canalsoprint dayof weeknameusingif...else statement.
Program to display arithmetic operator using switch case
#include <stdio.h>
intmain()
{
char op;
floatnum1, num2,result=0.0f;
/* Printwelcome message */
printf("WELCOMETO SIMPLE CALCULATORn");
printf("----------------------------n");
printf("Enter[number1] [+ - * /] [number2]n");
/* Inputtwonumberandoperatorfrom user*/
scanf("%f %c%f",&num1,&op, &num2);
12. Page 12 of 20
/* Switchthe value andperformactionbasedonoperator*/
switch(op)
{
case '+':
result= num1 + num2;
break;
case '-':
result= num1 - num2;
break;
case '*':
result= num1 * num2;
break;
case '/':
result= num1 / num2;
break;
default:
printf("Invalidoperator");
}
/* Printsthe result*/
printf("%.2f %c%.2f = %.2f",num1, op,num2, result);
return0;
}
Output:
WELCOME TO SIMPLE CALCULATOR
------------------------------------------------
Enter [number1] [+ - * /] [number2]
22 * 6
22.00 * 6.00 = 132.00
Explanation ofProgram:
Step by step descriptivelogic to createmenudrivencalculatorthatperformsallbasic arithmetic operations.
Input two numbersanda characterfrom userinthe given format. Store them in somevariablesay num1,op and
num2.
Switchthe value of op i.e. switch(op).
Therearefour possiblevaluesof opi.e. '+', '-', '*' and'/'.
Forcase'+' perform additionandstore result insomevariable i.e. result = num1+ num2.
Similarlyfor case'-' perform subtractionandstoreresult in somevariablei.e. result= num1 - num2.
Repeatthe processfor multiplicationanddivision.
Finallyprint the value of result.
13. Page 13 of 20
Program to show the use ofconditional operator (ternary operator or short hand if-else operator).
#include<stdio.h>
int main()
{
int num;
printf("Enter the Number: ");
scanf("%d",&num);
(num%2==0)?printf("Even"):printf("Odd");
}
Output:
Enter the Number:4
Even
Explanation ofProgram:
expression1 ? expression2: expression3
where
expression1isCondition
expression2isStatementFollowedifConditionis True
expression2isStatementFollowedifConditionis False
Expression1is nothingbut BooleanConditioni.eit resultsinto either TRUEorFALSE
If result of expression1isTRUEthenexpression2is Executed
Expression1is saidto be TRUEif its result is NON-ZERO
If result of expression1isFALSE then expression3isExecuted
Expression1is saidto be FALSE if its result is ZERO.
Operatorthat works on 3 operandsiscalledastertiary operator. T ernaryoperator
Program to reverse a given number
#include<stdio.h>
int main(){
int num,rem, rev = 0;
printf("nEnter any no to be reversed : ");
scanf("%d",&num);
while(num >= 1) {
rem = num %10;
14. Page 14 of 20
rev = rev * 10+ rem;
num = num / 10;
}
printf("nReversed Number: %d", rev);
return (0);
}
Output:
Enter anyno to be reversed:123
ReversedNumber:321
Explanation ofProgram:
Program to display first10 natural no. & their sum.
#include<stdio.h>
intmain() {
inti = 1,sum=0;
for (i = 1; i <= 10; i++) {
printf("%d",i);
sum=sum+i;
}
printf("nSumof first10 natural numbers:%d", sum);
return(0);
}
Output:
1 2 3 4 5 6 7 8 9 10
Sumof first10 natural numbers:55
Explanation ofProgram:
Output:
Explanation ofProgram: