Important CPP Programs
Important CPP Programs
1. Hello World
#include <iostream>
using namespace std;
int main() {
cout << "Hello, World!";
return 0;
}
#include <iostream>
using namespace std;
int main() {
int a = 5, b = 10, temp;
temp = a;
a = b;
b = temp;
cout << "a = " << a << ", b = " << b;
return 0;
}
3. Even or Odd
#include <iostream>
using namespace std;
int main() {
int num;
cin >> num;
if (num % 2 == 0)
cout << "Even";
else
cout << "Odd";
return 0;
}
#include <iostream>
using namespace std;
int factorial(int n) {
if (n <= 1) return 1;
return n * factorial(n - 1);
}
int main() {
int n;
cin >> n;
cout << "Factorial: " << factorial(n);
Important C++ Programs with Examples
return 0;
}
5. Fibonacci Series
#include <iostream>
using namespace std;
int main() {
int n, t1 = 0, t2 = 1, nextTerm;
cin >> n;
for (int i = 1; i <= n; ++i) {
cout << t1 << " ";
nextTerm = t1 + t2;
t1 = t2;
t2 = nextTerm;
}
return 0;
}
#include <iostream>
using namespace std;
int main() {
int n, i;
bool isPrime = true;
cin >> n;
for(i = 2; i <= n / 2; ++i) {
if(n % i == 0) {
isPrime = false;
break;
}
}
if (isPrime)
cout << "Prime";
else
cout << "Not Prime";
return 0;
}
#include <iostream>
using namespace std;
class Student {
public:
string name;
int age;
void display() {
Important C++ Programs with Examples
cout << "Name: " << name << ", Age: " << age;
}
};
int main() {
Student s1;
s1.name = "John";
s1.age = 20;
s1.display();
return 0;
}
8. File Handling
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ofstream file("sample.txt");
file << "Hello File!";
file.close();
return 0;
}