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

QWERTY-keyboard when this idean came

QWERTY QWERTY   / ˈ k w Éœr t i /  is the most common modern-day  keyboard layout . The name comes from the first six  keys  appearing on the top left letter row of the keyboard and read from left to right: Q-W-E-R-T-Y. The QWERTY design is based on a layout created for the  Sholes and Glidden typewriter  and sold to  Remington  in 1873. It became popular with the success of the Remington No. 2 of 1878, and remains in use on electronic keyboards due to the  network effect  of a standard layout and a belief that  alternatives  fail to provide very significant advantages. [ 1 ]  The use and adoption of the QWERTY keyboard is often viewed as one of the most important case studies in  open standards  because of the widespread, collective adoption and use of the product. [ 2 ] History and purposes [ edit ] Keys are arranged on diagonal columns, to give space for the levers. Main article:  Sholes and Glidden typewriter Still used to this day, the QWERTY layout was devised

python program to Print Starting Series OF Indian Mobile Number for a State or operator or both

import requests import urllib.request import time from bs4 import BeautifulSoup as bs import re url = ' https://en.wikipedia.org/wiki/Mobile_telephone_numbering_in_India' state_to_extract = "UE" #if set to None all state is considered telecom_to_extracted = None #if set to none all operator from particular city is extracted response = requests . get(url) print (response) soup = bs(response . text, "html.parser" ) one_a_tag = soup . findAll( 'tr' )[ 35 :] lst = [] for k in one_a_tag: s = k . findAll( 'td' ) limit = len (s) i = 0 while True : if i == limit: break no = s[i] . text i += 1 if i == limit: break operator = s[i] . text i += 1 if i == limit: break state = s[i] . text i += 1 if i == limit: break res = f "{no} {operator} {state}" if state_to_extract is None : if telecom_to_extracted is None : lst . append(no) elif telecom_to_e

Dragon Age: Inquisition Digital Deluxe Edition + All DLCs (torrent) Repack Size: 20.1~23.9 GB

Brief : Dragon Age: Inquisition  is an  action role-playing video game  developed by  Bioware Edmonton  and published by  Electronic Arts . The third major game in the  Dragon Age  franchise,  Dragon Age: Inquisition  is the sequel to  Dragon Age: Origins  and  Dragon Age II . The game was released worldwide in November 2014 for  Microsoft Windows ,  PlayStation 3 ,  PlayStation 4 ,  Xbox 360 , and  Xbox One . Repack Size: 20.1~23.9 GB 

robot.txt what is this and how to use this

What do they do exactly? Robot.txt files tell your instructions to a search engine robot.. The first thing a search engine spider looks at when it is visiting a page is the robots.txt file. It looks for it because it wants to know what it should do. If you have instructions for a search engine robot, you must tell it those instructions. The most common problem people have with robot.txt files is that they don't know how to make them. If you can make web pages, you can also make a robot.txt file. The file is a text file, which means that you can use notepad, wordpad, or any other plain text editor. You can also make them in Frontpage or Dreamweaver by using the "code" view. You can even "copy and paste" them. So instead of thinking "I am making a robot.txt file", just think, "I am writing a note" they are the exact same process. However you would write a note or a letter on your computer will work for the robot.txt file. What should

How to open facebook through Uninor when it is blocked

Tweet Just Follow this steps . 1. Goto www.uninor.in 2. choose your circle 3.Goto  http://www.uninor.in/customer-care/Pages/customer-complaint-log.aspx 4. Now in new complaint just type your moblie number 5.now you will receive passwrod just type in and hit submit 7. NOW select as following as type as it in every box Complaint Type   -- Select --   DND Related   GPRS   Network Related   Tariff & VAS Related   Activation/ Deactivation   Barring/ Unbarring   Balance Related    Complaint Area   -- Select --   Activation / Deactivation   PC/Modem Connectivity   Usage / Charges related   GPRS issues   Non-Uninor sites   Complaint sub Area   -- Select --   Unable to browse   Unable to download   Please ensure all questions below are answered in the text box below. 1. Handset make and model no. 2. Web Site Name/ URL 3. Error message

Overview of C

Why use C?: C has been used successfully for every type of programming problem imaginable from operating systems to spreadsheets to expert systems - and efficient compilers are available for machines ranging in power from the Apple Macintosh to the Cray supercomputers. The largest measure of C's success seems to be based on purely practical considerations: the portability of the compiler; the standard library concept; a powerful and varied repertoire of operators; an elegant syntax; ready access to the hardware when needed; and the ease with which applications can be optimized by hand-coding isolated procedures C is often called a "Middle Level" programming language. This is not a reflection on its lack of programming power but more a reflection on its capability to access the system's low level functions. Most high-level languages (e.g. Fortran) provides everything the programmer might want to do already built into the language. A low l

Download pocket tank delux with 295 weapons free total 295 weapons version 1.6

Download Pocket Tanks Deluxe Full Version Free With 295 Weapons Pack | Size: 30MB UPDATED 2019 /19/april Description: Pocket Tanks is a 1-2 player computer game for Windows and Mac OS X, created by Blitwise Productions, developer of Super DX-Ball and Neon Wars. Adapted from Michael Welch's earlier Amiga game Scorched Tanks, this newer version features modified physics, dozens of weapons ranging from simple explosive shells to homing missiles, and the ability to move the tank. It supports several expansion packs. At the moment, players can have up to 295 different weapons total. Pocket Tanks is often abbreviated as PTanks. Have Fun! NOTE: FILE NAME IS SCRAMBLED FOR AVOIDING HARD DETECTION & FILE TAKEN DOWN . How to Play: Best with 2 players on the same computer at school or at work. UPDATED LINK https://mirr.re/d/u1Y https://nl26.seedr.cc/ff_get/447027537/ptd16.295.exe?st=lUp-PbRp4YOwToHIOGwStQ&e=1555747979 http://www.uploadmagnet.com/7gfzhbyfe

Error:(1, 0) Plugin with id 'com.android.application' not found

just add the following code to your top level build.gradle  {note by top level build.gradle i means that if you open that build.gradle you will see a comment like this // Top-level build file where you can add configuration options common to all sub-projects/modules. add the following code  !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! buildscript { repositories { jcenter() } dependencies { classpath 'com.android.tools.build:gradle:0.12.+' // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files } } !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! and click on sync now ..it will do the rest..

Control Loops in c

Objectives: Having read this section you should have an idea about C's: 1.Conditional, or Logical, Expressions as used in program control 2.the do while loop 3.the while loop 4.the for loop Go With The Flow: Our programs are getting a bit more sophisticated, but they still lack that essential something that makes a computer so necessary. Exactly what they lack is the most difficult part to describe to a beginner. There ar e only two great ideas in computing. The first is the variable and you've already met that. The second is flow of control. When you write a list of instructions for someone to perform you usually expect them to follow the list from the top to the bottom, one at a time. This is the simple default flow of control through a program. The C programs we have written so far use this one-after-another default flow of control. This is fine and simple, but it limits the running time of any program we can write. Why? Simply because there is a limit to the nu