C++ Practice Questions for Beginners with Solutions

In this article, I will take you through some very important C++ practice questions for beginners with their solutions. Here I will cover some most important programs like prime numbers, reversing a number and Armstrong numbers.

C++ Practice Questions for Beginners

The first problem is to write a program with C++ programming language to check if a number is prime or not.

Also, Read – Benefits of Competitive Coding.

Prime numbers are numbers which have only 2 distinct factors i.e 1 and the number itself. Eg. 2,3,5,7,19 etc. Now let’s see how to identify whether a number is prime or not by using the C++ programming language:

#include<iostream>
#include<cmath>
using namespace std;
int main(){
    int n;
    cout<<"enter number :";
    cin>>n;
    bool flag = 0;
    for(int i = 2; i<=sqrt(n); i++){
        if (n%i == 0){
            cout<<"Not a Prime Number";
            flag = 1;
            break;
        }
    }
    if(flag == 0){
        cout<<"Prime number"<<endl;
    }
    return 0;
}

enter number :7
Prime number

The second problem is to write a program using the C++ programming language to reverse a number. For example, Given a number 1879 we need to convert it to 9781. 100020 will be converted to 20001 (Note: We need to remove the trailing zeroes).

Now let’s see how to reverse a number using the C++ programming language:

#include<iostream>
using namespace std;
int main(){
    int n;
    cout<<"enter number :";
    cin>>n;
    int reverse = 0;
    while(n>0){
        int lastdigit = n%10;
        reverse = reverse * 10 + lastdigit;
        n = n/10;
    }
    cout<<reverse<<endl;
    return 0;
}

enter number :7889
9887

The third problem is to write a program using the C++ programming language to check if a number is Armstrong number or not.

Armstrong numbers are numbers which have their sum of cube of individual digits equal to the number itself. Now let’s see how to identify Armstrong numbers by using the C++ programming language:

#include<iostream>
#include<math.h>
using namespace std;
int main(){
    int n;
    cout<<"Enter Number :";
    cin>>n;
    int sum = 0;
    int originaln = n;
    while(n>0){
        int lastdigit = n%10;
        sum+= pow(lastdigit,3);
        n = n/10;
    }
    if(sum == originaln){
        cout<<"Armstrong number"<<endl;
    }
    else{
        cout<<"not an armstrong number"<<endl;
    }
    return 0;    
}

Enter Number :371
Armstrong number

I hope you liked this article on the C++ practice questions for beginners with solutions. Feel free to ask your valuable questions in the comments section below.

Aman Kharwal
Aman Kharwal

I'm a writer and data scientist on a mission to educate others about the incredible power of data📈.

Articles: 1501

Leave a Reply