1. Home
  2. Computing & Technology
  3. C / C++ / C#

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.

Explore C / C++ / C#
About.com Special Features

Holiday Central

What to eat, where to go, fun things to do and how to save money on the perfect gifts. More >

Family Tech Center

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

  1. Home
  2. Computing & Technology
  3. C / C++ / C#
  4. C
  5. C Tutorials
  6. C Tutorial - Lesson Five - About Control Statements>

©2009 About.com, a part of The New York Times Company.

All rights reserved.