Czech version
logolink

< Back to the list of lessons

Conditions - Branching of Program

AlgortimyContent of the lesson:

  • What Is a Condition
  • IF THEN (ELSE) Command Syntax in C language
  • Simple Conditions
  • Complex Conditions, Operators AND and OR
  • Example of Advanced Mathematical Formula

What Is a Condition

In a real life we often encounter conditions – deciding on the basis on some experience; for example:

  • If it is raining, I will take an umbrella.
  • I can only walk across the road when the light is green.
  • I can only walk across the road when the traffic light is green and there is no car around.

In general: When a condition is valid, then ..., otherwise ... Conditions may be of different levels of complexity and quantity – and this complicates the whole system of conditions. But then the whole system can provide solutions even for relatively complex situations.

IF THEN (ELSE) Command Syntax in C

In C (as in many other programming languages) exists the command IF-THEN (ELSE). The syntax of this command should be:

Basic syntax of the IF command in C
if (condition) 
{
	sequence-of-commands
}

If we also want to specify what should happen if the condition is not valid, the command IF-THEN includes the part ELSE which is executed if the condition is not valid.

Syntax of the IF (ELSE) command in C
if (condition) 
{
	sequence-of-commands-1
}
else
{
	sequence-of-commands-2
}

Simple Conditions

Take a look at the following simple example:

IF in C programming language
#include "stdafx.h"

int _tmain(int argc, _TCHAR* argv[])
{
	int a;
	scanf("%d", &a);
	if (a > 5)
	{
		printf("a je vetsi nez 5")
	}
	fflush(stdin);
	getchar();
	return 0;
}

If we want to have more exact information we use the complete IF-ELSE form:

IF-ELSE in C programming language
#include "stdafx.h"

int _tmain(int argc, _TCHAR* argv[])
{
	int a;
	scanf("%d", &a);
	if (a > 5)
	{
		printf("a je vetsi nez 5")
	}
	else
	{
		printf("a je mensi nez 5");
	}
	fflush(stdin);
	getchar();
	return 0;
}

If we want to be even more precise and evaluate both inequality and equality, we have to use nested if or the construction if-else if-else:

IF-ELSE in C programming language
#include "stdafx.h"

int _tmain(int argc, _TCHAR* argv[])
{
	int a;
	scanf("%d", &a);
	if (a > 5)
	{
		printf("a je vetsi nez 5")
	}
	else
	{
		if (a == 5)
		{
			printf("a je rovno 5");
		}
		else
		{
			printf("a je mensi nez 5");
		}
	}
	fflush(stdin);
	getchar();
	return 0;
}

Note: You can also see the "is equal to" operator which is represented by two characters equal to, not only one as for assigning a value.

You can also shorten this syntax using the construction if – else if – else.

IF-ELSE in C programming language
#include "stdafx.h"

int _tmain(int argc, _TCHAR* argv[])
{
	int a;
	scanf("%d", &a);
	if (a > 5)
	{
		printf("a je vetsi nez 5")
	}
	else if (a == 5)
	{
		printf("a je rovno 5");
	}
	else
	{
		printf("a je mensi nez 5");
	}
	fflush(stdin);
	getchar();
	return 0;
}

Complex Conditions, Operators && and ||

If a more complex condition is needed, it can be put together from more conditions using the operators && (meaning of AND) and || (meaning of OR).

Operator &&

The operator && is a parallel to the conjunction "and". If we put together several conditions using AND, then the resultant condition is valid ONLY if EACH condition is valid. In everyday life we use this operator in the following consideration: "When it's raining AND I am out THEN I open my umbrella." or "When it is raining on me AND I have my umbrella THEN I open it." (if ((it is raining of me) && (I have an umbrella)) {I open it}).

An example using the AND operator
#include "stdafx.h"

int _tmain(int argc, _TCHAR* argv[])
{
	int a, b;
	scanf("%d", &a);
	scanf("%d", &b);
	if (a < 0 && b < 0)
	{
		printf("Cisla a a b jsou zaporna!")
	}
	else
	{
		printf("Cisla a a b nejsou obe zaporna!")
	}
	fflush(stdin);
	getchar();
	return 0;
}

Operator ||

