Coding Exercises for Beginners with Solutions (C++)
Practicing coding exercises is one of the best ways to learn C++ programming. It helps improve problem-solving skills and strengthens your understanding of programming concepts.
In this tutorial, you will find beginner-friendly coding exercises along with solutions and explanations.
1. Print Hello World
Write a program to print 'Hello World'.
#include <iostream>
using namespace std;
int main() {
cout << "Hello World";
return 0;
}
2. Add Two Numbers
Write a program to add two numbers.
#include <iostream>
using namespace std;
int main() {
int a = 5, b = 10;
cout << a + b;
return 0;
}
3. Check Even or Odd
Write a program to check whether a number is even or odd.
#include <iostream>
using namespace std;
int main() {
int num = 4;
if(num % 2 == 0)
cout << "Even";
else
cout << "Odd";
return 0;
}
4. Find Largest Number
Write a program to find the largest of two numbers.
#include <iostream>
using namespace std;
int main() {
int a = 10, b = 20;
if(a > b)
cout << a;
else
cout << b;
return 0;
}
5. Swap Two Numbers
Write a program to swap two numbers.
#include <iostream>
using namespace std;
int main() {
int a = 5, b = 10, temp;
temp = a;
a = b;
b = temp;
cout << a << " " << b;
return 0;
}
6. Factorial of a Number
Write a program to find the factorial of a number.
#include <iostream>
using namespace std;
int main() {
int n = 5, fact = 1;
for(int i = 1; i <= n; i++)
fact *= i;
cout << fact;
return 0;
}
7. Reverse a Number
Write a program to reverse a number.
#include <iostream>
using namespace std;
int main() {
int num = 123, rev = 0;
while(num != 0) {
rev = rev * 10 + num % 10;
num /= 10;
}
cout << rev;
return 0;
}
8. Count Digits
Write a program to count the number of digits in a number.
#include <iostream>
using namespace std;
int main() {
int num = 12345, count = 0;
while(num != 0) {
num /= 10;
count++;
}
cout << count;
return 0;
}
9. Check Prime Number
Write a program to check whether a number is prime.
#include <iostream>
using namespace std;
int main() {
int num = 7;
bool isPrime = true;
for(int i = 2; i < num; i++) {
if(num % i == 0) {
isPrime = false;
break;
}
}
if(isPrime)
cout << "Prime";
else
cout << "Not Prime";
return 0;
}
10. Sum of Digits
Write a program to find the sum of digits of a number.
#include <iostream>
using namespace std;
int main() {
int num = 123, sum = 0;
while(num != 0) {
sum += num % 10;
num /= 10;
}
cout << sum;
return 0;
}
Tips to Improve Coding Skills
1. Practice daily.
2. Solve problems step-by-step.
3. Understand logic, not just code.
4. Try variations of problems.
Conclusion
Practicing coding exercises regularly helps build a strong foundation in C++ programming.
Start with simple problems and gradually move to more complex ones to improve your skills.
Codecrown