IF, Else, While & For Loops
Loops
If statements.
If statements allow us to control the flow of our program. Usually, we use if statements when we need to check whether a given condition is true or false, for example:
TRUE ← evaluates to a nonzero number.
FALSE ← evaluates to zero
If syntax.
if (statement is TRUE)
Execute this line of code if TRUE;
}
else{
Execute this line of code if FALSE;
}
The braces indicate a block.
The `else` statement says that whatever code after it is executed, the if statement is FALSE.
Else if.
`else if` statements are helpful when multiple conditional statements may be evaluated as true.
Basic example:
#include <stdio.h>
/**
* main - Entry point
*
* Return: Always 0
*/
int main()
{
int i = 0;
int j = 0;
printf("Enter a number: %d\n", i);
scanf("%d", &i);
printf("Enter a number: %d\n", j);
scanf("%d", &j);
if(i < j){
printf("%d is less than %d\n", i, j);
}
else if(i > j){
printf("%d its greater than %d\n", i, j);
}
else if(i == j){
printf("%d is equal to %d\n", i, j);
}
else{
printf("%d is not less, greater or equal to %d", i, j);
}
}
For loops.
When we know how often the loop should run, we may prefer to use a for loop.
/**
* main - Entry point.
*
* Return: Always 0
*/
int main() {
int i;
/* Return numbers from 1 to 10*/
for (i = 1; i < 11; ++i)
{
printf("%d ", i);
}
return 0;
}
>
1. The initialization statement is executed only once (`i = 1`)
2. The test expression is evaluated (`i < 11`)
3. If the test expression is evaluated as false, the `for` loop will be terminated.
4. If the test expression is evaluated to true, the `for` loop executes, and the update expression (`i < 11`) is updated.
5. The test expression is evaluated till it evaluates to false.
Recommended by LinkedIn
While loop.
When we must repeatedly execute a statement as long as a given condition is true, it is better to use a while loop.
Basic example:
int main(void
{
int i = 10;
while(i < j){
printf("value of i: %d\n", i):
i++;
}
return 0;
}
Do while loop
This loop is guaranteed to execute at least one time.
int main(void
{
int letter = 97;
do {
putchar(letter);
letter++;
} while (letter <= 122);
putchar(10);
return (0);
}
)
Integers.
There are two flavors of integer variables:
Character Variables.
Char is another sort of int,
Usigned data types.
You can find this post in my repository along with if, else, while exercises here:
Learning with alx_africa <3!