Difference between while loop and if statement

By : Milon
On : 5:38 PM

The basic structure of while loop is as following

while(condition){
        statement;
      }

The basic structure of if statement is as following

if(condition){
        statement;
      }

So, seeing their structure, it seems that they are same. But no,,, they are not same. if the condition of if is true, the if statement will execute. Otherwise not. Once the condition is true it will execute and will iterate. Where as the while loop will iterate until it get a false or '0'

#include <stdio.h>
int main()
{
    char ch;
    printf("Press any key without N/n to continue the program\n");
    ch = getch();
    while((ch != 'N') && (ch != 'n')){
        printf("\a");
        ch = getch();
    }
    return 0;

}

The above program will not stop till you pressed N or n. As soon as you pressed the N or n the condition will false and the while stop iterating

#include <stdio.h>
int main()
{
    char ch;
    printf("Press n\n");
    ch = getch();
    if(ch == 'n'){
        printf("\a You pressed n\n");
        ch = getch();
    }
    printf("Then you pressed %c\n",ch);
    return 0;

}

To understand better, do as I state, After executing the program, press n, the condition will true, so the statement, You pressed n will show on display. Again press n, that means again the condition is true, but it will not iterate and execute the last statement Then you pressed ...