C / C++ Courses ? 6 (Conditions – If Statements)
They are used to compare some values and operate according to result.
The result can be true or false.
- If the condition is true, it operates everything in if statement.
- If the condition is false, it skips whole if statements and continue.
We can build conditional statements in two forms:
1-for multiple lines of operations;
if(condition){
statement 1;
statement 2;
…
}
2-for single line;
if (condition)
statement;
We can write paranthesis, but no need for this for single line.
*For building conditions, we use 2 types of operators:
1)Relational Operators
<, <=, >, >=
2)Equality Operators
==, !=
Ex; Write a program that allows the user to enter an integer. The program will print if the integer is positive or negative.
#include<stdio.h>
int main(){
int num;
printf("Enter an integer: ");
scanf("%d",&num);
if(num>0)
printf("%d is positive.",num);
if(num<0)
printf("%d is negative.",num);
return 0;
}
Output will be like that: (Bold ones are entered by the user)
Enter an integer: 78
78 is positive.
or if we enter negative number:
Enter an integer: -11
-11 is negative.
Ex; Write a program that allows the user to enter 2 integers. The program will print largest of them or they are equal.
#include<stdio.h>
int main(){
int num1,num2;
printf("Enter 2 integers: ");
scanf("%d%d",&num1,&num2);
if(num1>num2)
printf("%d is largest.",num1);
if(num2>num1)
printf("%d is largest.",num2);
if(num1==num2)
printf("They are equal to each other.");
return 0;
}
!!Pay Attention!!
“==” is equality operator.It’s used for comparing.
“=” is assignment operator. It’s used for assigning.
If we write
if (x=5){
…
}
this will be always true. It will make x’s value 5 and result will be always true. Don’t forget!
»Extra:If we write like below, it will print sth or not?
if ( 1 ){
printf(“Yes, this is true”);
}
Answer is in the following lesson😉
?Answer of previous lesson’s extra:
int x,y;
x=5;
y=4;
float av= (x+y) / 2;
av=9/2; // they have the same type, both of them are integer. Then result must be integer. Then;
av=4;
c ya ! 🙂
[…] ?Answer of previous lesson’s extra: […]
Yoruma Açığız! :)