Control Flow in C++. If-else, Loops, aur Jump Statements with Examples
Programming ka asli maza tab aata hai jab aap program ka flow control kar paao — matlab kis line ke baad kya chalega, kab chalega, aur kab rukega. Is blog mein hum C++ ke Control Flow statements ko samjhenge.
1. If-Else & Nested If
if-else ka use tab hota hai jab aapko kisi condition ke basis pe decision lena ho.
Simple If-Else Example:
#include<iostream>
using namespace std;
int main(){
int age;
cout << "Enter your Age: ";
cin >> age;
if (age >= 18) {
cout << "You can vote!";
} else {
cout << "Sorry, you can't vote.";
}
return 0;
}
Nested If-Else Example:
#include<iostream>
using namespace std;
int main(){
int marks;
cout << "Marks dijiye: ";
cin >> marks;
if (marks >= 90) {
cout << "Grade: A";
} else if (marks >= 75) {
cout << "Grade: B";
} else if (marks >= 50) {
cout << "Grade: C";
} else {
cout << "Fail ";
}
return 0;
}
2. Switch Case
Jab aapke paas multiple fixed options ho (jaise menu system), tab switch
use hota hai.
Switch Example:
#include<iostream>
using namespace std;
int main(){
int choice;
cout << "1. Tea\n2. Coffee\n3. Juice\nEnter your choice: ";
cin >> choice;
switch(choice) {
case 1:
cout << "You selected Tea.";
break;
case 2:
cout << "You selected Coffee.";
break;
case 3:
cout << "You selected Juice.";
break;
default:
cout << "Invalid choice!";
}
return 0;
}
3. Loops in C++
Loops ka use repeat karne ke liye hota hai — jab tak condition true hai, loop chalta hai.
For Loop:
for (int i = 1; i <= 5; i++) {
cout << "Hello " << i << endl;
}
While Loop:
int i = 1;
while (i <= 5) {
cout << "While loop: " << i << endl;
i++;
}
Do-While Loop:
int i = 1;
do {
cout << "Do-While loop: " << i << endl;
i++;
} while (i <= 5);
4. break, continue, goto
break
: loop ko turant rok deta hai.
Example:
for (int i = 1; i <= 10; i++) {
if (i == 5) {
break; // loop yahin ruk jayega
}
cout << i << " ";
}
// Output: 1 2 3 4
continue
: current iteration skip karta hai.
Example:
for (int i = 1; i <= 5; i++) {
if (i == 3) {
continue; // 3 skip hoga
}
cout << i << " ";
}
// Output: 1 2 4 5
goto
: directly jump karta hai kisi label par (rarely used)
Example:
int n;
cout << "Enter a number: ";
cin >> n;
if (n < 0)
goto negative;
cout << "Number is positive.";
return 0;
negative:
cout << "Negative number entered!";
Comments