C++ for simple programs
Largest of 3 numbers:
Algorithm:
Step 1: Start Step 2: Declare variables a,b and c. Step 3: Read variables a,b and c. Step 4: If a>b If a>c Display a is the largest number. Else Display c is the largest number. Else If b>c Display b is the largest number. Else Display c is the greatest number. Step 5: Stop
CPP program:
#include<iostream>
using namespace std;
class greatest
{
private:
int x,y,z;
public:
void input()
{
cout<<"Enter 3 nos.";
cin>>x>>y>>z;
}
void calc()
{
int r;
r=((x>y)&&(x>z)?x:(y>x)&&(y>z)?y:z);
cout<<"Greatest no:"<<r;
}
};
int main()
{
greatest g;
g.input();
g.calc();
}
OUTPUT ::
Checking the number is prime or not:
algorithm to check whether a number entered by user is prime or not.
Step 1: Start Step 2: Declare variables n,i,flag. Step 3: Initialize variables flag←1 i←2 Step 4: Read n from user. Step 5: Repeat the steps until i<(n/2) 5.1 If remainder of n÷i equals 0 flag←0 Go to step 6 5.2 i←i+1 Step 6: If flag=0 Display n is not prime else Display n is prime Step 7: Stop
Cpp program:
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int num,i,count=0;
cout<<"Enter a number:";
cin>>num;
for(i=2;i<num;i++)
{
if(num%i==0)
{
count++;
break;
}
}
if(count==0)
{
cout<<"This is a prime number";
}
else
{
cout<<"This is not a prime number";
}
getch();
}
Output:
Fibonacci Series Program in C++:
algorithm to print the Fibonacci series.
Step 1: Start Step 2: Declare variables first_term,second_term and temp. Step 3: Initialize variables first_term←0 second_term←1 Step 4: Display first_term and second_term Step 5: Repeat the steps until second_term≤given number 5.1: temp←second_term 5.2: second_term←second_term+first term 5.3: first_term←temp 5.4: Display second_term Step 6: Stop
Program:
#include<iostream.h>
#include<conio.h>
void main()
{
int i,no, first=0, second=1, next;
clrscr();
first=0;
second=1;
cout<<"Enter nubmer of terms for Series: ";
cin>>no;
cout<<"Fibonacci series are: \n";
for(i=0; i<no; i++)
{
cout<<"\n"<<first;
next = first + second;
first = second;
second = next;
}
getch();
}
Output
Enter nubmer of terms for Series: 7 Fibonacci series are: 0 1 1 2 3 5 8
Factorial of given number:
Algorithm to find the factorial of a number entered by user.
Step 1: Start Step 2: Declare variables n,factorial and i. Step 3: Initialize variables factorial←1 i←1 Step 4: Read value of n Step 5: Repeat the steps until i=n 5.1: factorial←factorial*i 5.2: i←i+1 Step 6: Display factorial Step 7: Stop
#include<iostream.h> #include<conio.h> void main() { int i, no, fact=1; clrscr(); cout<<"Enter the any no. : "; cin>>no; for(i=1;i<=no;i++) { fact=fact*i; } cout<<"Factorial: "<<fact; getch(); }
Output
Enter the any no. : 4 Factorial: 24
0 comments:
Post a Comment