The operator || is parallel to the conjunction "or". If we put together several conditions using OR, then the resultant condition is valid when AT LEAST ONE of the conditions is valid (and it is not valid only if none of the conditions is valid). In everyday life we use this operator in the following considerations, for example: "When I am hungry or I like tasty meals, I take something delicious." or "When I want to be a good student or I am bored, I learn something." (if ((I want to be a good student) || (I am bored)) {I learn something}).

An example using the OR operator
#include "stdafx.h"

int _tmain(int argc, _TCHAR* argv[])
{
	int a, b;
	scanf("%d", &a);
	scanf("%d", &b);
	if (a > 0 || b > 0)
	{
		printf("Alespon jedno z cisel a a b je vetsi nez 0!")
	}
	else
	{
		printf("Cisla a a b jsou obe mensi nebo rovna 0!")
	}
	fflush(stdin);
	getchar();
	return 0;
}

Example of Advanced Mathematical Formula

In previous lessons we solved the calculation of simple formulas. Some of them already looked quite complicated. Try to write a program for calculating a simple quotient of two numbers a and b.

Sample: Calculation of the quotient of two arbitrarily given numbers a and b.

A quotient of two numbers in C
#include "stdafx.h"

int _tmain(int argc, _TCHAR* argv[])
{
	int a, b;
	printf("Zadejte cislo a: ");
	scanf("%d", &a);
	printf("Zadejte cislo b: ");
	scanf("%d", &b);
	if (b == 0)
	{
		printf("Deleni nulou je nedefinovaná operace, proto nelze podil zadaných cisel spocitat.");
	}
	else
	{
		printf("Podil zadanych cisel je %d",a/b);
	}
	fflush(stdin);
	getchar();
	return 0;
}

As we know from Math, division by zero is not an allowed operation. If we forget this fact, the program crashes when it tries to divide by zero (which is an unacceptable status). We can see that without the condition IF-THEN it is not possible to handle a simple quotient of any two numbers correctly.

We can complicate the task slightly by the requirement that the previous program should store the quotient of a / b in a variable c. The following solution is the first thing that comes to our minds:

A quotient of two numbers in C
#include "stdafx.h"

int _tmain(int argc, _TCHAR* argv[])
{
	int a, b, c;
	printf("Zadejte cislo a: ");
	scanf("%d", &a);
	printf("Zadejte cislo b: ");
	scanf("%d", &b);
	if (b == 0)
	{
		printf("Deleni nulou je nedefinovaná operace, proto nelze podil zadaných cisel spocitat.");
	}
	else
	{
		c = a / b;
		printf("Podil zadanych cisel je %d",c);
	}
	fflush(stdin);
	getchar();
	return 0;
}

You can face one problem. In case you divided two numbers (for example 5 and 2) you get an integer number (in our case 2). However, you might want to get more accurate result.

The problem is in the data types. The result of division of 2 integer numbers in C is again an integer number (even if you save it into float variable). If you want to get a float number and input integer numbers (for example because of memory), you have to retype one of the values (change its data type for this calculation). This can be done by adding the required data type into brackets before the name of the variable.

The final program is illustrated in the following source code:

A quotient of two numbers in C
#include "stdafx.h"

int _tmain(int argc, _TCHAR* argv[])
{
	int a, b;
	float c;
	printf("Zadejte cislo a: ");
	scanf("%d", &a);
	printf("Zadejte cislo b: ");
	scanf("%d", &b);
	if (b == 0)
	{
		printf("Deleni nulou je nedefinovaná operace, proto nelze podil zadaných cisel spocitat.");
	}
	else
	{
		c = (float)a / b;
		printf("Podil zadanych cisel je %f",c);
	}
	fflush(stdin);
	getchar();
	return 0;
}

Individual Task

Write a program to count the formula X = (A+B) / (C/D). The user assigns the variables A, B, C and D.

Individual Task

Write a program to calculate square root from the given value A.

Questions

  1. How can you branch a program?
  2. What is the right syntax of IF and ELSE conditions? Show more samples.
  3. Is it possible to write more commands after the ELSE command to be executed?
  4. Do the IF or ELSE commands contain any specialty in syntax?
webdesign, xhtml, css, php - Mgr. Michal Mikláš