Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

Basic C programming exercises

The document contains a series of C programming exercises divided into two parts: basic declarations and operations, and conditional statements and loops. Each exercise focuses on different aspects of C programming, including variable declarations, arithmetic operations, input/output, error handling, and control structures. The exercises range from simple tasks like printing messages to more complex problems involving calculations, condition checks, and loops.

Uploaded by

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

Basic C programming exercises

The document contains a series of C programming exercises divided into two parts: basic declarations and operations, and conditional statements and loops. Each exercise focuses on different aspects of C programming, including variable declarations, arithmetic operations, input/output, error handling, and control structures. The exercises range from simple tasks like printing messages to more complex problems involving calculations, condition checks, and loops.

Uploaded by

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

C programming exercises

Part I: Basic declarations, operations, input and output


Exercise 1: Mark variable declarations, assignment operations, operators, and expressions of the following
code. Which is the result of the evaluation of each expression?

int i1, i2, i3;


float r1, r2, r3;
i1=12;
i2=5;
r1=12.0;
r2 =5;
r3= r1/r2;
r3=i1/i2;
i3=i1/r2;

Exercise 2: Are the following statements right? Explain your answer


i=i+1
printf("%d", 4+20);
printf("sum = var_one + var_two = %d + %d", var_one, var_two, sum);

