By Silver
The basic if statement and its use and form.
In this lecture I will explain why and how 'if statements' in the C programming language are used.
The 'if statement' in C, is basically used to decide whether or not a statement is going to be executed or not. This decision depends on various tests. In general, the basic form of the if statement goes as follows:
If(test is true)
{
execute these
statements
}
Where you would use an if statement, and a basic example of its form.
An example of where an if statement would be needed, would be checking whether or not a number is in a certain range. When using if statements, we do not need to use a semi-colon to separate the other lines.
An example of a program that uses if statements would be checking for a specific number range. If the input (whilst the programme is running) is true, then the programme will print the message on the screen. If the input is false, then the program will not print a message on the screen.
An example of this programme would be:
Main()
{
int number;
printf(enter a number between 1 and 10 (1-5 true)\n");
scanf("%d",&number);
if(number>=0 && number<=6)
printf("true \n");
}
In this program, entering a number higher than 5 will result in the program closing, and lower than 5, would result in the message 'true' appearing.
Note the logical operator in this programme, is used for convenience. An alternative programme would be to change the logical operator to: if(number>=1 || number<=6), the same outcome would occur.
The if else statement, what it is used for and how it is laid out.
If in your program you want to run a series of questions using the if statement and you want the program to check each statement before deciding which one to execute and which one to ignore, then 'else' is used. The else will determine which statement is true to the input, and it will execute only the true statement. An example of the else layout is as follows:
If(test is true)
{
Execute these
Statements
}
else
{
execute these
statements
}
Note the use of braces, whilst using this code. A second set of braces is only required if statements after the 'else' take up more than 2 lines. Or, if your using more than one 'if' statement in the program.
The while loop, how it is used and what it is used for.
The 'while' statement lets us repeat a group of statements, until the input is true. The basic structure of the while statement is:
While(operation)
{
execute these
statements
}
In any program running the 'while' loop, it will run over again, providing it is supplied with a positive number, if a wrong number is entered, then the loop will stop running, and the program will end.
The 'do' and 'for' statements, are examples of more loops. They will run the program continuously testing for groups of instructions, to determine whether the program should be repeated or not.
All these statements are used with the 'if' statement in C, but I've just given you basic examples of how and why they are used.