Skip to main content

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 number of instructions you can write and it doesn't take long for

a computer to read though and obey your list. So how is it that we have programs that run for hours on end if need be? The answer is statements that alter the one-after-another order of
obeying instructions. Perhaps the most useful is the loop.

Suppose we ask you to display "Hello World!" five times on the screen. Easy! you'd say:


#include
main()
{
printf("Hello World!\n");
printf("Hello World!\n");
printf("Hello World!\n");
printf("Hello World!\n");

printf("Hello World!\n");
}

Indeed, this does exactly what was asked. But now we up the bet and ask you to do the same job for 100 hellos or, if you're still willing to type that much code, maybe 1,000 Hello World's,
10,000 Hello World's, or whatever it takes you to realise this isn't a sensible method!

What you really need is some way of repeating the printf statements without having to write it out each time. The solution to this problem is the while loop or the do while loop.

The while and do while Loops:

You can repeat any statement using either the while loop:

while(condition) compound statement;

or the do while loop:

do compound statement while(condition);

The condition is just a test to control how long you want the compound statement to carry on repeating.

Each line of a C program up to the semicolon is called a statement. The semicolon is the statement's terminator. The braces { and } which have appeared at the beginning and end of our

program unit can also be used to group together related declarations and statements into a compound statement or a block.

In the case of the while loop before the compound statement is carried out the condition is checked, and if it is true the statement is obeyed one more time. If the condition turns
out to be false, the looping isn't obeyed and the program moves on to the next statement. So you can see that the instruction really means while something or other is true keep on doing

the statement.

In the case of the do while loop it will always execute the code within the loop at least once, since the condition controlling the loop is tested at the bottom of the loop. The do while
loop repeats the instruction while the condition is true. If the condition turns out to be false, the looping isn't obeyed and the program moves on to the next statement.


Conditions or Logical Expressions:

The only detail we need to clear up is what the condition (or Logical Expression) can be. How, for example, do we display 100 or 10,000 "Hello World!" messages? The condition

can be any test of one value against another. For example:

a>0

is true if a contains a value greater than zero;

b<0 br="">
is true if b contains a value less than zero.

The only complication is that the test for 'something equals something else' uses the character sequence == and not =. That's right: a test for equality uses two equal-signs, as in a==0, while
an assignment, as in a=0, uses one. This use of the double or single equal sign to mean slightly different things is a cause of many a program bug for beginner and expert alike!

So what about answering the question? What about the 100 "Hello World"s? Well, for the moment we know easily how to produce an infinite number of Hello World!"s using while loop:


#include
main()
{
while (1 == 1) printf("Hello World!\n");
}

and using the do while loop:


#include
main()
{
do
printf("Hello World!\n");
while (1 == 1)
}

If you type either of these programs in and run it you will find that your screen fills with a never ending list of "Hello World!"s. Why? Because the condition to keep the repeat going is ( 1 ==

1 ), one equals one in plain English, which is always true! So how do we stop the loop? In some cases it could be by pulling the plug out - but usually you can stop an infinite loop by
pressing Ctrl-Break or Ctrl-C.

An infinite loop is sometimes useful - I certainly hope the program controlling the nearest nuclear power station is an infinite loop that never receives a Ctrl-Break signal! Most loops,
however, have to stop some time.

To solve our problem of printing 100 "Hello World!"s we need a counter and a test for when that counter reaches 100. A counter is a simple variable that has one added to it each time

through the loop, using an instruction like this:

a=a+1;

This always confuses beginners, because they aren't used to seeing the variable on both sides of the equal-sign. All this means is that a has one added to it to produce a new value, and this
value is stored back in the location called a. If you're worried, try thinking about it as:


temp = a+l;
a = temp;


The two approaches are more or less the same. C is a language where anything that's used often can be said concisely, so it lets you say "add one to a variable" using the shorter notation:

++a;

The double plus is read "increment a by one". Make sure you know that ++a; and a=a+1; are the same thing because you will often see both in typical C programs.