Exercise 3: Write a program that declares an integer variable and assigns it a value. The program must show the
value of the variable and its memory address.
Exercise 4: Which is the value of r after the following code snippet?
float n=6.0, m=2.0, r;
r = 25.0 + 120 * n / m;
Exercise 5: Write a program to calculate the remainder of the division of two integers. Use the module operator
(%)
Exercise 6: Write a C program to print your name, date of birth, and mobile number.
Exercise 7: Write a C program to print a block F using the hash (#), where the F has a height of six characters
and width of five and four characters. And also print a very large 'C’.

Exercise 8: Find the errors of the following program:

int main(void) {
foat radius, circum;
printf(type the radius);
scanf("%f", &radius);
circum = 2 * PI * radius
printf("%f", circum);
return 0;

1
NF-TechHub USS-CSC-C language GBHS & SPECC Dschang
Exercise 9: Write a C program to assign the value 4/0 to an integer variable. What happens when the program
is compiled? What happens when the program is executed?
Exercise 10: Write a C program that reads two integer values from the keyboard (x, y) and prints on the screen
x/y and x%y. Run the program several times with different inputs. What happens when the variable y gets the
value 0?
Exercise 11: Write a program that calculates the area of a right-angled triangle. The program must ask the
height and the length of the base. The output of the program must be: Rightangled triangle of height __ and
base __. Area __. (Blank spaces are filled with the actual values). (NOTE: Area = (base * height) / 2 )

Exercise 12: Compiler Messages Take your completed working program that calculates the area of a right-
angled triangle, and make a series of single changes that introduce errors (for example delete single lines,
change the names of variables in one place only as for a typing error, delete brackets, etc). After each change
made, compile the program, make a note of the error message and its cause, work out what the error message
means, correct the program and recompile it to ensure it has been fixed, then insert the next error.

Exercise 13: Write a program that reads a temperature in degrees Fahrenheit and prints out the corresponding
temperature in degrees Celsius (C = (F - 32) * 5 / 9). Make the program 'user friendly' (this applies to all
subsequent programs you write - ever!).

Extend the program to calculate the area of a circumference.

Exercise 14: Write a C program that declares two variables, x (integer) and y (float) and directly assign them
the values 6 and 2.0. The program must print on the screen the results of the expressions below:

x*y
3*x*y
3*x/y
3*x%y

What happens when the program is compiled? How would you fix this error?
Exercise 15: Write a C program with the code below and compile it. Is there any error?

#include
int main(void){
int a, b;
char string[8];
int c;
a=7; b=14; c=128;
printf ("Type a word: ");
scanf("%[^\n]", string);
printf("String is %s\n", string);
printf("Variables values are:\na=%d\nb=%d\nc=%d\n", a, b, c);
system("pause");
return 0;
}
Run the program by using Hello as input. What happens?

Run the program again by entering Supercscstudentsgbhsdschang. What happens?


2
NF-TechHub USS-CSC-C language GBHS & SPECC Dschang
Exercise 16: Write a C program with the code below and compile it. Study the output of the program as a result
of the use of different format modifiers.

#include <stdio.h>
int main (void) {
printf("Type formats in printf \n\n");
printf("------------------------\n");
printf("Floating point values \n");
printf("Float literal 1234.12345678\n");
printf("> 8 spaces, 1 decimal value 8.1f: [%8.1f] \n", 1234.12345678);
printf("> 8 spaces, 3 decimal values 8.3f: [%8.3f] \n", 1234.12345678);
printf("> 2 spaces, 3 decimal values 2.3f: [%2.3f] \n", 1234.12345678);
printf("> 12 spaces,6 decimal values 12.6f: [%12.6f] \n", 1234.12345678);
printf("> 20 spaces,6 decimal values 20.6f: [%20.6f] \n", 1234.12345678);
printf("> same as before, left align -20.6f: [%-20.6f] \n", 1234.12345678);
printf("\n------------------------\n");
printf("Strings \n");
printf("String [hello madrid] \n");
printf("> Direct print: [hello madrid] \n");
printf("> With placeholder: [%s] \n", "hello madrid");
printf("> Using width specifier (20 spaces, 4 letters) 20.4s: [%20.4s] \n", "hello madrid");
printf("\n"); system ("pause");
return (0);
}

Exercise 17: Write a C program that prints on the screen a welcome message and asks the user’s birth year,
which must be stored in a variable named dateU. The program must calculate the current age of the user and
print on the screen You were born in <date> You are this <year>, being date and age the read and the
calculated value, respectively.
You are recommended to create the program incrementally, and to check compilation errors after developing
each program section.

Exercise 18: Write a C program to perform addition, subtraction, multiplication and division of two numbers.
Sample expected output:
Input any two numbers separated by comma : 15 , 7.5
The sum : 15 + 7.5 = 22.5
The difference: 15 – 7.5 = 7.5
The product : 15 * 7.5 = 112.50
The quotient: 15 * 7.5 = 2.0000

Exercise 19: Write a program that calculates the volume (V) and surface area (A) of a
cylinder using the values entered by user. Display the volume and the surface area. Set the
precision up to four decimal places.

Exercise 20: Write a C program to swap two numbers.

3
NF-TechHub USS-CSC-C language GBHS & SPECC Dschang
Part II: Conditional statements and loops
Exercise 1: What is the output of each of the following code fragments? (Given the declaration int a=1, b=2,
c=3;):
1. if (6 < 2 * 5){ 5. int x = 100; int y = 200;
printf("Hello"); if (x > 100 && y <=200){
printf ("There"); printf ("%d %d %d", x, y, x+y);
} }else {
printf ("%d %d %d", x, y, 2*x-y); }
2. if(a>b) {
if(a>c) { 6. if (a < c) {
printf ("1111"); printf ("*");
else { } else if (a == c) {
printf ("2222");
printf ("&");
}}
}else {
printf ("$"); }
3. if (a < c) {
printf ("*");}
7. if(++a > b++ || a-- > 0){
else if (a == b){
c++;
printf ("&");} }else{
else { printf ("$")}; c--;
printf ("%d %d %d", a, b, c);}
4. if(a<b) {
printf ("####"); } 8. if(‘a’ > ‘b’ || 66 > (int)(‘A’)) {
else { printf ("#*#");}
printf ("&&&&");
printf ("****");}

Exercise 2: Write a C program to read the age of a candidate and determine whether he is eligible to cast
his/her own vote in 2025.

Exercise 3: Write a C program to accept the height of a person in centimeters and categorize the person
according to their height.

Height in cm Category
<150cm Dward
<166cm Short
<175cm Average
>=175cm Tall

Exercise 4: Write a C program that read a number from the user and determine if the number is even or odd.

Exercise 5: Write a C program to read the roll no, name and marks of three subjects and calculate the total,
average and grade.
Average >= 90% : Grade A Average >= 80% : Grade B Average >= 70% : Grade C
Average >= 60% : Grade D Average >= 40% : Grade E Average < 40% : Grade F

4
NF-TechHub USS-CSC-C language GBHS & SPECC Dschang
Sample expected output:
Input the Roll Number of the student :655
Input the Name of the Student :Divine
Input the marks of Computer, Maths and Physics: 90 80 70
#################################
Roll No : 655
Name of Student : Divine
Marks in Computer : 90
Marks in Maths : 80
Marks in Physics : 70
Total Marks = 240
Average = 80
Grade : B

Exercise 6: An electric power distribution company charges its domestic consumers as follows.
Consumption Units Rate of Charge
0-200 0.50fcfa per unit
201-400 100fcfa plus 0.65fcfa per unit excess 200
401-600 230fcfa plus 0.80fcfa per unit excess of 400.
An additional surcharge of 20% is added to the bill
Write a C program that reads the customer number and power consumed and prints the amount to be paid by the
customer.
Exercise 7: Write a C program to read temperature in centigrade and display a suitable message according to
the temperature state below:
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
Exercise 8: Write a C program to check whether a triangle is Equilateral, Isosceles or Scalene.
Exercise 9: Write a C program to check whether a character is an alphabet, digit or special character.
Sample test Data: @
Sample expected output: This is a special character.
Exercise 10: Write a program in C to read any Month number in integer then display the month name and
number of days for this month.
Sample test Data: 7
Sample expected output: July has 31 days
Exercise 11:
1) Write a program in C to display the first 10 natural numbers.
Sample expected output: 1 2 3 4 5 6 7 8 9 10
2) Extend the program to calculate the sum of the first 10 natural numbers and display it
Sample expected output:
1 2 3 4 5 6 7 8 9 10

5
NF-TechHub USS-CSC-C language GBHS & SPECC Dschang
The sum is: 55

3) Extend the program to calculate the average of the first 10 natural numbers and display
Sample expected output:
1 2 3 4 5 6 7 8 9 10
The sum is: 55
The average is: 5.5

