Home » How to know the do while loop in C programming [closed]

How to know the do while loop in C programming [closed]

Solutons:


Well: Hope the following helps you.

  • Unlike for and while loops, which test the loop condition at the top
    of the loop, the do…while loop in C programming language checks its
    condition at the bottom of the loop
  • A do…while loop is similar to a while loop, except that a do…while loop is guaranteed to execute at least one time.

A sample syntax would be:

do{
statement(x);

}while(condition);

Notice that the conditional expression appears at the end of the loop, so the statement(x) in the loop execute once before the condition is tested.

If the condition is true, the flow of control jumps back up to do, and the statement(x) in the loop execute again. This process repeats until the given condition becomes false.

Try this code and you will be good:

#include <stdio.h>

int main ()
{
   // local variable definition 
   int x = 5;

   // do loop execution 
   do
   {
       printf("value of x: %dn", x);
       x = x + 1;
   }while( x < 10 );

   return 0;
}

Here is a great way to understand the difference between a while loop and a do / while loop.

(But first, a side note: do / while are actually pretty rare in practice. You don’t usually need them. The good, clean algorithms that you usually want to write, that naturally do the right thing for any input, and that properly do nothing when they’re given no input, usually end up being written in terms of while loops. “while (there's something to do) { do something; }“. But there are times when a do / while loop is exactly what you want.)

Suppose you’re trying to convert an integer to a string, that is, construct a string containing the base-10 representation of an integer, basically just like printf %d. This is a standard exercise. Here is the standard solution:

void itoa(int n, char buf[], int size)
{
    char *p = buf;
    while(n > 0)
        {
        if(p >= &buf[size-1]) abort();
        *p++ = n % 10 + '0';
        n /= 10;
        }
   *p = '';

   strrev(buf);
}

We use the % operator to generate digits, filling them into a destination array. The standard additional difficulty with this technique is that it generates digits in the wrong order; the standard way to compensate for that is with a string-reverse function. Anyway, here’s the string-reverse function and a little test driver so you can try it out:

void strrev(char str[])
{
    char *p1 = str, *p2;
    for(p2 = str; *p2 != ''; p2++)
        ;
    p2--;
    while(p1 < p2)
        {
        char tmp = *p1;
        *p1 = *p2; *p2 = tmp;
        p1++; p2--;
        }
}

So go ahead and type that code in, and compile it, and play with it. You should discover that it works fine for just about any number you can type into it, except…

It does not work for zero! If you type in 0, the test while(n > 0) fails immediately, and we make zero trips through the loop, and we compute no digits, and we generate an empty string.

So: suppose you want to generate the string "0" for zero. In other words, suppose we always want to make at least one trip through the loop, even when n is initially 0. This sounds like a job for… do / while! Just rewrite the loop like this — same body, same condition (n > 0), but with the condition tested at the bottom of the loop instead of at the top:

do  {
    if(p >= &buf[size-1]) abort();
    *p++ = n % 10 + '0';
    n /= 10;
    } while(n > 0);

Try this, and you’ll see that it generates the same output for positive numbers, and now it works as expected for 0, too.

(But, in case you were wondering, the other thing this simple code doesn’t handle, and the do/while modification does nothing to address, is negative numbers.)

Related Solutions

How to remove repetition in output results in this code

You could put all your lines in a java.util.LinkedHashSet<String>. A Set means it will only keep distinct items. The reason we'll use a LinkedHashSet instead of a regular HashSet is to retain the input-order. After adding them all to the set, we print...

Can You decrypt this javascript?

the script is not encrypted, but obfuscated, But, to reduce your curiosity, see the script below after I've deobfuscated: var z = ["$(i)['f'](5(){$('#3')['j']('<a 4="2://6.7.8" c="d" e="b" g="h:9!0;k:1!0;l:m!0">تصميم:عبدو...

i do not understand this bfs algorithm code

The main thing you don't understand is std::pair http://www.cplusplus.com/reference/utility/pair/ which combines two types (or two of the same type) into the type of one object made from those two. Also notice the using namespace std; that lets the programmer...

How to save Answers in SQL?

The best way of saving multiple records into an sql server table from .Net is using a table valued parameter. First, you need to create a user defined table type (UDT) in your sql server: CREATE TYPE UDT_UserAnswers AS TABLE ( UserAnswers_UserId int,...

unlimited zero as output while running c++ in cpp driod

First off, you need to declare the variable j somewhere. Assuming you have declared j somewhere else in the program, this program as you have written it here will actually print nothing out. Since j is set to start at 0, and 0 is not greater than 0, the...

Android get text from editText

First initialize the editText just like you initialize the Button and TextView then you are able to get the text from editText you must have initialize. (EditText, input1 and input2). in Activity : EditText editTextView1; EditText editTextView2; String input1;...

T-SQL to generate expect result

Assuming that I understand the problem: you have a number of rows with sections ("Cates") and symbols ("Type"); if there are any symbols ending in a minus sign then these indicate a row without a minus sign should be removed; symbols are never "mixed" per...

retrieve contents of div and make image src

The button demonstrates that ablility. Use the button's onclick code wherever you need. <div id="flag-name" style="hidden">en-flag.jpg</div> <img id="myImage" /> <button...

Not getting correct javascript [closed]

So the mistake you're making is that if you loop through several things and hardcode the id, several elements get the same id, which is why your increase() function is updating the "wrong" elements. So you need to give each item in the loop a unique id. One way...

Leaderboard/Highscore for game in PHP

Rather than doing this psuedo: Scenario 1: // user exists // determine current score // update user, current score + new game score Scenario 2: // user does not exist // insert user with new game score Here, you're trying to keep a single row updated with the...

Copy content of one array to another arry

You can use Array.prototype.concat() var A = [1, 2, 3, 4]; var res = A.concat(A); console.log(A, res); I'd suggest to go with guest271314 answer. But if you want to multiply it more than twice, and you're looking for an alternative solution, you can also do it...

How to Make text appear and disappear on image after tapping.

Based on the code you provided, here is a solution that allows the visibility of a div to be toggled when the container is clicked using JavaScript: <style> /* Container holding the image and the text */ .container { position: relative; } /* Bottom right...

Explain the output obtained by using the following Macro

If you had considered the warnings you could have identified yourself macro1.c: In function ‘main’: macro1.c:11:3: warning: passing argument 1 of ‘printf’ makes pointer from integer without a cast [enabled by default] ABC(("Sum of x + y is %d", x + y)); ^ In...

Font scaling based on width of container

But what if the container is not the viewport (body)? This question is asked in a comment by Alex under the accepted answer. That fact does not mean vw cannot be used to some extent to size for that container. Now to see any variation at all one has to be...

How to send Some Value in Button to Textbox in c sharp? [closed]

Hi just add simple code to your buttons, Concern about validations and things. private void plusButton_Click(object sender, EventArgs e) { if (string.IsNullOrEmpty(textBox2.Text)) { int count = 0; textBox2.Text = count.ToString(); } else { int count =...

Clarification regarding content in my android app [closed]

Should i be worried about getting sued (if seen from other angle the source website will also make revenue from my app as their websites are being viewed) (i even show disclaimer saying "all articles belong to respective owners") Directly copying content even...

How do I prevent from writing a number that is already written?

Using a hashset, For every new number, check. If it already exist inside the hashset, ignore it else add it to the hash set and print it int[] numbers = new int[100]; HashSet<int> uniqueNums = new HashSet<int>(); for (int i=0; i < numbers.Length;...

Android code not working

Change your onCreate View like This: TextView textView; ImageView imageView; Button eat; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textView = (TextView)...

Increase Boost regex speed or use PCRE in C++ [duplicate]

i used the boost and got better result (2 Min) You'd have to show me that to believe it !! Using benchmark software from this app RegexFormat that uses Boost, I get less than 3 seconds. The thing with that benchmark software is you can use a single test line...