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

Screenshots from Windows 1.01

Windows 1.0 is a graphical personal computer operating environment developed by Microsoft, released on November 20, 1985, as the first version of the Microsoft Windows line. Version 1.01 , also released in 1985, was the first point-release after Windows 1.00.   Screenshots from Windows 1.01: ⇰ Desktop  First Run Empty Desktop Desktop With Applications ⇰  Office Applications Notepad Text Editor Calculator Calendar Clock Address Book ⇰  Multimedia Applications Media player, CD player, Volume level, and Sound: This GUI doesn’t have these features. ⇰  Networking Applications Terminal Phone Dialer: This GUI doesn’t have this feature. ⇰  Internet Applications Browser, and Mail: This GUI doesn’t have these features. ⇰  Accessibility Applications Keyboard Map:  This GUI doesn’t have this feature. ⇰  Settings Desktop themes,  Display,  Screensaver,  Keyboard, Mouse,  Accessibility,  Power M

Java: The Complete Reference, 9th Edition

This is Herb's most popular book on Java, fully updated and expanded to cover Java SE 8 (JDK 8).    Whether you're an experienced pro or just starting out, this one-stop guide will help you master this important language.  Inside you'll find comprehensive coverage of the Java language, its keywords, syntax, and fundamental programming principles.  Of course, descriptions of Java's newest features, such as lambda expressions, default interface methods, and the stream API are included. This lasting resource also describes key elements of the Java API library, such as the Collections Framework, concurrency, applets, servlets, Beans, event handling,  AWT,  Swing, and more. Coverage of JavaFX, Java's newest GUI framework, is also included. *** TO REVIEW BOOK ***  (click below) *** TO REVIEW SOURCE CODE PROBLEM  SOLUTIONS, VISIT   THIS   LINK ***

C++ Program To Implement Casino Number Guessing Game.

#include <iostream> #include <string> #include <cstdlib> #include <ctime> using namespace std; void drawLine(int n, char symbol); void rules(); int main() { string playerName; int amount; int bettingAmount; int guess; int dice; char choice; srand(time(0)); drawLine(70,'_'); cout << "\n\n\n\t\tCASINO GAME\n\n\n\n"; drawLine(70,'_'); cout << "\n\nEnter Your Name : "; getline(cin, playerName); cout << "\n\nEnter Deposit Amount To Play Game : $"; cin >> amount;

Java: A Beginner's Guide, 6th Edition

This is Herb's step-by-step introduction to Java, updated for Java SE 8 (JDK 8). If you are just learning Java, then this is the book for you.  It starts at the beginning, explaining the history of Java, why it's important to the Web, and how it relates to the world of programming at large.  You then learn how to obtain the Java Development Kit (JDK) and write your first Java program. Next, it's on to the Java fundamentals, including data types, operators, control statements, classes, objects, and methods.  You'll then progress to more advanced topics, such as inheritance, exception handling, the I/O system, multithreading,  applets, and lambda expressions. Also included is coverage of some of Java's most powerful features, such as generics, autoboxing, enumerations, and static import.  An introduction to JavaFX, Java's newest GUI framework, is also included. *** TO REVIEW BOOK *** (click below) *** TO REVIEW SOURCE CODE PROBLEM  SOLUTIO

The C Programming Language, 2nd Edition*

This book is meant to help the reader learn how to program in C. It is the definitive reference guide, now in a second edition. Although the first edition was written in 1978, it continues to be a worldwide best-seller. This second edition brings the classic original up to date to include the ANSI standard. For evolution of the planet earth and our modern understanding of biology, there was Darwin's Origin of the Species. For mathematics, there was Newton's PhilosophiƦ Naturalis Principia Mathematica. Well, for the internet, for Facebook, for LinkedIn, Twitter, Instgram, Snapchat, WhatsApp, Pornhub and even the odious website for Justin Bieber would never have existed without Kernigan and Ritchie (more affectionately known as K&R)'s classic, The C Programming Language. What language was TCP/IP written in? C. What language inspired both C++ and Java (and the abominable C#)? C. What language are most libraries on most operating systems written in if not assembler? C.