4) Extend the program so that it can be used to calculate the sum and the average of the any first n natural
numbers and display it. (Note the value of n is entered by the user.)
Exercise 12:
1) Write a C program to calculate the factorial of a given number.
Note: n! = n * (n-1) * (n-2) … * 1 e.g 5! = 5 * 4 * 3* 2 *1 = 120
2) Extend the program so that it calculate the factorial of the n first numbers specify by the user.
Exercise 13:
1) Write a C program to calculate the Fibonacci of a given number.
Note: F0 = 0, F1 = 1 and Fn = Fn-1 + Fn-2 for n > 1
2) Extend the program so that it calculate the Fibonacci series within a given number of ranges

Exercise 14:
1) Write a C program to check whether a given number is a 'Perfect' number or not.
Sample test Data
Input the number : 56
Expected Output :
The positive divisor : 1 2 4 7 8 14 28
The sum of the divisor is : 64
So, the number is not perfect.
2) Extend the program to find the 'Perfect' numbers within a given number of ranges.
Sample test Data: 50
Expected Output: The Perfect numbers within the given range are: 6 28

Exercise 15:

1) Write a program in C to find if a given number is a prime or not.


Note: A prime number is a whole number greater than 1 whose only factors are 1 and itself. The first
few prime numbers are 2, 3, 5, 7, 11, 13, 17, 19, 23 and 29. Numbers that have more than two factors
are called composite numbers.
2) Extend the program to find the prime numbers within a range of numbers.

Exercise 16: Write a C program to display Pascal's triangle.

Exercise 17: Write a program to check whether the given number is a palindrome or not.
Note: A palindrome number is a number (such as 16461) that remains the same when its digits are reversed

Exercise 18: Write a program to check whether the given number is an Armstrong number or not.
Note: Armstrong number is a number that is equal to the sum of cubes of its digits. For example 0, 1, 153, 370,
371 and 407. 153 = 13 +53 + 33

6
NF-TechHub USS-CSC-C language GBHS & SPECC Dschang
Exercise 19: Write a program to print the multiplication table in the following format.

1 2 3 4 5
1 1 2 3 4 5 *
2 2 4 6 8 10 ***
3 3 6 9 12 15 *****
4 4 8 12 16 20 *******
5 5 10 15 20 25 *********
*******
Exercise 20: Write a program in C to display a pattern like a diamond. *****
***
*

Exercise 21: Use a nested while loop to reproduce the following output

1
22
333
4444
55555

Exercise 22:

1) Write a C program that prompts the user to input a series of integers until the user enter 0 to stop using a
while loop.
2) Extend the program to Calculate and print the sum of all the positive integers entered.

Exercise 23: Write a C program that generates a random number between 1 and 20 and asks the user to guess
it. Use a while loop to give the user multiple chances until they guess the correct number.

Exercise 24: Write a C program that prompts the user to input a series of numbers until they input a duplicate
number. Use a while loop to check for duplicates.

Exercise 25:

1) Write a C program to input number from user and check whether number is Strong number or not.
Note: a Strong number is a special number whose sum of the factorial of digits is equal to the original
number. For Example: 145 is strong number. Since, 1! + 4! + 5! = 145
2) Extend the program to display all the strong number within a given range
Note: 1, 2 and 145 are the only strong numbers between 1 to 1000.

7
NF-TechHub USS-CSC-C language GBHS & SPECC Dschang

You might also like