question on for loop

This is a discussion on question on for loop within the C++ Programming forums, part of the General Programming Boards category; how can i construct a summation program using a for loop? i.e. the user enters the number 2 and the ...

  1. #1
    Registered User
    Join Date
    Oct 2006
    Posts
    6

    question on for loop

    how can i construct a summation program using a for loop? i.e. the user enters the number 2 and the program executes: 0 + 1 + 2 = 3.

  2. #2
    Registered User
    Join Date
    Jan 2005
    Posts
    7,340
    How would you do it? What are your ideas?

  3. #3
    Registered User
    Join Date
    Oct 2006
    Location
    Miami, FL
    Posts
    6
    If you have a loop like the following:
    Code:
    int count = 5;
    
    for(int i = 0; i <= count; i++) {
         printf("%i ", i);
    }
    It will print out "0 1 2 3 4 5". Figuring out how to get the program to sum these values is extremely easy at this point.

  4. #4
    Registered User
    Join Date
    Nov 2005
    Posts
    545
    Apart from if you are using C++ then don't use printf

  5. #5
    Reverse Engineer maxorator's Avatar
    Join Date
    Aug 2005
    Location
    Estonia
    Posts
    2,318
    Printf is totally legal in C++.
    http://www.cppreference.com/stdio/index.html
    Code:
    int count = 5;
    int sum=0;
    for(int i = 0; i <= count; i++) {
        sum+=i;
        printf("%i ", i);
        if(i==count-1){
            printf("+ ");
        }
        else{
            printf("= ");
        }
    }
    printf("sum: %i",sum);
    "The Internet treats censorship as damage and routes around it." - John Gilmore

  6. #6
    Registered User
    Join Date
    Jan 2005
    Posts
    7,340
    Just because something is legal doesn't mean you should use it. gets is legal in C. Although there is little reason to discuss it here since it is irrelevant to the topic and the point being made by UMTopSpinC7.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Alice....
    By Lurker in forum A Brief History of Cprogramming.com
    Replies: 16
    Last Post: 06-20-2005, 02:51 PM
  2. Debugging question
    By o_0 in forum C Programming
    Replies: 9
    Last Post: 10-10-2004, 05:51 PM
  3. Question about pointers #2
    By maxhavoc in forum C++ Programming
    Replies: 28
    Last Post: 06-21-2004, 12:52 PM
  4. Question...
    By TechWins in forum A Brief History of Cprogramming.com
    Replies: 16
    Last Post: 07-28-2003, 09:47 PM
  5. Question, question!
    By oskilian in forum A Brief History of Cprogramming.com
    Replies: 5
    Last Post: 12-24-2001, 12:47 AM

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