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

20 Windows Keyboard Shortcuts You Might Not Know

Global Windows Shortcuts Win+1, 2, 3, 4, etc. will launch each program in your taskbar. It is helpful then to keep your most used programs at the beginning of your task bar so you can open them one right after another. This also works in Windows Vista for the quick launch icons. Win+Alt+1, 2, 3, etc. will open the jump list for each program in the taskbar. You can then use your arrows to select which jump list option you want to open. Win+T will cycle through taskbar programs. This is similar to just hovering over the item with your mouse but you can launch the program with Space or Enter. Win+Home minimizes all programs except current the window. This is similar to the Aero shake and can be disabled with the same registry key. Win+B selects the system tray which isn’t always useful but can come in very handy if your mouse stops working. Win+Up/Down maximizes and restores down the current window so long as that window has the option to be maximized. It is exactly t...

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...

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 Put Google Adsense Below Post Title in Blogger?

Adsense is used by majority of expert bloggers for their website monetization because it is a cookie based contextual advertising system that shows targeted ads relevant to the content and reader. As bloggers are paid on per click basis, they try various ad placements on the blog to  increase the revenue  and get maximum clicks on the ad units. Well, on some blogs, you might have seen Adsense ad units placed below the post title. Do you know why? It is because the area just below the post title gets the most exposure and is the best place to put AdSense ad units to increase  Click Through Rate (CTR). Even though ads below post title work like a charm but this doesn’t mean that it will work for you as well. If you want to find out the best AdSense ads placement for your blog, try experimenting by placing ads at various locations such as header, sidebar, footer, etc. You can try other  blog monetization methods  as well to effectively monetize y...

Java API call Example using GSON, org.json.json and Jackson [ Simple Get Call] and parsing result as JSON

import com.fasterxml.jackson.databind.JsonNode ; import com.fasterxml.jackson.databind.ObjectMapper ; import com.google.gson.* ; import org.json.JSONArray ; import org.json.JSONObject ; import java.io.* ; import java.net.HttpURLConnection ; import java.net.URL ; public class APICALL { public static void main (String[] args) throws IOException { // String url="https://mocki.io/v1/19a50724-c2e5-46a1-b457-543462cdfde2"; String url= "https://jsonplaceholder.typicode.com/users" ; String line ; StringBuilder resp= new StringBuilder() ; System. out .println(url) ; HttpURLConnection con= (HttpURLConnection) new URL(url).openConnection() ; con.setRequestMethod( "GET" ) ; con.setRequestProperty( "Accept" , "application/json" ) ; System. out .println(con.getResponseMessage()) ; System. out .println(con.getContentType()) ; InputStream inputStream=con.getInput...

remove virus without antivirus

want  to remove virus without antivirus here it is Start->Run->type cmd in each drive type attrib /s /d it will display the list of all files in that drive along with folders.concntrate on files having SHR attribute.normally virus files have two characteristics 1.SHR attribute 2.Queer name like amvo.exe,r6r.exe,autorun.inf etc. Noteme system files also have this attribute like MSDOS.SYS,IO.SYS etc so before deleting googling about that file will help. to delete these files type c:\>del /f /s /a >> to view the content of files with .inf,.vbs,.c etc i.e files which r not batch files or executables.goto explorer n then goto the required drive or folder n type the filename with extension it wil open up in notepad. >>there is another method also.goto the required location n type attrib -s -h -r filename then use gui to see that hiiden file.if it is not n exe or .bat or then open it with notepad.Here you will get some information like a file na...

Creating an Executable Jar File

Creating a jar File in  Eclipse In  Eclipse  Help contents, expand "Java development user guide" ==> "Tasks" ==> "Creating JAR files."  Follow the instructions for "Creating a new JAR file" or "Creating a new runnable JAR file."The  JAR File  and  Runnable JAR File  commands are for some reason located under the  File menu: click on  Export...  and expand the  Java  node. Creating a jar File in  JCreator You can configure a "tool" that will automate the jar creation process.  You only need to do it once. Click on  Configure/Options . Click on  Tools  in the left column. Click  New , and choose  Create Jar file . Click on the newly created entry  Create Jar File  in the left column under  Tools . Edit the middle line labeled  Arguments:  it should have cvfm $[PrjName].jar manifest.txt *.class Click OK. Now set...

keyboard-shortcuts-that-work-in-all-web-browsers

Each major web browser shares a large number of keyboard shortcuts in common. Whether you’re using Mozilla Firefox, Google Chrome, Internet Explorer, Apple Safari, or Opera – these keyboard shortcuts will work in your browser. Each browser also has some of its own, browser-specific shortcuts, but learning the ones they have in common will serve you well as you switch between different browsers and computers. This list includes a few mouse actions, too. Tabs Ctrl+1-8 – Switch to the specified tab, counting from the left. Ctrl+9 – Switch to the last tab. Ctrl+Tab – Switch to the next tab – in other words, the tab on the right. (Ctrl+Page Up also works, but not in Internet Explorer.) Ctrl+Shift+Tab – Switch to the previous tab – in other words, the tab on the left. (Ctrl+Page Down also works, but not in Internet Explorer.) Ctrl+W, Ctrl+F4 – Close the current tab. Ctrl+Shift+T – Reopen the last closed tab. Ctrl+T – Open a new tab. Ctrl+N – Open a new browser window....

Samsung mobile cheat codes

* Software version: *#9999# * IMEI number: *#06# * Serial number: *#0001# * Battery status- Memory capacity : *#9998*246# * Debug screen: *#9998*324# – *#8999*324# * LCD kontrast: *#9998*523# * Vibration test: *#9998*842# – *#8999*842# * Alarm beeper – Ringtone test : *#9998*289# – *#8999*289# * Smiley: *#9125# * Software version: *#0837# * Display contrast: *#0523# – *#8999*523# * Battery info: *#0228# or *#8999*228# * Display storage capacity: *#8999*636# * Display SIM card information: *#8999*778# * Show date and alarm clock: *#8999*782# * The display during warning: *#8999*786# * Samsung hardware version: *#8999*837# * Show network information: *#8999*638# * Display received channel number and received intensity: *#8999*9266# * *#1111# S/W Version * *#1234# Firmware Version * *#2222# H/W Version * *#8999*8376263# All Versions Together * *#8999*8378# Test Menu * *#4777*8665# GPSR Tool * *#8999*523# LCD Brightness * *#8999*377# Error LOG Menu *...

C program to find whether two Strings are cyclic Anagram or not

Example 1.first String: abcd  second string:dabc  output:They are cyclic anagram 2.  first String: abcd  second string:dcab output:They are not  cyclic anagram CODE: 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 # include # include int main() { char s[ 100 ], b[ 100 ], temp; int n, len, i; printf( "Enter the String \n " ); scanf( "%s" , s); printf( " \n Entered String=%s" , s); printf( " \n Enter String to be matched->" ); scanf( "%s" , b); printf( " \n Entered String to be matched->%s" , b); len = strlen(s); if (len != strlen(b)) { printf( " \n they are not cyclic anagram \n " ); getchar(); return 0 ; } ...