1. Computing & Technology

Discuss in my forum

C Tutorial - Lesson Five - About Control Statements

By , About.com Guide

1 of 5

Control Statements
In this lesson, we'll be covering the major control statements which are for, while, do while,switch and if. With these under your belt, you are well on the way to becoming a seasoned programmer.

The If Statement

Programs need to make decisions. Should this statement be executed or that one? Are these parameters correct and so on. This is done using the if statement. The syntax is pretty easy.
 if ( conditional expression ) 
 statement; 
 
This can be extended with else.
 if ( conditional expression ) 
 statement1; 
 else 
 statement2; 
 
So if the expression is true, statement1 is executed, otherwise statement2 is executed.

Here are some examples:

 if ( a==3 ) 
 b=a; 
 
 if ( b==0 ) 
 { 
 b=1; 
 a += 2; 
 } 
 else 
 { b=0; 
 a=1; 
 } 
 
Be Careful that you don't write = when you mean ==
Can you see the problem with this code?
 if (a=1) 
 { 
 b =9;
 } 
 
This will always set b to 9 as (a=1) is always true. It assigns a value of 1 to a instead of comparing a with 1. The corrected line should be this.
 if (a==1)
 
This is a common mistake amongst beginners.

Conditional Operators

This is a list of the comparisons you can make.
  • == Equal To. if (a == b)
  • < Less than. if (a < b)
  • > Greater than. if (a > b)
  • != Not Equal. if ( a != b)
  • < Less than or equal to. if (a <= b)
  • > Greater than or equal To. if (a >= b)

    On the next page : Learn about the For Loop, the first of the looping statements.

©2012 About.com. All rights reserved.

A part of The New York Times Company.