0% found this document useful (0 votes)
40 views5 pages

C++ Loop Problems and Solutions

Uploaded by

2024200000129
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
40 views5 pages

C++ Loop Problems and Solutions

Uploaded by

2024200000129
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

🔹 Basic Loop Problems

1. Print numbers from 1 to N

#include <iostream>
using namespace std;
int main() {
int n;
cout << "Enter N: ";
cin >> n;
for (int i = 1; i <= n; i++) {
cout << i << " ";
}
return 0;
}

2. Sum of first N natural numbers

#include <iostream>
using namespace std;
int main() {
int n, sum = 0;
cout << "Enter N: ";
cin >> n;
for (int i = 1; i <= n; i++) {
sum += i;
}
cout << "Sum = " << sum;
return 0;
}
3. Multiplication Table of a Number

#include <iostream>
using namespace std;
int main() {
int n;
cout << "Enter a number: ";
cin >> n;
for (int i = 1; i <= 10; i++) {
cout << n << " x " << i << " = " << n * i << endl;
}
return 0;
}

🔹 Intermediate Problems
4. Reverse a number

#include <iostream>
using namespace std;
int main() {
int n, rev = 0;
cout << "Enter a number: ";
cin >> n;
while (n > 0) {
int digit = n % 10;
rev = rev * 10 + digit;
n /= 10;
}
cout << "Reversed = " << rev;
return 0;
}
5. Factorial of a number

#include <iostream>
using namespace std;
int main() {
int n, fact = 1;
cout << "Enter a number: ";
cin >> n;
for (int i = 1; i <= n; i++) {
fact *= i;
}
cout << "Factorial = " << fact;
return 0;
}

6. Fibonacci Series

#include <iostream>
using namespace std;
int main() {
int n, a = 0, b = 1;
cout << "Enter number of terms: ";
cin >> n;
cout << a << " " << b << " ";
for (int i = 3; i <= n; i++) {
int c = a + b;
cout << c << " ";
a = b;
b = c;
}
return 0;
}
🔹 Advanced Practice
7. Check if a number is Prime

#include <iostream>
using namespace std;
int main() {
int n;
bool isPrime = true;
cout << "Enter a number: ";
cin >> n;

if (n <= 1) isPrime = false;


for (int i = 2; i <= n / 2; i++) {
if (n % i == 0) {
isPrime = false;
break;
}
}

if (isPrime) cout << "Prime number";


else cout << "Not a prime number";
return 0;
}

8. Print a Triangle Pattern

*
**
***
****
*****

#include <iostream>
using namespace std;
int main() {
int n;
cout << "Enter number of rows: ";
cin >> n;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= i; j++) {
cout << "*";
}
cout << endl;
}
return 0;
}

You might also like