Q1. Write a program to print "Hello, World!
"
Code:
#include <iostream>
using namespace std;
int main() {
cout << "Hello, World!";
return 0;
}
Output:
Hello, World!
---
Q2. Write a program to add two numbers.
Code:
#include <iostream>
using namespace std;
int main() {
int a = 5, b = 3;
int sum = a + b;
cout << "Sum: " << sum;
return 0;
}
Output:
Sum: 8
---
Q3. Write a program to swap two numbers using a temporary variable.
Code:
#include <iostream>
using namespace std;
int main() {
int x = 10, y = 20, temp;
temp = x;
x = y;
y = temp;
cout << "x = " << x << ", y = " << y;
return 0;
}
Output:
x = 20, y = 10
---
Q4. Write a program to check whether a number is even or odd.
Code:
#include <iostream>
using namespace std;
int main() {
int num = 7;
if (num % 2 == 0)
cout << "Even";
else
cout << "Odd";
return 0;
}
Output:
Odd
---
Q5. Write a program to find the maximum of two numbers.
Code:
#include <iostream>
using namespace std;
int main() {
int a = 12, b = 8;
if (a > b)
cout << a << " is greater";
else
cout << b << " is greater";
return 0;
}
Output:
12 is greater
---
Q6. Write a program to build a simple calculator using switch-case.
Code:
#include <iostream>
using namespace std;
int main() {
char op = '+';
int a = 10, b = 5;
switch(op) {
case '+': cout << "Sum = " << a + b; break;
case '-': cout << "Difference = " << a - b; break;
case '*': cout << "Product = " << a * b; break;
case '/': cout << "Quotient = " << a / b; break;
default: cout << "Invalid operator";
}
return 0;
}
Output:
Sum = 15
---
Q7. Write a program to print numbers from 1 to 10 using a loop.
Code:
#include <iostream>
using namespace std;
int main() {
for(int i = 1; i <= 10; i++) {
cout << i << " ";
}
return 0;
}
Output:
1 2 3 4 5 6 7 8 9 10
---
Q8. Write a program to find the sum of first n natural numbers.
Code:
#include <iostream>
using namespace std;
int main() {
int n = 5, sum = 0;
for (int i = 1; i <= n; i++) {
sum += i;
}
cout << "Sum = " << sum;
return 0;
}
Output:
Sum = 15
---
Q9. Write a program to calculate the factorial of a number.
Code:
#include <iostream>
using namespace std;
int main() {
int n = 5;
long long fact = 1;
for (int i = 1; i <= n; i++) {
fact *= i;
}
cout << "Factorial = " << fact;
return 0;
}
Output:
Factorial = 120
---
Q10. Write a program to print the first 5 terms of Fibonacci series.
Code:
#include <iostream>
using namespace std;
int main() {
int n = 5, a = 0, b = 1;
cout << a << " " << b << " ";
for (int i = 2; i < n; i++) {
int next = a + b;
cout << next << " ";
a = b;
b = next;
}
return 0;
}
Output:
01123