+ 8
If Else If
I’m not exactly sure how to do a proper if else if statement in C programming. I’m also unsure as when to use the curly brackets in the code (I know they’re not always required. This is my first programming language & I’m teaching myself so I apologize for my total ignorance. 😇 If someone could provide a very simple example of an if else if program & kindly walk me through it, I’d really appreciate it. ~Thanks in advance, Cj
16 Respostas
+ 12
The if statement has the same function as other languages.
It has three basic forms:
if( expression )
statement
OR:
if( expression )
statement1
else
statement2
OR:
if( expression )
statement1
else if( expression )
statement2
else
statement3
+ 8
if (condition1) {
// execute if condition1 is true
}
else if (condition2) {
// if condition1 is false, execute if condition2 is true
}
+ 8
if(condition1)
{
Statements; //executes when condition 1 is true
}
else if(condition2)
{
Statements;//executes when condition 2 is true
}
Note that the curly braces{} are not required when there is only one statement in the if-block or else-block,, more than one statement there we require the curly braces..
+ 8
theseigemeister 🐶✨
You are welcome! 😊
+ 7
Thank you Fermi, appreciate it!
+ 7
Thanks a lot Fermi. Very helpful.
+ 5
As for curly brackets, they are not required if only one statement follows the if-else statement.
if (true)
std::cout << "Hello";
If you have multiple statements you want to execute based on the evaluation of condition, then you have to group them together using curly braces.
if (true) {
// statement 1
// statement 2
}
+ 5
Thanks for your response Danijel.
Great community on here! 🌟✨
+ 4
Thank you for the response/information TAL.
+ 4
Thanks for clarifying Sai Kiran.
Appreciate everyone’s feedback.
+ 3
1.We can use curly brackets when there is a code more than one line after if Or else.
2.In all other cases Its is not that much important to use curly brace
Eg:
If(condition1)
{
/* code
* Some printf statements
* Some condition
* Increment or decrement
*/
}
else
If(condition2)
Printf("single line code after if");
else
Printf("single code after else");
+ 1
Based on time & space complexity's Use for loop but its better & recomended to use recursion for a good coder
+ 1
If its based on curly brackets its similar to the above if else form
For nested for loop curly brackets are not required
Eg :
/* in this case we wont need any curly bracket. */
for(int i=0;i<3;i++)
for(int j=0;j<3;j++)
{
scanf("%d",&a[i][j]);
}
0
In Python
0
I also had a doubt on usage of for loops(where to use)
0