If Else statement किसी भी programming language का सबसे important feature है , C++ If else conditions के according किसी Code Of Block को run करने के लिए use होता है। Means जब हमें Condition True होने पर कोई दूसरा code run करना हो condition गलत होने पर कुछ और तब हम If else का use करते हैं।

c++ if else syntax

if(condition)
{
  // write your logic for true condition
}
else
{
  //write logic if condition false
}

c++ if else example

CopyFullscreenClose FullscreenRun
#include <iostream>
using namespace std;
int main() {
  int age = 30;
  if(age >= 18) {
      cout << "You are eligible to vote";
  }
  else {
      cout << "You are not eligible to vote";
  }
  return 0;
}
Output
You are eligible to vote

तो ऊपर दिए गए example में आप देख सकते हैं की C++ में if else किस तरह से use करते हैं। हालांकि if या else के अंदर single line code ही है तो आप curly brackets {} skip कर सकते हैं।
For Example -

if(age >= 18) 
    cout << "You are eligible to vote";
else
    cout << "You are not eligible to vote";

यह भी same output generate करेगा , लेकिन ध्यान रहे कि , सिर्फ single line ही होनी चाहिए।

c++ if else if

if else if जैसा की नाम से पता चलता है कि अगर upper condition condition false होती है और else if में दी हुयी condition true return करती है तो else if code of block run होगा। हालाँकि if के बाद यह जरूरी नहीं की एक ही else if use हो condition के according एक से ज्यादा भी use हो सकते हैं।

c++ if else if example

CopyFullscreenClose FullscreenRun
#include <iostream>
using namespace std;
int main() {
  int marks = 70;
  if(marks >= 80)
    cout << "Amazing Grade : A";
  else if(marks >= 70)
    cout << "Grade B";
  else if(marks >= 50)
    cout << "Grade C";
  else if (marks >= 33) 
    cout << "Grade D";   
  else 
    cout << "Failed !";
  return 0;
}
Output
Grade B

c++ short hand if else

इन सबके अलावा हम short hand trick भी use में ले सकते हैं जिसे ternary operator कहते हैं , क्योंकि इसमें 3 operands को use किया जाता है। इससे आप multiple lines के code को single line से replace कर सकते हैं। इसे mostly if else की जगह ही use करते हैं।

CopyFullscreenClose FullscreenRun
#include <iostream>
using namespace std;
int main() {
  int age = 30;
  string message = (age >=18) ? "You are eligible to vote" : "You are not eligible to vote";
  cout << message;
  return 0;
}
Output
You are eligible to vote

I Hope, अब C++ में if else / else if के बारे में अच्छे से समझ गए होंगे।

Related Topics :

Rahul Kumar

Rahul Kumar

Hi ! I'm Rahul Kumar Rajput founder of learnhindituts.com. I'm a software developer having more than 4 years of experience. I love to talk about programming as well as writing technical tutorials and blogs that can help to others. I'm here to help you navigate the coding cosmos and turn your ideas into reality, keep coding, keep learning :)

Get connected with me. :) LinkedIn Twitter Instagram Facebook

b2eprogrammers