Skip to main content

Conditional Execution in c

Objectives:

Having read this section you should be able to:

1.Program control with if , if-else and switch structures
2.have a better idea of what C understands as true and false.


Program Control:

It is time to turn our attention to a different problem - conditional execution. We often need to be able to choose which set of instructions are obeyed according to a condition. For
example, if you're keeping a total and you need to display the message 'OK' if the value is greater than zero you would need to write something like:

if (total>O) printf("OK");

This is perfectly reasonable English, if somewhat terse, but it is also perfectly good C. The if statement allows you to evaluate a >condition and only carry out the statement, or compound
statement, that follows if the condition is true. In other words the printf will only be obeyed if the condition total > O is true.

If the condition is false then the program continues with the next instruction. In general the if statement is of the following form:

if (condition) statement;

and of course the statement can be a compound statement.

Here's an example program using two if statements:



#include

main()
{
int a , b;

do {

printf("\nEnter first number: ");
scanf("%d" , &a);

printf("\nEnter second number: ");
scanf("%d" , &b);

if (a if (b
} while (a < 999);
}

Here's another program using an if keyword and a compound statement or a block:

#include

main()
{
int a , b;

do {

printf("\nEnter first number: ");
scanf("%d" , &a);

printf("\nEnter second number: ");
scanf("%d" , &b);

if (a printf("\n\nFirst number is less than second\n");
printf("Their difference is : %d\n" , b-a);

printf("\n");
}

printf("\n");

} while (a < 999);
}

The if statement lets you execute or skip an instruction depending on the value of the condition. Another possibility is that you might want to select one of two possible statements - one
to be obeyed when the condition is true and one to be obeyed when the condition is false. You can do this using the


if (condition) statement1;
else statement2;

form of the if statement.

In this case statement1 is carried out if the condition is true and statement2 if the condition is false.

Notice that it is certain that one of the two statements will be obeyed because the condition has to be either true or false! You may be puzzled by the semicolon at the end of the if part
of the statement. The if (condition) statement1 part is one statement and the else statement2 part behaves like a second separate statement, so there has to be semi-colon
terminating the first statement.

Logical Expressions:

So far we have assumed that the way to write the conditions used in loops and if statements is so obvious that we don't need to look more closely. In fact there are a number of
deviations from what you might expect. To compare two values you can use the standard symbols:

> (greater than)

< (less than)

>= (for greater than or equal to )
<= (for less than or equal to)
== (to test for equality).

The reason for using two equal signs for equality is that the single equals sign always means store a value in a variable - i.e. it is the assignment operator. This causes beginners lots of

problems because they tend to write:

if (a = 10) instead of if (a == 10)

The situation is made worse by the fact that the statement if (a = 10) is legal and causes no compiler error messages! It may even appear to work at first because, due to a logical quirk
of C, the assignment actually evaluates to the value being assigned and a non-zero value is treated as true (see below). Confused? I agree it is confusing, but it gets easier. . .

Just as the equals condition is written differently from what you might expect so the non-equals sign looks a little odd. You write not equals as !=. For example:

if (a != 0)

is 'if a is not equal to zero'.

An example program showing the if else construction now follows:


#include

main ()
{
int num1, num2;

printf("\nEnter first number ");
scanf("%d",&num1);

printf("\nEnter second number ");
scanf("%d",&num2);

if (num2 ==0) printf("\n\nCannot devide by zero\n\n");
else printf("\n\nAnswer is %d\n\n",num1/num2);
}

This program uses an if and else statement to prevent division by 0 from occurring.

True and False in C:

Now we come to an advanced trick which you do need to know about, but if it only confuses you, come back to this bit later. Most experienced C programmers would wince at the
expression if(a!=0).

The reason is that in the C programming language dosen't have a concept of a Boolean variable, i.e. a type class that can be either true or false. Why bother when we can use numerical
values. In C true is represented by any numeric value not equal to 0 and false is represented by 0. This fact is usually well hidden and can be ignored, but it does allow you to write

if(a != 0) just as if(a)

because if a isn't zero then this also acts as the value true. It is debatable if this sort of shortcut is worth the three characters it saves. Reading something like

if(!done)

as 'if not done' is clear, but if(!total) is more dubious.


Using break and continue Within Loops:

The break statement allows you to exit a loop from any point within its body, bypassing its normal termination expression. When the break statement is encountered inside a loop, the loop

is imediately terminated, and program control resumes at the next statement following the loop. The break statement can be used with all three of C's loops. You can have as many
statements within a loop as you desire. It is generally best to use the break for special purposes, not as your normal loop exit. break is also used in conjunction with functions and >case
statements which will be covered in later sections.

The continue statement is somewhat the opposite of the break statement. It forces the next iteration of the loop to take place, skipping any code in between itself and the test condition of

the loop. In while and do-while loops, a continue statement will cause control to go directly to the test condition and then continue the looping process. In the case of the for loop, the
increment part of the loop continues. One good use of continue is to restart a statement sequence when an error occurs.


#include

main()
{
int x ;

for ( x=0 ; x<=100 ; x++) {
if (x%2) continue;
printf("%d\n" , x);

}
}


Here we have used C's modulus operator: %. A expression:

a % b

produces the remainder when a is divided by b; and zero when there is no remainder.

Here's an example of a use for the break statement:


#include

main()
{
int t ;

for ( ; ; ) {
scanf("%d" , &t) ;
if ( t==10 ) break ;
}
printf("End of an infinite loop...\n");

}


Select Paths with switch:

While if is good for choosing between two alternatives, it quickly becomes cumbersome when several alternatives are needed. C's solution to this problem is the switch statement. The
switch statement is C's multiple selection statement. It is used to select one of several alternative paths in program execution and works like this: A variable is successively tested against a
list of integer or character constants. When a match is found, the statement sequence associated with the match is executed. The general form of the switch statement is:

switch(expression)
{
case constant1: statement sequence; break;
case constant2: statement sequence; break;
case constant3: statement sequence; break;
.
.
.
default: statement sequence; break;
}


Each case is labelled by one, or more, constant expressions (or integer-valued constants). The default statement sequence is performed if no matches are found. The default is optional.
If all matches fail and default is absent, no action takes place.

When a match is found, the statement sequence asociated with that case are executed until break is encountered.

An example program follows:


#include

main()
{
int i;

printf("Enter a number between 1 and 4");
scanf("%d",&i);

switch (i)
{
case 1:
printf("one");
break;
case 2:
printf("two");
break;
case 3:
printf("three");
break;
case 4:
printf("four");
break;

default:
printf("unrecognized number");
} /* end of switch */

}

This simple program recognizes the numbers 1 to 4 and prints the name of the one you enter. The switch statement differs from if, in that switch can only test for equality, whereas the if
conditional expression can be of any type. Also switch will work with only int and char types. You cannot for example, use floating-point numbers. If the statement sequence includes
more than one statement they will have to be enclosed with {} to form a compound statement.

Comments

Popular posts from this blog

13 websites to register your free domain

Register your Free Domain Now!! 1)  .tk Dot TK is a FREE domain registry for websites on the Internet. It has exactly the same power as other domain extensions, but it’s free! Because it’s free, millions of others have been using .TK domains since 2001 – which makes .TK powerful and very recognizable.  Your website will be like www.yourdomainname.tk . It is free for 1 year. It’s a ccTLD domain whixh having the abbreviation  Tokelau. To create a .tk domain, Visit   www.dot.tk 2) co.cc Co.cc is completely free domain which is mostly used by blogspot bloggers because of it’s easy to use DNS system. Creating a co.cc for blogger is simple ( for instructions- “click here”). Your website will be like www.yourdomainname.co.cc . To create a .co.cc domain, visit www.co.cc 3)   co.nr co.nr is too like co.cc. Your website will be like  www.yourdomainname.co.nr . You can add it for blogger also.. To create a .co.cc domain, vi...

