-->

4. CPP-Programming Examples

CPP Statements: Previous                                                                Next: CPP Operators
  1. Write a C++ program to take input of two numbers and display their sum on screen:
#include
void main( )
{
    int num1,num2;
    int sum=0;
    cout<<“Enter two Numbers : ”;
    cin>>num1>>num2;
    sum = num1 + num2;
    cout<<“The Sum of Two Numbers is : ”<
}

  1. Write a program to print all the Prime Numbers between 1 to 100.
#include
void main( )
{
    int p=0, i=2, j=1;
    while(j <= 100)
    {
                        i=2;
                        p=0;
                        while(i<=j/2)
                        {
                             if(j%2 == 0)
                             {
                                             p = 1;
                                             break;
                             }
                             i++;
                        }
                        if(p == 0)
                        {
                             cout<<“The Prime Number is : ”<< j;
                        }
                        j++;
    }
}

Output:
program to print all the Prime Numbers between 1 to 100

  1. Write a program to input 10 numbers in array and print count of Even and Odd.
#include
void main( )
{
    int a[10], i, count1=0, count2=0;     
    for(i=0;i<10 i="" span="">
    {
               cout<<“Enter a Number : ”;
               cin>>a[i];
    }
    for(i=0;i<10 i="" span="">
    {
                if(a[i]%2 == 0)
                        count1++;
                else
                        count2++;
    }
    cout<<“The Count of Even Numbers is : ”<
    cout<<“The Count of Odd Numbers is : ”<
}
Note: All control structure, array, pointer, functions works same as C Language.

  1. Write a program to enter a sentence and Count Numbers of Characters.
#include
#include
void main( )
{
    charsentence[30];
    inti, count=0;   
    cout<<“Enter a Sentence : ”;
    gets(sentence);

    for(i=0; sentence[i] != ‘\0’;i++)
    {
                if(sentence[i] == 32)
                        continue;
                else
                        count++;
    }
    cout<<“The Number of Characters is : ”<
}
Output:
program to enter a sentence and Count Numbers of Characters.

  1. Make a function which will accept a number and print sum of digits.
#include
intsum_of_digit(int);
void main( )
{
    intsum=0,num;
    cout<<“Enter a Number : ”;
    cin>>num;

    sum = sum_of_digit(num);

    cout<<“Sum is : ”<
}
intsum_of_digit(intnum)
{
    int digit, sum = 0;
    while(num>0)
    {
              digit = num % 10;
              num = num / 10;
              sum = sum + digit;
    }
    return sum;
}
Output:
program function which will accept a number and print sum of digits

CPP Statements: Previous                                                                Next: CPP Operators