You are here:About>Computing & Technology>C / C++ / C#> C> C Tutorials> C Tutorial - Lesson Five - About Control Statements
About.comC / C++ / C#

C Tutorial - Lesson Five - About Control Statements

From David Bolton,
Your Guide to C / C++ / C#.
FREE Newsletter. Sign Up Now!

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.

  1. Control Statements
  2. The For Loop
  3. Break and Continue
  4. While and Do While
  5. About Switch Statements

Previous | Next >>

 All Topics | Email Article | Print this Page | |
Advertising Info | News & Events | Work at About | SiteMap | Reprints | HelpOur Story | Be a Guide
User Agreement | Ethics Policy | Patent Info. | Privacy Policy©2008 About, Inc., A part of The New York Times Company. All rights reserved.