Binary Search Tree in C++( dynamic memory based )

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 #include<bits/stdc++.h> using namespace std; struct bst { int val; bst * left, * right; }; bst * root = nullptr; void srch ( int num,bst * head) { if (head == nullptr){ cout << " \n Number is not present \a " << endl; return ; } if (head -> val == num) { cout << " \n Number is present \n\a " ; return ; } else { if (num < head -> val) srch(num,head -> left); else srch(num,head -> right); ...

Binary Search Tree in Java implementation (reference based, dynamic memory)

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 import java.util.Scanner ; class BST { static BST . Node root = null ; public void insert ( int num ) { if ( root == null ) { root = new BST . Node ( num ); } else { // root node is not empty BST . Node temp = root ; while ( temp != null ) { if ( num <= temp . getVal ()) { if ( temp . getLeft () != null ) temp = temp . getLeft (); ...

what is LOREM ipsum and why do designers use it

What is Lorem Ipsum? Lorem Ipsum  is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum. Why do we use it? It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now...

Track Lost Android Phone and Tablet

1. Use the IMEI Number Every Android phone carries a unique IMEI number. It will be printed at the back of your device. If you are unable to find the number, you have to launch your phone app and dial the number *#06#. This will give you the IMEI number of your phone. Store this number in a safe place so that it helps you in locating your phone when it is lost 2 Android Device Manager Google has recently released a new locator feature for Android gadgets called Android Device Manager, which helps its users locate their lost or stolen phones and tablets. It functions in the same way as Lookout and Samsung’s “Find My Mobile”. Here’s how to use Android Device Manager. Go to the Google Settings app, then select Android device manager. By default, the locator feature is activated but to activate remote data wipe, select the box next to “Allow remote factory reset”, then select “activate”. To use this feature, open the site https://www.google.com/android/devicemanager and sig...

DOWNLOAD ADVANCED INSTALLER

DOWNLOAD FEATURES JAVA LICENSING PURCHASE SUPPORT FORUMS Caphyon Advanced Installer Advanced Installer The power of Windows Installer made easy Buy Download .MSI installs in Minutes Advanced Installers deploy products on millions of computers worldwide Powerful and easy to use  Windows Installer  authoring tool. Install, update and configure your products  safely, securely  and reliably . Freeware Windows Installer Free Installer Trial With Advanced Installer, packaging and deploying SourceTree is now just a simple part of our development process. We can focus our efforts on building new features in SourceTree and improving existing ones so that SourceTree becomes the best Windows interface to Git source repositories. Steve Streeting , Lead developer of SourceTree at  Atlassian Full story Windows Installer Software Windows Installer Software Windows Installer Software Windows Installer Software Wind...

Streamlining Java Web Application Deployment with React WAR Generator

In the ever-evolving world of web development, managing builds and deployments can often be cumbersome and error-prone. Today, we're excited to introduce a tool designed to simplify and streamline this process: the React WAR Generator . What is the React WAR Generator? The React WAR Generator is a Python-based tool that automates the creation of WAR (Web Application Archive) files for Java web applications. It caters specifically to frontend projects built with React or similar frameworks, making it easier to package and deploy your web applications to a Tomcat server. Key Features Profile-Based Builds : With support for multiple profiles ( dev , test , prod , default ), you can build your application according to different environments and configurations. Version File Generation : Optionally generate a version file that integrates versioning information directly into your TypeScript files, ensuring your build versions are always up-to-date. Tomcat Deployment : Simplify your deploy...

how to Send a Confirmation Email Upon Form Submission-Woofoo

When someone successfully submits an entry, you can automatically send them a confirmation email to let them know. You can customize the email to include any follow-up info you'd like, and you can choose to include a copy of their entry in the email as well. To set up confirmation emails in Form Settings: Log in and go to  Forms . Hover over  Edit  next to the form you want to edit. Choose  Edit form . Click the  Form Settings  tab. Under Confirmation Options, select  Send Confirmation Email to User . From the  Send To  dropdown, select an Email field from your form. We'll send the confirmation email to the email address the person filling out your form entered into this field. If the dropdown says "No Email Fields Found", add an  Email  field to your form. In the  Reply To  textbox, enter the reply-to email—if someone replies to their confirmation email, this is the email address that their reply will be s...

Exception Handling in Java

Exception Handling() it is an event that stops the normal flow of execution of the program and terminates the program abnormally. Exception always occurs at runtime. There Is two type of Exception: Checked Exception.:-The exception which is checked by the compiler at the compilation time. Ex: IOException,ClassNotFoundException. Unchecked Exception: The Exception which Cant be checked by the compiler at the compilation time and directly occurs at runtime is called an unchecked Exception. Ex:NullPointerException,StringIndexOutOfBoundsException. Error: Error is the type of unchecked Exception which occurs due to programmers mistake, end-user input mistake, resource unavailability or network problem etc. OutOfMemoryError StackOverFlowError etc. 5 keywords to handle Exception: try catch finally throw throws possible combination: try-catch try-catch-catch try-catch-finally try finally try-...

Input and Output Functions in c

Objectives: Having read this section you should have a clearer idea of one of C's: 1.input functions, called scanf 2.output functions, called printf On The Run: Even with arithmetic you can't do very much other than write programs that are the equivalent of a pocket calculator. The real break through comes when you can read values into variables as the program runs. Notice the important words here: "as the program runs". You can already store values in variables using assignment. That is: a=100; stores 100 in the variable a each time you run the program, no matter what you do. Without some sort of input command every program would produce exactly the same result every time it was run. This would certainly make debugging easy! But in practice, of course, we need programs to do different jobs each time they are run. 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 cal...