You are on page 1of 5

Programming

Fundamental

NOOR- E- AYESHA
submitted to: | Miss Asma Akram
Semester: 01(Regular)
Departement: BSSE
 Write a program in C++ to find a prime number within a range
of 50 by using iterative statements or loops only.

SOLUTION:

#include<iostream>
using namespace std;

int main()
{
for (int num = 2; num <= 50; num++)
{
bool isPrime = true;
for (int i = 2; i < num; i++)
{
if (num % i == 0)
{
bool isPrime = false;
break;
}
}
if (isPrime)
{
cout << num << " ";
}
return 0;
}

 Write a program in simple C++ language to find the sum of the


digits of a given number by user using only loops.

SOLUTION:
#include<iostream>
using namespace std;
main()
{
int n,sum;
sum=0;
cout<<"Enter any number= ";
cin>>n;
while(n!=0)
{
sum=sum+n%10; //add last digit to sum;
n=n/10; //remove last digit from number given;
}
cout<<"Sum of the digits of number is= "<<sum<<endl;
return 0;
}

 Write a program in C++ to display the first n terms of the


Fibonacci series.0 1 1 2 3 5 8 13 21 34 by using loops only.

SOLUTION:

#include<iostream>
using namespace std;
main()
{
int n,t1,t2,next_term;
t1=0;
t2=1;
next_term=0;
cout<<"Enter a number= ";
cin>>n;
cout<<"Fabinocci series is= ";
for(int i=1;i<=n;i++)
{
if(i==1)
{
cout<<t1<<", ";
continue;
}
if(i==2)
{
cout<<t2<<", ";
continue;
}
next_term=t1+t2;
t1=t2;
t2=next_term;
cout<<next_term<<", ";
}
return 0;
}
 Write a program in simple C++ to display the numbers in
reverse order.

SOLUTION:

#include<iostream>
using namespace std;
main()
{
int n;
cout<<"Enter any number= ";
cin>>n;
cout<<"Reversed number is= ";
while(n>0)
{
cout<<n%10; // it prints the last digit.
n=n/10; // it removes the last digit.
}
return 0;
}

 Write a program that display the following output.


1
12
123
1234
12345
SOLUTION:

#include<iostream>
using namespace std;
main()
{
for(int i=1;i<=5;i++)
{
for(int j=1;j<=i;j++)
{
cout<<j;
}
cout<<endl;
}
return 0;
}

 Write a C++ program to check whether a given number


is positive or negative.
SOLUTION:

#include<iostream>
using namespace std;
main()
{
int n;
cout<<"Enter any number= ";
cin>>n;
if(n>0)
cout<<"Number is positive.";
else if(n<0)
cout<<"Number is negative.";
else
cout<<"You entered zero.";
return 0;
}

You might also like