- WAP to print the table of any asked number.
//table of any number:
#include<iostream>
using namespace std;
int main(){
//take the number whose table you want;
int n;
cin>>n;
// we took upto 10 number only, you can set as per your requirement
for(int i=1; i <= 10; i++){
cout<<n<<" * "<<i<<" = "<< n*i<<endl;
}
return 0;
}
Explanation:
We defined an integer variable, n, to prompt the user for the multiplication table they wish to display. To generate this table, we utilized a looping algorithm that produces results up to the specified range.
2. WAP to print the odd and even numbers
#include<iostream>
using namespace std;
int main(){
int n;
cout<<"Enter the element upto which u want num: ";
cin>>n;
cout<<"Odd numbers are: ";
for(int i = 1; i <= n; i=i+2){
cout<<i<<" ";
}
cout<<endl;
cout<<"Even numbers are: ";
for(int i = 2; i <= n; i=i+2){
cout<<i<<" ";
}
}
3. WAP to print whether the given number is prime or composite.
// given number is prime or composite
#include<iostream>
using namespace std;
int main(){
int n;
cout<<"Enter any num: ";
cin>>n;
bool flag = false;
for(int i = 2; i <= n-1; i++){
if(n % i == 0){
flag = true;
// here, it makes the num composite
}
}
if(!flag){ // flag != true
// not true then it is prime
cout<<"Prime number";
}else{
cout<<"Composite";
}
}
Explanation:
A number is considered prime if it is divisible only by 1 and itself. Therefore, we start checking from an index of 2 up to n-1 to identify composite numbers. If the number is divisible by any value within this loop, it indicates that the number is composite; thus, we set the flag to false, meaning the number is prime at the beginning. If while entering the loop, if divisible then flag is changed to true which means the num is composite. so at last bool function is checked whether it is true or false.
4. WAP to print the factors of a given number
// factor of any number
// factor of 5 : 1,5 -> factor meaning, by which numbers the given number is divisible
// as above, 5 is divisible by 1 and 5. so 1 and 5 are the factors of 5
#include<iostream>
using namespace std;
int main(){
int n;
cin>>n;
int factor;
cout<<"Factors of "<<n<<" is: ";
for(int i = 1; i <= n; i++){
if(n % i == 0){
factor = i;
cout<<factor<<" ";
}
}
}
5. WAP to print the factorials of a given number.
// factorial of any number
// 5! -> 5*4*3*2*1
#include<iostream>
using namespace std;
int main(){
int n;
cin>>n;
int fact = 1;
// we have to start from 1 (not zero) else every factorial will be zero
for(int i = 1; i <= n; i++){
// here condition can also be -> i = n; i >=1; i++ , both are same thing
fact = fact*i;
}
cout<<"Factorial of "<<n<<" is: "<<fact;
}
6. WAP to count the digit of a given number
// counting the digit of number
#include<iostream>
using namespace std;
int main(){
int num;
cout<<"Enter any number: ";
cin>>num;
int count = 0;
do{
num = num/10;
count++;
}while(num!=0);
cout<<"Number of digit: "<<count;
}
If you don’t understand any logic of the program then just leave a comment.