Skip to main content

The Basics Of C Programming - Part 5.

Conditional statements are used to execute a statement or a group of statement based on certain conditions. In the C programming language, you can typically use the following conditional statements:

1.   if statement
2.   if-else statement
3.   ternary statement or ternary operator
4.   nested if…else statement
5.   switch statement

The syntax of an if statement is:
if(boolean_expression) {
/* statement(s) to execute if the boolean expression is true */
}
If the Boolean expression is true, code inside the if statement is executed. If the Boolean expression is false, then the first set of code after the end of the if statement (after the closing curly brace) is executed.

Example:
#include <stdio.h>
int main ()
{
int a = 10;
if( a < 20 ) {
printf("a is less than 20\n");
}
printf("value of a is %d\n", a);
return 0;
}
Output:
a is less than 20
value of a is 10


The syntax of an if...else statement is:
if(boolean_expression)  {
/* statement(s) to execute if the boolean expression is true */ }
else { 
/* statement(s) to execute if the boolean expression is false */}

If the boolean_expression is true, code inside the if statement is executed; and the else statement is skipped. If the boolean_expression is false, code inside the else statement is executed; and the if statement is skipped.

Example:
#include <stdio.h>
int main ()
{
int a = 100;
if( a < 20 )
{
printf("a is less than 20\n" );
}
else
{
printf("a is not less than 20\n" );
}
printf("value of a is %d\n", a);
return 0;
}
Output:
a is not less than 20
value of a is 100

The if… else if... else statement allows you to check for multiple test expressions and execute different codes for more than two conditions. When using if… else if... else statements, there are few points to keep in mind: (1) An if can have zero or one else's and it must come after any else if's, (2) An if can have zero to many else if's and they must come before the else, and (3) Once an else if succeeds, the remaining else if's or else's will not be tested.

Example:
#include <stdio.h>
int main ()
{
int a = 100;
if( a == 10 )
{
printf("Value of a is 10\n" );
}
else if( a == 20 )
{
printf("Value of a is 20\n" );
}
else if( a == 30 )
{
printf("Value of a is 30\n" );
}
else
{
printf("None of the values is matching.\n" );
}
printf("Exact value of a is %d\n", a );
return 0;
}
Output:
None of the values is matching.
Exact value of a is 100

It is always legal to nest if...else statements, which means you can use one if or else if statement inside another if or else if statement.

Example:
#include <stdio.h>
int main ()
{
int a = 100;
int b = 200;

if( a == 100 )
{
if( b == 200 )
{
printf("Matched!\n" );
}}
printf("The value of a is %d\n", a );
printf("The value of b is %d\n", b );
return 0;
}
Output:
Matched!
The value of a is 100
The value of b is 200

You can nest else if...else in the similar way as you have nested if statements.

Ternary statement or Ternary operator can be used to replace if...else statements. It has the following general form:
exp1 ? exp2 : exp3;
where exp1, exp2, and exp3 are expressions.

Meaning of syntax: The condition in exp1 is evaluated. If it is true, then exp2 becomes the value of the entire expression. If it is false, then exp3 becomes the value of the entire expression.

Example:
#include <stdio.h>
main()
{
int a , b;
a = 10;
printf( "Value of b is %d\n", (a == 1) ? 20: 30 );
printf( "Value of b is %d\n", (a == 10) ? 20: 30 );
}
Output:
Value of b is 30
Value of b is 20

The switch statement allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable being switched on is checked for each switch case. The following rules apply to a switch statement:

The expression used in a switch statement must have an integral or enumerated type, or be of a class type in which the class has a single conversion function to an integral or enumerated type.

You can have any number of case statements within a switch. Each case is followed by the value to be compared to and a colon.

The constant-expression for a case must be the same data type as the variable in the switch, and it must be a constant or a literal.

When the variable being switched on is equal to a case, the statements following that case will execute until a break statement is reached.

When a break statement is reached, the switch terminates, and the flow of control jumps to the next line following the switch statement.

Not every case needs to contain a break. If no break appears, the flow of control will fall through to subsequent cases until a break is reached.

A switch statement can have an optional default case, which must appear at the end of the switch. The default case is used for performing a task when none of the cases is true. No break is needed in the default case.

Example:
#include <stdio.h>
int main ()
{
char grade = 'B';   // local variable definition

switch(grade)
{
case 'A' :
printf("Excellent!\n" );
break;

case 'B' :
case 'C' :
printf("Well done\n" );
break;

case 'D' :
printf("You passed\n" );
break;

case 'F' :
printf("Better try again\n" );
break;

default :
printf("Invalid grade\n" );
}
printf("Your grade is  %c\n", grade );
return 0;
}
Output:
Well done
Your grade is B

It is always legal to nest switch statement i.e. having a switch as a part of the statement sequence of an outer switch. Even if the case constants of the inner and outer switch contain common values, no conflicts will arise.

Example:
#include <stdio.h>
int main ()
{
int a = 100;
int b = 200;

switch(a)
{
case 100:
printf("This is part of outer switch\n", a );

switch(b)
{
case 200:
printf("This is part of inner switch\n", a );
}}
printf("Exact value of a is %d\n", a );
printf("Exact value of b is %d\n", b );
return 0;
}
Output:
This is part of outer switch
This is part of inner switch
Exact value of a is 100
Exact value of b is 200

