Code Scrappers

TOPIC 7: Control Statements

A program comprises of a number of statements that are usually executed in sequence.Programs can be made much more powerful if we can control the order in which statements are run.
Statements fall into three general categories:

If Statements

The keyword if basically tells the compiler that it is a decision control instruction. The if statement allows us to add some decision-making into our programs.

Syntax :

  if (condition )

   {
      Statement...;

      …………..

      Statement...;

   } 


NOTE 1:If the condition is true(nonzero), the statement will be executed.If the condition turns out to be false(0), the statement will not be executed.

For Example :

 if (marks>=90)
  {

    printf("You have scored A+ grade\n");

  }

NOTE 2:For readability, the statements enclosed in { } are usually indented.

NOTE 3:This allows the programmer to quickly tell which statements are to be conditionally executed.

C Programs using if statements

1. Write a program to print a message if negative number is entered.

#include<stdio.h>

void main()

{

 int number;

 printf("Enter the number : \n");

 scanf("%d", &number);

if(number<0)

{
    printf("The number is negative\n");
    number = -number;
}

printf("The number is %d\n",number);


}

Output: Enter the number: 6
The number is 6

Output: Enter the number: -2
The number is negative
The number is -2

2. Write a program to perform division of 2 numbers

#include<stdio.h>

void main()

{
  int num1,num2;

  float num3;

  printf("Enter 1st number : ");

  scanf("%d", &num1);

  printf("Enter 2nd number : ");

  scanf("%d", &num2);

if(num2 == 0)

     {
           printf("Error!Division cannot be performed\n");
           exit(0);

     }

num3 = num1/num2;

printf("Quotient after division is %f \n",num3);

}

Output: Enter 1st number :
6
Enter 2nd number :
2
Quotient after division is 3


<< Back Next >>