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?
#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;
}
#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;
}
Increasing indentation doesn't mean decrease readability. If you have a very long if-condition, it will decrease indentation, but also decrease readability. You should use the only way that allows you to keep your code clean and as simple as possible. Efficiency of code is also necessary since you are talking about C. Logical operators helps to combine two or more if-conditions in one and sometimes it really improve readability, sometimes - not. Sometimes, nested-ifs are better choice, you should think about your situation and choose the best way.
As stated by other commenters, your instructor is wrong and code has logical errors.