The increment operator ++ and the equivalent decrement operator --, can be used as either prefix (before the variable) or postfix (after the variable). Note: ++a increments a before using
its value; whereas a++ which means use the value in a then increment the value stored in a.

Now it is easy to print "Hello World!" 100 times using the while loop:

#include
main()
{
int count;
count=0;
while (count < 100)
{
++count;
printf("Hello World!\n");
}
}

[program]

or the do while loop:


#include
main()
{
int count;
count=0;
do
{
++count;
printf("Hello, World!\n");
} while (count < 100)
}


Note: the use of the { and } to form a compound statement; all statements between the braces will be executed before the loop check is made.

The integer variable count is declared and then set to zero, ready to count the number of times we have gone round the loop. Each time round the loop the value of count is checked against
100. As long as it is less, the loop carries on. Each time the loop carries on, count is incremented and "Hello World!" is printed - so eventually count does reach 100 and the loop stops.
These little programs are just a bit more subtle than you might think. Ask yourself, do they really print exactly 100 times? Ask yourself: what is the final value of count? If you want to make

sure you are right change the printf to:

printf("count is %d",count);

and add a printf after the loop:

printf("final value is %d",count);

Make sure you understand why you get the results that you do. What would happen if you changed the initial value of count to be one rather than zero?


Looping the Loop:

We have seen that any list of statements enclosed in curly brackets is treated as a single statement, a compound statement. So to repeat a list of statements all you have to do is put them

inside a pair of curly brackets as in:


while (condition)
{
statementl;
statement2;
statement3;
}

which repeats the list while the condition is true. Notice that the statements within the curly brackets have to be terminated by semicolons as usual. Notice also that as the while statement
is a complete statement it too has to be terminated by a semi-colon - except for the influence of one other punctuation rule. You never have to follow a right curly bracket with a

semi-colon. This rule was introduced to make C look tidier by avoiding things like

};};};}

at the end of a complicated program. You can write the semi-colon after the right bracket if you want to, but most C programmers don't. You can use a compound statement anywhere you
can use a single statement.


The for Loop:

The while, and do-while, loop is a completely general way of repeating a section of program over and over again - and you don't really need anything else but... The while loop repeats a

list of instructions while some condition or other is true and often you want to repeat something a given number of times.

The traditional solution to this problem is to introduce a variable that is used to count the number of times that a loop has been repeated and use its value in the condition to end the loop. For
example, the loop:


i=l;
while (i<10 br=""> {
printf("%d \n",i);
++i;
}

repeats while i is less than 10. As the ++ operator is used to add one to i each time through the loop you can see that i is a loop counter and eventualy it will get bigger than 10, i.e. the loop

will end.

The question is how many times does the loop go round? More specifically what values of i is the loop carried out for? If you run this program snippet you will find that it prints 1,2,3... and
finishes at 10. That is, the loop repeats 10 times for values of i from 1 to 10. This sort of loop - one that runs from a starting value to a finishing value going up by one each time - is so
common that nearly all programming languages provide special commands to implement it. In C this special type of loop can be implemented as a for loop.

for ( counter=start_value; counter <= finish_value; ++counter )
compound statement


which is entirely equivalent to:


counter=start;
while (couner <= finish)
{
statements;
++counter;
}


The condition operator <= should be interpreted as less than or equal too. We will be covering all of C's conditions , or logical expressions, in the next section.

For example to print the numbers 1 to 100 you could use:

for ( i=l; i <= 100; ++i ) printf("%d \n",i);

You can, of course repeat a longer list of instructions simply by using a compound statement.

The C for loop is much more flexible than this simple description. Indeed, many would be horrified at the way we have described the for loop without displaying its true generality, but
keep in mind that there is more to come.

In the meantime consider the following program, it does a temperature conversion, but it also introduces one or two new concepts:

1.our counter does not have to be incremented (deremented) by 1; we can use any value.

2.we can do calculations within the printf statement.


#include

main()
{
int fahr;

for ( fahr = 0 ; fahr <= 300 ; fahr = fahr + 20)
printf("%4d %6.1f\n" , fahr , (5.0/9.0)*(fahr-32));

}

and here's another one for you to look at:


#include

main()
{
int lower , upper , step;
float fahr , celsius;

lower = 0 ;
upper = 300;
step = 20 ;

fahr = lower;

while ( fahr <= upper ) {

celsius = (5.0 / 9.0) * (fahr - 32.0);
printf("%4.0f %6.1f\n" , fahr , celsius);
fahr = fahr + step;
}
}

Comments

Popular posts from this blog

Random post with specific label - Blogger Widget

1. go to blogger dashboard, select template and edit html. 2. search for </head> to add script. - you may download and upload to your site, or just use this link (no download required) script <script src='http://docs.google.com/uc?id=0B7xJbTAja8i0a0ZJbXJ2TkkwSW8&amp;export=download' type='text/javascript'/> 2. search for ]]></b:skin> to add style/css. img.label_thumb{ float:left; padding:5px; border:1px solid #8f8f8f; background:#D2D0D0; margin-right:10px; height:55px; width:55px; } img.label_thumb:hover{ background:#f7f6f6; } .label_with_thumbs { float: left; width: 100%; min-height: 70px; margin: 0px 10px 2px 0px; adding: 0; } ul.label_with_thumbs li { padding:8px 0; min-height:65px; margin-bottom:10px; } .label_with_thumbs a {} .label_with_thumbs strong {} 2. save template. 3. add a widget. 3. edit widget. at this example i use random post with label "blogger", you must replace it with your label. <div s...

Submit your site for free to search engine~SEO TOOL SERACH ENGINE SUBMitt free

free Submit the main page of your site only. The rest of your site will be crawled by the search engines. Only 5 submissions in every 24 hours period are allowed. URL  * Email  * Name  * Business Phone  * Country  *   None Selected   United States   Afghanistan   Albania   Algeria   American Samoa   Andorra   Angola   Anguilla   Antigua and Barbuda   Argentina   Armenia   Aruba   Australia   Austria   Azerbaijan   Bahamas   Bahrain   Bangladesh   Barbados   Belarus   Belgium   Belize   Benin   Bermuda   Bhutan   Bolivia    Bosnia Hercegovina   Botswana   Bouvet Island   Brazil   Brunei Darussalam   Bulgaria   Burkina Faso   Burundi   Cambodia   Cameroon   Canada   Cape Verde   Cayman Islands   Central African Republic   Chad   Chi...

Tips to Enable or Disable Toast Notifications on Windows 8

Windows 8 is among the most incredible and interesting kind of Windows version from Microsoft. It has visually eye catching design, which is found in modern user interface that is meant for redesigning a number of operating systems, worked out for users. If you have used or seen someone using Windows 8 you could have noticed the toast notifications in this modern version of windows, which simply appears the moment you install or uninstall any application. There are many users who are well versed with the bubble notifications, which were found in the earlier versions of Windows seen via the taskbar. The new application platform in Windows 8 comes with an integrated notification system for installing or uninstalling a number of modern applications. The Windows 8 style application can employ a number of notifications types including the traditional toast notifications, live titles and lock screen. These can be managed by either disabling or enabling the notification of your applicatio...

List of all search engine by topics,genre and based on

Tweet General Baidu  (Chinese, Japanese) Bing Blekko Google Sogou  (Chinese) Soso.com  (Chinese) Volunia Yahoo! Yandex.com Yodao  (Chinese) P2P search engines FAROO Seeks  (Open Source) YaCy  (Free and fully decentralized) Metasearch engines See also:  Metasearch engine Blingo Yippy  (formerly Clusty) DeeperWeb Dogpile Excite Harvester42 HotBot Info.com Ixquick Kayak Mamma Metacrawler Mobissimo Otalo PCH Search and Win SideStep Thiv WebCrawler Geographically limited scope Accoona ,  China / United States Alleba , Philippines Ansearch ,  Australia / United States / United Kingdom / New Zealand Biglobe ,  Japan Daum ,  Korea Goo ,  Japan Guruji.com ,  India Leit.is ,  Iceland Maktoob ,  Arab World Miner.hu ,  Hungary Najdi.si ,  Slovenia Naver ,  Korea Onkosh ,  Arab World Rambler ,  Russia Rediff ,  India SAPO ,...

Downloading Windows 8 for Free [Full version]

Tweet Downloading Windows 8 for Free [Full version] Windows 8 is a new version of Windows that focuses on variety of hardware platform and form factors such as slim-type computers and new generation of touch devices. The new version free for download was made available for developers and testers of the new OS. Here’s the download links for the Enterprise version of Windows. How to get and download the latest operating system Thankfully, Microsoft released the new version free for download designed for technological professionals, engineers and IT personnel's for testing and debugging purposes. Download Links of the ISO file (x86 and x64) Windows 8 32-Bit version Windows 8 64-Bit version If you can’t download the file, make sure that you are login to your respected  Hotmail account .

Google Sheet/Google form Script to send automated Email to users

Well many of us want to send especially bloggers sometimes want to send automated replies to user 's ..but as usual, not everyone is a code geek or lovers ... so this is a small guide to How to use Google form with Google sheet to make an automated reply link....so follow the steps accordingly. STEP 1: GOTO google Forms ... and create a form ... in my case I just take users email id and how do they get to my site. 1. GOTO   https://docs.google.com/forms?usp=mkt_forms 2. login with your account. now choose blank form. 3. in Form title write your forms name, for example, let say my form. 4. in Form description write the description let say  A simple form ... 5. now go to setting and in general tab, check collect email address. and  click on save 6. (optional) you can also ask some basic question 7. now goto responses tab now click on create new spreadsheet button. (that green icon ..) in select response, destination cho...

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 (); ...

C++ Program to implement Virtual Class by using Multipath Inheritance

Issue the books to various members of library. – Member-Membername, Age, Address – Faculty (derived from member classs)- Department and integer type array for issuing books with upperlimit 10. – Student (derived from member class)- Class, Rollno and integer type array for issuing books with upperlimit 4. Daily Transaction (derived from Faculty and Student classes)- date of issue, date of return (calculated from date of issue as 15 days for students and 45 days for a faculty). #include #include #include #include #include class CDATE{     private:         int dd;         int mm;         int yy;     public:         struct date d;         CDATE(){             getdate(&d);             dd = d.da_day;             mm = d.da_mon;         ...

just more way to disable autorun.inf

Auto run.Inf this is a instruction file associated with the Auto run function. It is a simple text configuration file that instructs the OS (operating system) which executable to start which icon to use which additional menu commands to make available etc Auto run.inf must be located in the root directory of a volume.That is CD,DVD,of Floppy Disk or Pen drive. It is mainly used by the manufacturer on what actions to taken when their CD-ROM when it is inserted. In OS, when autorun.inf is enabled (Normally by default it is enabled ) then by inserting the Cd or DVD the content of the medium is automatically executed. This is to avoid the user intervention and help the low level knowledge of computer literacy people. But Virus programmer taken this as advantage and make virus instruction in autorun.inf text file. TYPICAL AUTORUN.INF A typical autorun.inf file looks like below. [autorun] open=setup.exe icon=setup.exe,0 label=GameProgram SIMPLE METHOD NOT TO GET INFECTED BY AUTORUN.INF:...

python program get union of two list (program to get A union B ) list method .

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 #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Mar 16 17:08:52 2018 @author: beast """ def version1 (): a = [ 'a' , 'b' , 'c' , 'd' , 'e' ] # list 1 b = [ 'a' , 'b' , 'c' , 'd' , 'e' , 'f' , 'g' , 'h' ] # list 2 c = [k for k in (a) if (k in (a) and k not in (b))] # include unique item from list 1 : items are (list1-list2)(set thoery) d = [l for l in (b) if l in (a ) and l in (b) or (l not in (a) and l in (b))] #include all the comman from list 1 and unique from list 2 lst = c + d # append above two comprehensed list to get union of list1 U list2 lst . sort() # not neccessay but makes list easy to understand (sorting in ascending order ) ...