Lesson 4
( Command if )
Hi and welcome back!
In this lesson we are going to talk about very important command and that's if.
We will begin a detailed consideration of the control commands from the command if.
Basic command selection in C is simple command if. The general form of the command if is:
if ( condition )
command
Control expression must be inside of ( ).
In algorithm( picture 1) :
In algorithm( picture 1) :
![]() |
| Picture 1 |
...
If command is there where we asked is value of m less than value of n ( m<n ). The program sequence affect the value of m and n.
In this case, if m<n the program will end and will skip commands ( "print m" "m=n".... ).
Else
By adding "else" to simple command if we are getting basic form of this command.
This form provides choice between two explicit alternative command. If condition is true it will do alternative action otherwise (if condition is true ) it will do action (like in picture 2).
![]() |
| Picture 2 |
if ( condition ) action;
else alternative action;
For command if it says that they are "nested" ( when one if is within another if ).
Example :
instead of writing this:
if( condition 1 )
if( condition 2 )
command
you will write:
* if( condition 1 && condition 2 )
command
*- If one of the condition is false the command will not be executed
You can now play around with if and else commands and learn more about them.
Now i will show you how does that look like in simple program.
Let's say that you have two numbers and you want to see witch one is larger or smaller.
solution :
#include <stdio.h>
int main(){
int num1, num2;
clrscr();
num1=4;
num2=10;
if ( num1<num2) printf( "Number 2 is larger than number 1! ");
else if( num1>num2 ) printf( "Number 1 is larger than number 2! ");
else if( num1==num2 ) printf( "Number 1 is equal to number 2! ");
getch();
}
But what if you want to input your numbers in the program?
Well it's easy, we are just going to use scanf function.
#include <stdio.h>
int main(){
int num1, num2;
clrscr();
printf( "Number 1 = ");
scanf( "%d" , &num1 );
printf( "\nNumber 2 = ");
scanf( "%d" , &num2 );
if ( num1<num2) printf( "Number 2 is larger than number 1! ");
else if( num1>num2 ) printf( "Number 1 is larger than number 2! ");
else if( num1==num2 ) printf( "Number 1 is equal to number 2! ");
getch();
}
Okay that's it for this lesson come back to learn more about C.
I will be posting more lessons about C programming, so follow me, comment if there is something you would change and i will see you next time :) .
If something doesn't work or you need help just email me on: sashans89@gmail.com and i will help you.




Good lesson about programming,good luck Saša!
ReplyDelete