Kiran Borge

Mar 16, 2026 • 2 min read

C++ Basic Codes

Basic programming in c++

1. Fibonacci Series

Idea

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;
}

2. Prime Number

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;
}

3. Even and Odd Number

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;
}

4. Palindrome Number

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;
}

5. Sorting Array

Sorting means arranging numbers in order.

Example:

Original Array:
5 2 8 1 3

After 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;
}

Join Kiran on Peerlist!

Join amazing folks like Kiran and thousands of other builders on Peerlist.

peerlist.io/

It’s available... this username is available! 😃

Claim your username before it's too late!

This username is already taken, you’re a little late.😐

0

1

0