Basic C Practice Problems

Posted on December 18, 2023 by Vishesh Namdev
Python C C++ Javascript Java
C Programming Language

Basic Practice Problems based on chapter which you learn in previous Tutorials.

1. Addition of two numbers

#include <stdio.h> Copy Code
int main () {
// Declare variables to store the numbers
int num1, num2;

// Prompt the user to enter the first number
printf ("Enter the first number: ");
scanf ("%d", &num1);

// Prompt the user to enter the second number
printf ("Enter the second number: ");
scanf ("%d", &num2);

// Calculate the sum
int sum = num1 + num2;

// Display the result
printf ("Sum: %d ", sum);

return 0;
}

2. Find the size of int, char, float and double

#include <stdio.h> Copy Code
int main () {
// Find the size of int
printf ("Size of int: %lu bytes ", sizeof (int));

// Find the size of char
printf ("Size of char: %lu bytes ", sizeof (char));

// Find the size of double
printf ("Size of double: %lu bytes ", sizeof (double));

// Find the size of float
printf ("Size of float: %lu bytes ", sizeof (float));

return 0;
}
1. sizeof(int): Returns the size of an int in bytes.
2. sizeof(char): Returns the size of a char in bytes.
3. sizeof(double): Returns the size of a double in bytes.
4. sizeof(float): Returns the size of a float in bytes.

3. Find the Quotient and Remainders of given number

#include <stdio.h> Copy Code
int main () {
// Declare variables
int dividend, divisor, quotient, remainder;

// Get input from the user
printf ("Enter the dividend: ");
scanf ("%d", &dividend);

printf ("Enter the divisor: ");
scanf ("%d", &divisor);

// Calculate quotient and remainder
quotient = dividend / divisor ;
remainder = dividend % divisor ;

// Display the result
printf ("Quotient: %d ", quotient );
printf ("Remainder: %d ", remainder );

return 0;
}

1. dividend is the number to be divided.
2. divisor is the number by which the division is performed.
3. quotient is the result of the division (dividend / divisor).
4. remainder is the remainder of the division (dividend % divisor).

4. Swap two numbers

Swapping two number in C programming language means exchanging the values of two variables. Suppose you have two variable var1 & var2. Value of var1 is 20 & value of var2 is 40.

#include <stdio.h> Copy Code
int main () {
int num1, num2;

printf ("Enter the first number: ");
scanf ("%d", &num1);

printf ("Enter the second number: ");
scanf ("%d", &num2);

// Swap without using a temporary variable
num1 = num1 + num2 ;
num2 = num1 - num2 ;
num1 = num1 - num2 ;

printf ("After swapping: ");
printf ("First number: %d ", num1 );
printf ("Second number: %d ", num2 );

return 0;
}

How did you feel about this post?

๐Ÿ˜ ๐Ÿ™‚ ๐Ÿ˜ ๐Ÿ˜• ๐Ÿ˜ก

Was this helpful?

๐Ÿ‘ ๐Ÿ‘Ž