Basic programming in c++
Each number = sum of previous two numbers
0 1 1 2 3 5 8 13#include <iostream>
using namespace std;
int main()
{
int num;
int a=0, b=1, c;
cout << "Enter Number: ";
cin >> num;
for(int i=1; i<=num; i++)
{
cout << a << " ";
c = a + b;
a = b;
b = c;
}
return 0;
}A prime number is divisible only by:
1 and itself // 2 3 5 7 11#include <iostream>
using namespace std;
int main()
{
int num = 5;
int count = 0;
for(int i=1;i<=5;i++)
{
if(num % i == 0)
{
count++;
// If num is divisible by i, increase count by 1.
// count++ means count = count + 1.
}
}
if(count == 2)
{
cout << "Prime Number";
}
else{
cout << "Not Prime";
}
return 0;
}Even → divisible by 2
Odd → not divisible by 2#include <iostream>
using namespace std;
int main()
{
int num = 10;
if(num % 2 == 0)
cout << "Even Number";
else
cout << "Odd Number";
return 0;
}Palindrome means same forward and backward
Example:
121
1331#include <iostream>
using namespace std;
int main()
{
int num = 121;
int rem, rev = 0, temp;
temp = num; // we stored original no -Because we will change num.
while(num > 0)
{
rem = num % 10; // Get Last Digit
rev = rev * 10 + rem; // Reverse Number
num = num / 10; // Remove Last Digit
}
if(temp == rev) // Compare Numbers
cout << "Palindrome";
else
cout << "Not Palindrome";
return 0;
}Sorting means arranging numbers in order.
Example:
Original Array:
5 2 8 1 3After sorting (ascending):
1 2 3 5 8// arr[10] = {5,24,556,54,14,52,0,63,2,98}
#include <iostream>
using namespace std;
int main()
{
int arr[10] = {5,24,556,54,14,52,0,63,2,98};
for(int i=1; i<=10; i++) // This loop selects each element one by one.
{
for(int j=i+1; j<10; j++) // This loop compares the selected number with the remaining numbers.
{
if(arr[i]> arr[j]) // Compare Numbers 5 > 2 → true
{
int temp = arr[i]; // Swap Numbers
arr[i] = arr[j];
arr[j] = temp;
}
}
}
for(int i=1; i<=10; i++)
{
cout << arr[i] << " ";
}
return 0;
}0
1
0