So far we had come to know about basic concepts of C. Today we will start learning about C weapon logy-- C control statements.
Control Statements
- Conditional statements (if,if/else,else if, switch)
- Looping(for, while, do while)
- Labels (Goto) etc
If(<condition>){ //some code will run when the condition is true }else { //another code block will run when the if <condition> is false }
if(100){ printf("In if statement block.\n");//this code will always run, } if(-10000) printf("This printf will run because the condition is non zero.\n"); if(5>10) printf("This will not run"); printf("\nThis will always run.");
#include<stdio.h> #include<conio.h> void main(){ int a = 10; if(a == 10){ printf("A is 10"); } getch(); }
See the above program has an if statement or block, notice carefully the condition was ‘a == 10’. There is a ‘==’ operator, whenever we want some comparison there must be a ‘==’ operator in if condition. We can extend this program as using else statement with the if block.
#include<stdio.h> #include<conio.h> void main(){ int a = 10; if(a == 10){ printf("A is 10"); }else { printf("A is not 10"); } getch(); }
Notice that we used else statement at immediate after the if statement, otherwise compiler will throw an error. We cant use the else without the preceding if.
- Input year
- Check the year has a reminder after the operation year%4
- Show the output
//this will wait for a real number is pressed, for simplicity we assume the user will input a legal year(an integer variable) scanf(“%d”,&year);
if(year%4 == 0){ printf("The year %d is a leap year",year); } else { printf("The year %d is not a leap year",year); }
if(year<0){ printf("%d is not a valid year. Program will terminate now.",year); }else { if(year%4 == 0){ printf("The year %d is a leap year",year); } else { printf("The year %d is not a leap year",year); } }
If(<condition>){ If(<some other condition>){ //some other codes if the <some other condition> is true }else { //else some other codes } }else { //code will execute if the <condition> is false }
#include<stdio.h> #include<conio.h> void main(){ int a = 10, b = 20 , c = 5; if(a>b){ if(a>c){ printf("a(%d) is the biggest among-st %d %d %d ",a,a,b,c); }else { printf("c(%d) is the biggest among-st %d %d %d ",c,a,b,c); } }else { if(b>c){ printf("b(%d) is the biggest among-st %d %d %d ",b,a,b,c); }else { printf("c(%d) is the biggest among-st %d %d %d ",c,a,b,c); } } getch(); }
So this program is able to find out the biggest number among three numbers. But we some time need this process done among thousands of numbers! How? We will see this in the next part.
Tasks
- Input a number and find out the number is even or odd.
- Input two numbers and make a swap program(interchanging the value of two variables)
- Test various exceptions, Check the errors occur for misplacing the if and else block in a program, Check for a number bigger than the range of integer
- What will happen when a user inputs a character for the leap year program?