Follow Techotopia on Twitter

On-line Guides
All Guides
eBook Store
iOS / Android
Linux for Beginners
Office Productivity
Linux Installation
Linux Security
Linux Utilities
Linux Virtualization
Linux Kernel
System/Network Admin
Programming
Scripting Languages
Development Tools
Web Development
GUI Toolkits/Desktop
Databases
Mail Systems
openSolaris
Eclipse Documentation
Techotopia.com
Virtuatopia.com
Answertopia.com

How To Guides
Virtualization
General System Admin
Linux Security
Linux Filesystems
Web Servers
Graphics & Desktop
PC Hardware
Windows
Problem Solutions
Privacy Policy

  




 

 

The GNU C Programming Tutorial - Decisions

Node:Decisions, Next:, Previous:Pointers, Up:Top



Decisions

Testing and Branching. Making conditions.

Until now, our code examples have been linear: control has flowed in one direction from start to finish. In this chapter, we will examine ways to enable code to make decisions and to choose among options. You will learn how to program code that will function in situations similar to the following:

  • If the user hits the jackpot, print a message to say so: You've won!
  • If a bank balance is positive, then print C for "credit"; otherwise, print D for "debit".
  • If the user has typed in one of five choices, then do something that corresponds to the choice, otherwise display an error message.

In the first case there is a simple "do or don't" choice. In the second case, there are two choices. The final case contains several possibilities.

C offers four main ways of coding decisions like the ones above. They are listed below.


if...

if (condition)
{
  do something
}

if...else...

if (condition)
{
  do something
}
else
{
  do something else
}

...?...:...

(condition) ? do something : do something else;

switch

switch (condition)
{
  case first case : do first thing
  case second case : do second thing
  case third case : do third thing
}

 
 
  Published under free license. Design by Interspire