Can someone help me understand this very simple loop?

This is a discussion on Can someone help me understand this very simple loop? within the C Programming forums, part of the General Programming Boards category; Hello, I need to be able to know the output of this loop without a computer... I came up with ...

  1. #1
    Registered User
    Join Date
    Feb 2010
    Posts
    244

    Can someone help me understand this very simple loop?

    Hello,
    I need to be able to know the output of this loop without a computer... I came up with i=20 s=60, but the answer is i=20 s=3 and I dont understand the logic behind it. Can someone please explain?

    Code:
    int main() {
    	
    int i=0, s=0;
    while ( i<20)
    i++;
    s= s+3;
    printf("i=%d, s=%d\n", i, s);

    Thanks in advance

  2. #2
    Registered User
    Join Date
    Jan 2008
    Posts
    79
    i am guessing but i would assume that because you didnt include
    Code:
    {}
    That the while loop is just executing one line i.e the i++ the s=s+3 isnt in the loop and only gets called once the loop has exited i.e once i = 20

  3. #3
    Registered User
    Join Date
    Feb 2010
    Posts
    244
    hmm that kind of makes sense I hope your right, thank you!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. loop needed also how to make input use letters
    By LoRdHSV1991 in forum C Programming
    Replies: 3
    Last Post: 01-13-2006, 05:39 AM
  2. Trying to figure out a simple loop....
    By chadsxe in forum C++ Programming
    Replies: 9
    Last Post: 01-05-2006, 01:31 PM
  3. simple collision detection problems
    By Mr_Jack in forum Game Programming
    Replies: 0
    Last Post: 03-31-2004, 04:59 PM
  4. Request for comments
    By Prelude in forum A Brief History of Cprogramming.com
    Replies: 15
    Last Post: 01-02-2004, 10:33 AM
  5. for loop or while loop
    By slamit93 in forum C++ Programming
    Replies: 3
    Last Post: 05-07-2002, 05:13 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21