C Programs
List Of All C Problems
Problem#1:
Find the sum of three numbers
Problem#2:
Take time in hour and convert it into seconds
Problem#3:
Take quiz marks (out of 15) as input and find percentage
Problem#4:
Design a program to assist in the design of a hydroelectric dam. Prompt the user for the height
of the dam and for the number of cubic meters of water that are projected to flow from the
top to the bottom of the dam each second. Predict how many megawatts (1MW=10
6
W) of
power will be produced if 90% of the work done on the water by gravity is converted to
electrical energy. Note that the mass of one cubic meter of water is 1000kg.
Use 9.80 meters/seconds as the gravitational constant g.
The relevant formula (w=work, m=mass, g= gravity, h=height) is:
W=mgh
Problem#5:
Take computer file size in GB and display the size in bytes.
Problem#6:
Write a program that calculates time to fill the tank if the tank already has some
water. The initial and final readings of scale on the tank are used to calculate the total liters of
water added. It takes 8 seconds to add one liter of water to the tank. Display time in minutes.
Problem#7:
Find whether a letter a capital letter or small letter
Example 1:
Total purchases $122.00
Teacher’s discount(13%) $15.86
Discounted total 106.14
Sales tax (5%) 5.31
Total $111.45
Example 2:
Total purchases $24.90
Sales tax (5%) 1.25
Total $26.15
Problem#1:
Find the sum of three numbers
/* Find the sum of three numbers */ #includeint main() { int num1 = 0; int num2 = 0; int num3 = 0; int sum = 0; printf(“Enter first number: ”); scanf(“%d”,&num1); printf(“Enter second number: ”); scanf(“%d”,&num2); printf(“Enter third number: ”); scanf(“%d”,&num3); sum = num1 + num2 + num3; printf(“%d + %d + %d = %d\n”, num1, num2, num3, sum); return 0; } //
Problem#2:
Take time in hour and convert it into seconds
/* Take time in hour and convert it into seconds */ #includeint main() { int timeInHours=0; int seconds=0; printf("Enter time in hours :"); scanf("%d", &timeInHours); seconds=timeInHours*3600; printf("Seonds in %d hours=%d\n",timeInHours,seconds); return 0; } //
Problem#3:
Take quiz marks (out of 15) as input and find percentage
/* Take quiz marks (out of 15) as input and find percentage */ #includeint main() { float marksInCs102 = 0.0; float percentage = 0.0; printf(“Enter your CS102 quiz marks (out of 15)”); scanf(“%f”,&marksInCs102); percentage= (marksInCs102/15) * 100; printf(“Your percentage in CS102 quiz is %f”, percentage); return 0; } } //
Problem#4:
Design a program to assist in the design of a hydroelectric dam. Prompt the user for the height
of the dam and for the number of cubic meters of water that are projected to flow from the
top to the bottom of the dam each second. Predict how many megawatts (1MW=10
6
W) of
power will be produced if 90% of the work done on the water by gravity is converted to
electrical energy. Note that the mass of one cubic meter of water is 1000kg.
Use 9.80 meters/seconds as the gravitational constant g.
The relevant formula (w=work, m=mass, g= gravity, h=height) is:
W=mgh
#includeint main() { float height=0.0; float meters=0.0; float work=0.0; float mass=0.0; float gravity=9.80; float w=0.0; float power=0.0; float powerMegaWatt=0.0; printf("Enter dam height: "); scanf("%f", &height); printf("Enter num of cubic meters: "); scanf("%f", &meters); mass=meters*1000; work=mass*gravity*height; power=0.9*work; powerMegaWatt=power/1000000; printf("Power in Megawatts is %.3f", powerMegaWatt); return 0; } //
Problem#5:
Take computer file size in GB and display the size in bytes.
/* (1GB=1024 MB, 1MB=1024 KB, 1KB=1024 bytes) */ #includeint main() { int fileSizeInGb=0; int bytes=0; printf("Enter fileSizeInGb :"); scanf("%d", &fileSizeInGb); bytes=fileSizeInGb*1024*1024*1024; printf("%d Gb in bytes=%d\n",fileSizeInGb,bytes); return 0; } //
Problem#6:
Write a program that calculates time to fill the tank if the tank already has some
water. The initial and final readings of scale on the tank are used to calculate the total liters of
water added. It takes 8 seconds to add one liter of water to the tank. Display time in minutes.
/* Input: Initial scale reading: 23 Input: Final scale reading: 75 Output: Total time taken to fill the tank is 6.93 minutes */ #includeint main() { float initialScaleReading=0.0; float finalScaleReading=0.0; float liters=0.0; float minutes=0.0; printf("Enter initialScaleReading:"); scanf("%f", &initialScaleReading); printf("Enter finalScaleReading:"); scanf("%f", &finalScaleReading); liters=finalScaleReading-initialScaleReading; minutes=liters*8/60; printf("Total time taken to fill the tank is %.2f minutes", minutes); return 0; } //
Problem#7:
Find whether a letter a capital letter or small letter
/* Find whether a letter a capital letter or small letter */ #includeProblem#8: An employee gets a yearly bonus only if his years of service are more than 3 years otherwise he gets no bonus. While years of service are more than 3 , bonus depends upon basic salary of employee. If salary is greater than or equals to 15000 than bonus is 20% of basic salary otherwise 15%.int main() { char ch; printf("Enter a letter: "); scanf("%c" , &ch); if( (ch >= 'a') && (ch <='z') ) { printf("\nThe letter you entered is a small letter\n "); } else if( (ch >= 'A') && (ch <='Z') ) { printf("\nThe letter you entered is a capital letter\n "); } else { printf("\nThis is not an alphabet!\n"); } return 0; } //
#includeProblem#9: Rock-paper-scissor game for 1 round only between player1 and player2int main() { int yearsOfService = 0; float basicSalary = 0.0; float bonus = 0.0; printf("Enter employee's total years of service : "); scanf("%d",&yearsOfService); if(yearsOfService > 3) { printf("Enter employee's monthly basic salary : "); scanf("%f",&basicSalary); if(basicSalary >= 15000.00) { bonus = basicSalary * .2; /* 20% bonus*/ printf("Bonus is %.2f \n" , bonus); } else { bonus = basicSalary * 0.15; /*15% bonus*/ printf("Bonus is %.2f \n" , bonus); } } else { printf("Employee gets no bonus\n"); } return 0; } //
#includeProblem#10: John needs a program to implement teacher’s discount policy. The program is to prompt the user to enter the purchase total and to indicate whether the purchaser is a teacher or not (y/n). If purchaser is not a teacher he/she will not get any discount. The store plans to give each customer a printer receipt, so your program is to create a nicely formatted output. Teachers receive a 13% discount on their purchases unless the purchase total is $100 or higher. The discount calculation occurs before addition of the 5% sales tax.int main() { char player1; char player2; printf("Player 1's Choice :"); scanf(" %c", &player1); printf("Player 2's Choice :"); scanf(" %c", &player2); if((player1 == 'r') && (player2 == 'p')) { printf("Player 2 wins"); } else if((player1 == 'r') && (player2 == 's')) { printf("Player 1 wins"); } else if((player1 == 's') && (player2 == 'p')) { printf("Player 1 wins"); } else if((player1 == 's') && (player2 == 'r')) { printf("Player 2 wins"); } else if((player1 == 'p') && (player2 == 'r')) { printf("Player 1 wins"); } else if((player1 == 'p') && (player2 == 's')) { printf("Player 2 wins"); } else { printf("Match Draw"); } return 0; } //
Example 1:
Total purchases $122.00
Teacher’s discount(13%) $15.86
Discounted total 106.14
Sales tax (5%) 5.31
Total $111.45
Example 2:
Total purchases $24.90
Sales tax (5%) 1.25
Total $26.15
#includeint main () { char teacher; float discountedTotal = 0.0; float totalPurchase = 0.0; float salesTax = 0.0; float teachersDiscounted = 0.0; float totalAmount = 0.0; printf("Are you a teacher? (y/n) :"); scanf("%c", &teacher); if (teacher == 'y') { printf("Enter total amount of your purchase :$"); scanf("%f", &totalPurchase); if(totalPurchase >= 100) { teachersDiscounted = totalPurchase * 0.13; /* 13/100=0.13 13% discount */ printf("Teacher's 13%% Discount is : $%.2f \n", teachersDiscounted); discountedTotal = totalPurchase - teachersDiscounted; printf("Discounted Total is : $%.2f \n", discountedTotal); salesTax = discountedTotal * 0.05; /*5/100=0.5 5% sales Tax */ printf("sale Tax 5%% amount is : $%.2f \n", salesTax); totalAmount=discountedTotal + salesTax; printf("Total Amount is : $%.2f ", totalAmount); } else { salesTax = totalPurchase * 0.05; printf("Sales Tax 5%% is : $%.2f", salesTax); totalAmount = totalPurchase + salesTax; printf("Total Amount is : $%.2f", totalAmount); } } else { printf("Enter total amount of your purchase :$"); scanf("%f", &totalPurchase); salesTax = totalPurchase * 0.05; /* 5/100=0.5 5% sales Tax */ printf("Sales Tax 5%% is : $%.2f \n", salesTax); totalAmount = totalPurchase + salesTax; printf("Total Amount is : $%.2f \n", totalAmount); } return 0; } //
Problem#11: Take distance in km as input and display the distance in m.
#includeProblem#12: Take time in hours as input and display the time in seconds.float calculateKmToM(float distInKm); /* function declaration */ int main () { float km = 0.0; float m = 0.0; printf("Enter distance in kilometer :"); scanf("%f" , &km); m = calculateKmToM(km); /* function calling */ printf("Distance in meters is : %.2f" , m ); return 0; } float calculateKmToM(float distInKm) { float distInM = 0.0; /* local variable declaration */ distInM = distInKm * 1000; return distInM; } //
#includeProblem#13: Take distance in km and time in hours as input and display the speed in km/hr.float timeInHours(float timeInHours); int main(){ float hrs=0.0; float secs=0.0; printf("Enter time in Hours :"); scanf("%f" , &hrs); secs=timeInHours(hrs); printf("Time in Seconds is : %.1f", secs); return 0; } float timeInHours(float timeInHours){ float secs=0.0; secs=timeInHours * 3600; return secs; } //
#includeProblem#14: Take distance in km and time in hours as input and display the speed in m/s.float calculateSpeed(float km, float hrs); int main(){ float km=0.0; float hrs=0.0; float speed=0.0; printf("Enter Distance in Km :"); scanf("%f", &km); printf("Enter time in hours :"); scanf("%f", &hrs); speed = calculateSpeed(km, hrs); printf("Speed is : %.1f", speed); return 0; } float calculateSpeed(float km, float hrs){ float speed=0.0; speed = km/hrs; return speed; } //
#includeProblem#15: Take temperature in Centigrade as input and convert it into Kelvin i.e. K = C + 273float calculateSpeed(float km, float hrs); int main(){ float km=0.0; float hrs=0.0; float speed=0.0; printf("Enter Distance is kilometers :"); scanf("%f", &km); printf("Enter Time in hours :"); scanf("%f", &hrs); speed = calculateSpeed(km, hrs); printf("Speed in m/s is : %.2f", speed); return 0; } float calculateSpeed(float km, float hrs){ float speed=0.0; float m=0.0; float secs=0.0; m = km * 1000; secs = hrs * 3600; speed = m/secs; return speed; } //
#includeProblem#16: Take temperature in Fahrenheit as input and convert it into Centigrade i.e. C = 5*(F-32)/9float convertInToKelvin(float centigrade); int main(){ float centigrade=0.0; float kelvin=0.0; printf("Enter Temperature in Centigrade :"); scanf("%f", ¢igrade); kelvin = convertInToKelvin(centigrade); printf("Temperature in Kelvin is : %.1f", kelvin); } float convertInToKelvin(float centigrade){ float kelvin=0.0; kelvin = centigrade + 273; return kelvin; } //
#includeProblem#17: Take temperature in Fahrenheit as input and convert it into Kelvin.float converInToCentigrade(float fahrenheit); int main(){ float centigrade=0.0; float fahrenheit=0.0; printf("Enter Temperature in Fahrenheit :"); scanf("%f", &fahrenheit); centigrade = converInToCentigrade(fahrenheit); printf("Temperature in Centigrade is %.1f", centigrade); return 0; } float converInToCentigrade(float fahrenheit){ float centigrade=0.0; centigrade = 5 * (fahrenheit-32)/9; return centigrade; } //
#includeProblem#18: Get the least significant digit (right-most) of a 3-digit number.float converInToKelvin(float fahrenheit); int main(){ float fahrenheit=0.0; float kelvin=0.0; printf("Enter Temperature in Fahrenheit :"); scanf("%f", &fahrenheit); kelvin = converInToKelvin(fahrenheit); printf("Temperature in Kelvin is : %.2f", kelvin); return 0; } float converInToKelvin(float fahrenheit){ float kelvin = 0.0; kelvin = (fahrenheit -32) * 5/9 + 273.15; return kelvin; } //
#includeProblem#19: Find out whether the input number is positive, negative or zeroint leastSignificant(int threeDigitNum); int main(){ int threeDigitNum=0; int lsd=0; printf("Enter Three Digit Number : "); scanf("%d", &threeDigitNum); lsd = leastSignificant(threeDigitNum); printf("Least Significant digit is : %d", lsd); return 0; } int leastSignificant(int threeDigitNum){ int lsd=0; lsd = (threeDigitNum % 10); return lsd; } //
#includeProblem#20: Input four lengths a, b, c and d and find out whether they ‘can’ form a valid square. float distInKm float distInM CalculateKmToMvoid positiveNegativeZero(int num); int main(){ int num=0; printf("Input any number :"); scanf("%d", &num); num = positiveNegativeZero(num); return 0; } void positiveNegativeZero(int num){ if (num > 0){ printf("Number is Positive"); return +num; } else if (num < 0){ printf("Number is Negative"); return -num; } else{ printf("Number is Zero"); return 0; } } //
#includeProblem#21: Two player guessing gamevoid validSquare(int a, int b, int c, int d); int main(){ int a=0; int b=0; int c=0; int d=0; int square=0; printf("Enter Length A :"); scanf("%d", &a); printf("Enter Length B :"); scanf("%d", &b); printf("Enter Length C :"); scanf("%d", &c); printf("Enter Length D :"); scanf("%d", &d); square = validSquare(a,b,c,d); return 0; } void validSquare(int a, int b, int c, int d){ int result=0; int square=0; if ((a==b) && (b==c) && (c==d)){ printf("It's a Valid Square"); } else{ printf("It's not a Valid Square"); } return square; } //
#includeProblem#22: Consider the next problem. We want to ask user to enter numbers and keep adding them until the user presses -1. We assumed -1 to be the stopping value. When user presses -1, loop stops and program shows total sum.int main() { int number = 0, guess = 0; int counter= 0; /*to count user attemps*/ /* asking player1 to enter a number */ printf("Player 1 !! enter a number between 1 to 10 :"); scanf("%d" , &number); /* asking player2 to guess the number player1 entered */ printf("Player 2 !! Guess the number: "); scanf("%d" , &guess); while(guess != number) /* if player2 guessed wrong ask again */ { counter++; printf("Wrong \n"); printf("Player 2 !! Guess the number again.."); scanf("%d",&guess); } printf("great!! u guessed after %d wrong attempts..", counter); return 0; } //
#includeint main() { int num = 0, totalScore = 0; printf("Enter number:"); /*input number*/ scanf("%d",&num); while(num != -1) /*if num is not equal to sentinel value (stopping value which we assume is -1) */ { totalScore = totalScore + num; printf("Enter number:"); scanf("%d",&num); } printf("Your total score is %d",totalScore); return 0; } //
#includeProblem#24: Program takes grade as input and comments according to itint main() { float marks =0.0; float percentage=0.0; char status = 'y'; /*we initialized status to 'y' , means yes , to indicate that the user wants to calculate percentage . if we do not initialize status with ‘y’ or ‘Y’ the loop will not even start*/ /*check if status contains ‘y’ or ‘Y’*/ while(status == 'y' || status == 'y') { printf("Enter your marks out of 500:"); /*input marks*/ scanf("%f",&marks); percentage = (marks /500) *100; printf("Your percentage is %.2f \n", percentage); /*ask user f wants to continue agian*/ printf("Do you want to calculate percentage again? (y/n): "); scanf(" %c" , &status); /*remember buffer problem in multiple character input? put a space before %c*/ } return 0; } //
#includeProblem#25: Modified version of above Program that takes grade as input and comments according to it. Now it works for both capital and small caseint main () { char grade ; printf("Enter Your Grade: "); scanf("%c", &grade); /*Input grade */ switch(grade) /*examine value in grade*/ { case 'A' : /* check if grade is equal to ‘A’*/ printf("Excellent work!\n" ); break; case 'B' : /* check if grade is equal to ‘B’*/ printf("Good Job!\n" ); break; case 'C' : /* check if grade is equal to ‘C’*/ printf("Well done\n" ); break; case 'D' : /* check if grade is equal to ‘D’*/ printf("You passed\n" ); break; case 'F' : /* check if grade is equal to ‘F’*/ printf("Better try again\n" ); break; default : /*if no case matches run default block*/ printf("Invalid grade\n" ); } return 0; } //
#includeProblem#26: Input two numbers. Ask user to enter a character +, -, * or / to choose the operation to perform among these numbers. Use switch statement to make a decision and, work and show result accordingly.int main () { char grade ; printf("Enter Your Grade: "); scanf("%c", &grade); /*Input grade */ switch(grade) /*examine value in grade*/ { case 'A' : /* check if grade is equal to ‘A’*/ case 'a' : printf("Excellent work!\n" ); break; case 'B' : /* check if grade is equal to ‘B’*/ case 'b' : printf("Good Job!\n" ); break; case 'C' : /* check if grade is equal to ‘C’*/ case 'c' : printf("Well done\n" ); break; case 'D' : /* check if grade is equal to ‘D’*/ case 'd' : printf("You passed\n" ); break; case 'F' : /* check if grade is equal to ‘F’*/ case 'f' : printf("Better try again\n" ); break; default : /*if no case matches run default block*/ printf("Invalid grade\n" ); } printf("Your grade is %c\n", grade ); return 0; } //
#includeProblem#27: create a program that takes an alphabet as input and shows if it’s a vowel or not. Using while loop make sure that the input character is an alphabet. If not, ask user again to input character.int main() { int num1=0; int num2=0; int sum=0; char process=0; char product=0; char subtract=0; char multiplication=0; char division=0; printf("Enter first Number :"); scanf("%d", &num1); printf("Enter second Number :"); scanf("%d", &num2); printf("Please Choice Any One of The Following Operations +,-,x,/ :"); scanf(" %c", &process); switch(process) { case '+' : product = num1 + num2; printf("Sum Results : %d", product); break; case '-' : subtract = num1 - num2; printf("Subtraction Results : %d", subtract); break; case '*' : multiplication = num1 * num2; printf("Multiplication Results : %d", multiplication); break; case '/' : division = num1 / num2; printf("Division Results : %d", division); break; default : printf("Please Input Valid Operation"); } return 0; } //
#includeProblem#28: calculate percentage as long as the user wishesint main() { char alphabet; printf("Enter an Alphabet :"); scanf(" %c", &alphabet); while ((alphabet < 65 ) || (alphabet > 122)) { printf("~~Invalid Input~~ \n"); printf("Please Input Valid Alphabet :"); scanf(" %c", &alphabet); } switch (alphabet) { case 'a' : case 'A' : printf("Alphabet is Vowel"); break; case 'e' : case 'E' : printf("Alphabet is Vowel"); break; case 'i' : case 'I' : printf("Alphabet is Vowel"); break; case 'o' : case 'O' : printf("Alphabet is Vowel"); break; case 'u' : case 'U' : printf("Alphabet is Vowel"); break; default : printf("Alphabet you Entered isn't Vowel"); } return 0; } //
#includeProblem#29: print tables of first five natural numbersint main() { float marks =0.0, percentage=0.0; char status = 0; do { printf("Enter your marks out of 500:"); /*input marks*/ scanf("%f",&marks); percentage = (marks /500) *100; printf("Your percentage is %.2f \n", percentage); /*ask user f wants to continue */ printf("Do you want to calculate percentage again? (y/n): "); scanf(" %c" , &status); /*remember buffer problem in multiple character input? put a space before %c*/ } while(status == 'y' || status == 'Y'); return 0; } //
int main() { int i=0, j =0; for(i=1 ; i<=5 ;i++) { printf("TABLE OF NUMBER %d\n" , i); for(j = 1; j <= 10; j++) { printf("%d * %d = %d\n", i, j , i*j); } printf("\n"); } return 0; } //
#includeProblem#31: find maximum value in an arrayint main() { int subMarks = 0; int subs = 0; int total = 0; char status = 0; do { total = 0; for(subs=1; subs<=5; subs++) { printf("Enter your total marks of subjects %d out of 100 :", subs); scanf("%d", &subMarks); while(subMarks > 100) { printf("~~Invalid Input~~ \n"); printf("Please Enter your total marks of subject %d out of 100 :", subs); scanf("%d", &subMarks); } total = total + subMarks; } printf("Your Total Marks of 5 subjects is : %d \n", total); printf("Do you want to Calculate your marks again? (y/n) :"); scanf(" %c", &status); } while (status == 'y' || status == 'Y'); return 0; } //
#includeProblem#33: Declare an array of char that holds vowels in small letters i.e. char vowel[5] = {‘a’ , ‘e’ , ‘I’ , ‘o’ , ‘u’} Create a function named capitalized that takes two parameters, first is the above mentioned array and second its size. This function changes all vowels to upper case. void capitalized (char arr[] , int size) Print array after capitalization Note: Use #define constant to set size of the arrayint findMax (int arr[]); int main() { int array[10] ={} , maximum = 0, i = 0; printf("Enter 10 integers:\n" ); for ( i = 0 ; i < 10 ; i++ ) { scanf("%d", &array[i]); } maximum = findMax(array); printf("maximum element is %d.\n", maximum); return 0; } int findMax (int arr[]) { int max=0, i=0; max = arr[0]; for ( i = 1; i < 10; i++ ) { if ( arr[i] > max) { max = arr[i]; } } return max; } //
/* vowel.c Written by Syed Rizwan Ali Shah */ #includevoid capitalized (char arr[] , int size); void printArray(int arr[], int size); #define N 5 /* Taking constant of 5 */ int main() { int size; char arr[N]={'a' , 'e' , 'i' , 'o' , 'u'}; capitalized (arr ,size); return 0; } void capitalized (char arr[N] , int size) { if (arr[0] == 'a') { size = 65; printf("Vowels in upper case are\n %c \t", size); } if (arr[1] == 'e') { size = 69; printf("%c \t", size); } if (arr[2] == 'i') { size = 73; printf("%c \t", size); } if (arr[3] == 'o') { size = 79; printf("%c \t", size); } if (arr[4] == 'u') { size = 85; printf("%c \t", size); } } /* void capitalized (char arr[N] , int size) { int i; if ((arr[N]== 'a' || 'e') && (arr[N] == 'i' || 'o') && (arr[N]== 'u')) { int i; for (i=0; i<5 data-blogger-escaped-are="" data-blogger-escaped-arr="" data-blogger-escaped-c="" data-blogger-escaped-case="" data-blogger-escaped-i="" data-blogger-escaped-in="" data-blogger-escaped-owels="" data-blogger-escaped-printf="" data-blogger-escaped-stdio="" data-blogger-escaped-upper="">
/* Written by Syed Rizwan Ali Shah */ #includeint main() { int id=0; int pay=0; int tax=0; int netPay=0; int i=0; /* variable for "for loop" */ FILE *fptr; fptr = fopen("emp.txt","w"); if(fptr == NULL) { printf("file not created"); } else { /* Heading of all columns */ fprintf(fptr,"Id \t"); fprintf(fptr,"Pay \t"); fprintf(fptr,"Tax \t"); fprintf(fptr,"Net Pay \n"); /* For loop, for multiple inputs */ for (i=1; i<=5;i++) { /* Input for Employee's ID */ printf("\n"); /* So user will be more comfortable in entering employee's ID and Employee's Pay */ printf("Enter Employee No:%d's ID :", i); scanf("%d", &id); fprintf(fptr,"\n %d \t", id); /* Input for Employee's Pay */ printf("Enter Employee No:%d's Pay :", i); scanf("%d", &pay); fprintf(fptr,"%d \t ", pay); tax = pay / 50; /* tax calculation */ netPay = pay - tax; fprintf(fptr, "%d \t", tax); fprintf(fptr, "%d \t \n", netPay); } } fclose(fptr); return 0; } //
nice collection!
ReplyDeleteReally amazing things thanks for sharing this types of knowledge please keep updating us.
ReplyDelete