Basic Example
Note:
In C++ the variables can be declared any where in the program , but they have to be declared before they are used.
Question:1
C++ program to take input for two numbers calculate and print their sum?
Sol:
#include<iostream> using namespace std; int main() { int a,b,c; cout<<"Enter 1st no "; cin>>a; cout<<"Enter 2nd no "; cin>>b; c=a+b; cout<<"Sum = "<<c<<endl; return(0); }
/* Output */ Enter 1st no 10 Enter 2nd no 20 Sum = 30
Question:2
C++ program to calculate and print square and cube of a number?
Sol:
#include<iostream> using namespace std; int main() { int n,s,c; cout<<"Enter any no "; cin>>n; s=n*n; c=n*n*n; cout<<"Square = "<<s<<endl; cout<<"Cube = "<<c<<endl; return(0); }
/* Output */ Enter any no 5 Square = 25 Cube = 125
Question:3
C++ program to calculate and print sum, prod, and difference between two numbers?
Sol:
#include<iostream> using namespace std; int main() { int a,b,s,p,d; cout<<"Enter 1st no "; cin>>a; cout<<"Enter 2nd no "; cin>>b; s=a+b; p=a*b; if(a>b) d=a-b; else d=b-a; cout<<"Sum = "<<s<<endl; cout<<"Prod = "<<p<<endl; cout<<"Diff = "<<d<<endl; return(0); }
/* Output */ Enter 1st no 10 Enter 2nd no 20 Sum = 30 Prod = 200 Diff = 10