Skip to main content

Control flow

if-else

src/c/basics/03-if-else.c
#include <stdio.h>

int main()
{
int age = 0;

printf("Please enter your age in years: ");
scanf("%d", &age);

if (age <= 18)
printf("You are not an adult.\n");
else if (age < 65)
printf("You are an adult.\n");
else
printf("You are a senior citizen.\n");

return 0;
}

switch

src/c/basics/03-switch.c
#include <stdio.h>

int main()
{
int age = 0, category;

printf("Please enter your age in years: ");
scanf("%d", &age);

if (age < 0)
category = 0;
else if (age <= 18)
category = 1;
else if (age < 65)
category = 2;
else
category = 3;

switch (category)
{
case 0:
printf("Invalid age.\n");
break;
case 1:
printf("You are not an adult.\n");
break;
case 2:
printf("You are an adult.\n");
break;
case 3:
printf("You are a senior citizen.\n");
break;

default:
printf("Should not be necessary here.\n");
break;
}

return 0;
}

Ternary operator

src/c/basics/03-ternary.c
#include <stdio.h>

int main()
{
int input1, input2, big;
printf("Enter two integer numbers (separated by space): ");
scanf("%d%d", &input1, &input2);

big = (input1 > input2) ? input1 : input2;

printf("Biggest number = %d\n", big);
return 0;
}