I am new to Programming and currently learning C, so I don't know much about this concept but I was learning Conditional Instructions and at that time, my instructor [I am learning online from YouTube] explained me about logical operators.
He explained that logical operators are used with if...else to decrease the indentation and increase the readability.
After some time, I was solving a problem to find the greatest of four numbers and here, he contradicted the theory. He described nested if to solve this question instead of using logical operators.
Now; I am confused, what approach should I go with and why?
Also; when should I use arithmetic instructions and when should I use nested if...else?
Code written by me:
#include <stdio.h>
int main()
{
int number1, number2, number3, number4;
printf("\nEnter the vlaue of number1: ");
scanf("%d", &number1);
printf("\nEnter the value of number2: ");
scanf("%d", &number2);
printf("\nEnter the value of number3: ");
scanf("%d", &number3);
printf("\nEnter the value of number4: ");
scanf("%d", &number4);
if(number1 > number2 && number1 > number3 && number1 > number4)
{
printf("\n%d is the greatest of four numbers.\n", number1);
}
else if(number2 > number3 && number2 > number4)
{
printf("\n%d is the greatest of four numbers.\n", number2);
}
else if(number3 > number4)
{
printf("\n%d is the greatest of four numbers.\n", number3);
}
else
{
printf("\n%d is the greatest of four numbers.\n", number4);
}
return 0;
}
Code written by my instructor:
#include <stdio.h>
int main()
{
int number1, number2, number3, number4;
printf("\nEnter the vlaue of number1: ");
scanf("%d", &number1);
printf("\nEnter the value of number2: ");
scanf("%d", &number2);
printf("\nEnter the value of number3: ");
scanf("%d", &number3);
printf("\nEnter the value of number4: ");
scanf("%d", &number4);
if(number1 > number2)
{
if(number1 >number3)
{
if(number1 > number4)
{
printf("\n%d is the greatest of four numbers.\n", number1);
}
}
}
else if(number2 > number3)
{
if(number2 > number4)
{
printf("\n%d is the greatest of four numbers.\n", number2);
}
}
else if(number3 > number4)
{
printf("\n%d is the greatest of four numbers.\n", number3);
}
else
{
printf("\n%d is the greatest of four numbers.\n", number4);
}
return 0;
}