Basic Practice Problems In C++

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 <iostream> Copy Code
int main () {
// Declare variables to store the two numbers
double num1, num2;

// Input the two numbers
std::cout << "Enter the first number: ";
std::cin >> num1;

std::cout << "Enter the second number: ";
std::cin >> num2;

// Perform addition
double sum = num1 + num2;

// Display the result
std::cout << "Sum: " << sum << std::endl;

return 0;
}

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

#include <iostream> Copy Code
int main () {
// Size of int
std::cout << "Size of int: " << sizeof (int) << " bytes" << std::endl ;

// Size of char
std::cout << "Size of char: " << sizeof (char) << " bytes" << std::endl ;

// Size of float
std::cout << "Size of float: " << sizeof (float) << " bytes" << std::endl ;

// Size of double
std::cout << "Size of double: " << sizeof (double) << " bytes" << std::endl ;

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 <iostream> Copy Code
int main () {
int dividend, divisor;

// Input the dividend and divisor
std::cout << "Enter the dividend: " << std::cin >> dividend;
std::cout << "Enter the divisor: " << std::cin >> divisor;

// Check if the divisor is not zero
if (divisor != 0) {
// Calculate quotient and remainder
int quotient = dividend / divisor;
int remainder = dividend % divisor;

// Display the results
std::cout << "Quotient: " << quotient << std::endl ;
std::cout << "Remainder: " << remainder << std::endl ;
} else {
std::cout << "Error: Division by zero is not allowed." << std::endl ;
}

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 <iostream> Copy Code
int main () {
// Declare two variables
int a, b;

// Input the values of the two numbers
std::cout << "Enter the value of a: ";
std::cin >> a;

std::cout << "Enter the value of b: ";
std::cin >> b;

// Swap using a temporary variable
int temp = a;
a = b;
b = temp;

// Display the swapped values
std::cout << "After swapping, the value of a: " << a << std::endl;
std::cout << "After swapping, the value of b: " << b << std::endl;

return 0;
}