The goto statement provides an unconditional jump from the 'goto' to a labeled statement in the same function. Note: Use of goto statement is highly discouraged in any programming language because it makes difficult to trace the control flow of a program, making the program hard to understand and hard to modify. Also, it allows you to do bad stuff such as jump out of scope. That being said, goto statement can be useful in some specific cases. For example: to break from nested loops.

Example:
#include<stdio.h>
int main()
{
int a,b;
printf("Enter two numbers A and B: ");
scanf("%d%d",&a,&b);

if(a>b)
{
goto first;
}
else
{
goto second;
}
first:
printf("\nA is greater..");
goto g;

second:
printf("\nB is greater..");
g:
return 0;
}
Output:
Enter two numbers A and B: 20 10
A is greater..

The break statement inside a loop immediately terminates the loop and the program control resumes at the next statement following the loop. If you are using nested loops, the break statement will stop the execution of the innermost loop and start executing the next line of code after the block. The break statement is also used to terminate a case in the switch statement.

Example:  
#include <stdio.h>
int main ()
{
int a = 10;   // local variable definition
while( a < 20 )       //while loop execution
{
printf("value of a: %d\n", a);
a++;

if( a > 15)
{
break;         //terminate the loop using break statement
}}
return 0;

}
Output:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15

The continue statement in C programming works somewhat like the break statement. Instead of forcing termination, it forces the next iteration of the loop to take place, skipping any code in between.

For the for loop, continue statement causes the conditional test and increment portions of the loop to execute. For the while and do...while loops, continue statement causes the program control to pass to the conditional tests.

Example 1:
# include <stdio.h>
int main()
{
int i;
double number, sum = 0.0;

for(i=1; i <= 5; ++i)
{
printf("\nEnter n%d: ",i);
scanf("%lf",&number);

if(number < 0.0)
{
continue;    // If user enters negative number, skip the statement
}
sum += number;   // sum = sum + number;
}
printf("\nSum = %.2lf",sum);
return 0;
}
Output:
Enter n1: 20
Enter n2: 40
Enter n3: -100
Enter n4: 10
Enter n5: 10
Sum = 80.00

Example 2:
#include <stdio.h>
int main ()
{
int a = 10;   // local variable definition
do      // do loop execution
{
if( a == 11)
{
a = a + 1;     // skip the iteration
continue;
}
printf("value of a: %d\n", a);
a++;
}
while( a < 15 );
return 0;
}
Output:
value of a: 10
value of a: 12
value of a: 13
value of a: 14 

Popular posts from this blog

Introduction To Algorithms, 3rd Edition

Before there were computers, there were algorithms. But now that there are computers, there are even more algorithms, and algorithms lie at the heart of computing. This book provides a comprehensive introduction to the modern study of computer algorithms. It presents many algorithms and covers them in considerable depth, yet makes their design and analysis accessible to all levels of readers. In this book, the authors tried to keep explanations elementary without sacrificing depth of coverage or mathematical rigor. Each chapter presents an algorithm, a design technique, an application area, or a related topic. Algorithms are described in English and in a pseudocode designed to be readable by anyone who has done a little programming. The book contains 244 figures — many with multiple parts — illustrating how the algorithms work. It also includes careful analysis of the running times of all algorithms. In this third edition, the entire book once again updated including changes cove...

C Program To Check Whether A Number Is Palindrome Or Not.

This program takes an integer from user and the integer is reversed. If the reversed integer is equal to the integer entered by user then that number is a palindrome. If not that number is not a palindrome.   #include <stdio.h> int main()  { int num, temp, remainder, reverse = 0; printf("Enter an integer: "); scanf("%d", &num); /*  original number is stored at temp */ temp = num; while (num > 0)  { remainder = num % 10; reverse = reverse * 10 + remainder; num /= 10;   }

The Basics Of C Programming - Part 3.

There are a number of different C input commands, the most useful of which is the scanf command. To read a single integer value into the variable called a you can use: scanf("%d",&a); When the program reaches the scanf statement it pauses to give the user time to type something on the keyboard and continues only when users press Enter or Return, to signal that he, or she, has finished entering the value. Then the program continues with the new value stored in a. In this way, each time the program is run the user gets a chance to type in a different value to the variable and the program also gets the chance to produce a different result! The final missing piece in the jigsaw is using the printf function, the one we use to print the value currently being stored in a variable. To display the value stored in the variable a you can use: printf("The value stored in a is %d",a); Note: the scanf function does not prompt for an input. You should ge...

C++ Program To Implement Bank Management System.

#include<iostream> #include<fstream> #include<cctype> #include<iomanip> #include <cstdlib> using namespace std; class account { int acno; char name[50]; int deposit; char type; public: void create_account(); //function to get data from user void show_account() const; //function to show data on screen void modify(); //function to add new data void dep(int); //function to accept amount and add to balance amount void draw(int); //function to accept amount and subtract from balance amount void report() const; //function to show data in tabular format int retacno() const; //function to return account number int retdeposit() const; //function to return balance amount char rettype() const;  //function to return type of account }; void account::create_account() { cout<<"\nEnter The Account No. : "; cin>>acno; cout<<"\n\nEnter The Name Of The Account Holder : "; cin.ig...