Something about programming

if else switch in C language

Previous tutorial: Data types and variables in C language
Next tutorial: for and while in C programming language

In this tutorial we'll learn what are conditional statements in C: if...else and switch. We already know that processor executes statements one by one from top to bottom. Control statements allow to change this order.

But firstly we need to learn how to get input from keyboard and logical and relational operators.

scanf - input in C

scanf is a function like printf. It allows to get input from keyboard in console in C programming language. In last tutorial we created several variables for our pseudo-game. We initialized them with some initial values. Let's allow the initialization to the users of our program:

int x,y;
char letter;
float fuel;

printf("Input x coordinate of the tank: ");
scanf("%i",&x);
printf("Input y coordinate of the tank: ");
scanf("%i",&y);
printf("Input letter representation of the tank: ");
scanf("%c",&letter);
printf("Input fuel amount of the tank: ");
scanf("%f",&fuel);

As you can see scanf is very similar to printf. It allows to use the same format specifiers. The only difference: we need to put & symbol before variable name. We'll know why it's needed in the following tutorial about pointers in C programming language.

Relational operators in C

As we know all operators in C evaluates to some value. Also we can say they return some value. Like 5+5 is evaluated to 10. There are operators that return only 1 or 0. 1 - if operation is true and 0 - if it is false. 5 < 3 (less than) evaluates to 0 as 5 is not less than 3. Such operators are called relational:

int a=1,b=2;
a > b;  // 0; larger than
a < b;  // 1; less than
a >= b; // 0; larger than or equal
a <= b; // 1; less than or equal
a != b; // 1; not equal
a == b; // 0; equal

Pay attention that for not equal in C is used combination != and for equality ==. You must remember difference between assignment = and equality comparison ==. It's very common error in the beginning to confuse them.

Logical operators in C programming language

Very often we need to combine several relational operators to construct complex condition. For that we need logical operators. Logical operators like relational returns 0 or 1.

! logical NOT. Changes the value to opposite:

int a = 0, b=1;
!a; // 1
!b; // 0
!!a; // 0

&& logical AND. Returns 1 only when both operands evaluates to 1:

int a = 0,b=0,c=1,d=1;
a && b; // 0
a && c; // 0
c && d; // 1

|| logical OR in C. Return 1 when one or both of operands evaluates to 1:

int a = 0,b=0,c=1,d=1;
a || b; // 0
a || c; // 1
c || d; // 1

if in C programming language

if statement allows to execute block of code depending on condition. If condition is true (1), the block will be executed, if it's false (0), the next line after the if block will be executed. Here is the syntax:

if (condition) {
  // block of code
}

Round and curly brackets are mandatory. Let's check example with our tank game. User can input negative values and we want it always equal or larger than zero:

printf("Input x coordinate of the tank: ");
scanf("%i",&x);
printf("Input y coordinate of the tank: ");
scanf("%i",&y);
if (x >= 0 && y >= 0) {
  // x, y are ok
}

We can make different conditions. It depends on our task. Let's print the error message if x or y is negative:

if (x < 0 || y < 0) {
  printf("One (or both) coordinate is negative");
  // do other stuff to solve the problem
}

if...else in C

It's possible to execute another block of code if the condition of if statement is wrong. For this we need to add else block:

if (x >= 0 && y >= 0) {
  // x, y are ok
}
else {
  printf("One (or both) coordinate is negative");
  // do other stuff to solve the problem
}

else belongs to the if statement, you can't use just else, there is if needed before it.

if...else if...else

if statement can have many conditions:

char direction;
printf("Input direction for movement ");
printf("(n - north, w - west, e - east, s - south): ");
scanf("%c",&direction);

if (direction == 'n') {
  // moving north
}
else if (direction == 'e') {
  // moving east
}
else if (direction == 's') {
  // moving south
}
else if (direction == 'w') {
  // moving west
}
else {
  print("Wrong direction!!!");
}

All branches are belong to the same if statement. If first condition is false, next one is checked... If all conditions are false, the else block will be executed.

switch control statement

In the previous example we have 4 possible values for direction. In such cases - when you have small amount of possible values - it's better to use switch conditional statement. Let's rewrite previous example using switch:

char direction;
printf("Input direction for movement ");
printf("(n - north, w - west, e - east, s - south): ");
scanf("%c",&direction);

switch(direction) {
  case 'n':
    // moving north
    break;
  case 'e':
    // moving east
    break;
  case 's':
    // moving south
    break;
  case 'west':
    // moving west
    break;
  default:
    print("Wrong direction!!!");
}

In brackets after keyword switch we put the variable we want to test. Inside switch there are several case blocks. In separate case blocks we check different directions. default block is executed if no case match. Each case block has statement with break. It tells the process to stop checking case blocks below. When processor start executing the switch it checks each case block from top to bottom. If one of the cases match, it's code is executed and last line of each case block is break - it stops the switch and continue executing the code after the switch.

Conclusion

In this tutorial we learn switch and if in C programming language. In next one we'll learn how to work with loops. As result we'll have very powerful tools to make our pseudo-game really cool

Comments:

No comments yet