Thread: would anybody be kind enough to help?

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #10
    Registered User
    Join Date
    Jul 2004
    Posts
    8
    I rewrote your for loop for a few reasons. First I would use the FOR loop for this problem over the while loop, since you need to declare, test and count. Second if this is for school, most teachers will know if you go beyond your ability and while what everyone else posted is correct most new programmers don't think that way. Ex: while(x).

    Next, you made some bad logical errors in this one. Namely, having the cout in the loop and taking x^2 instead of i^2 the wrong number. I know for loops are the toughest of the 3 main loops but if you take a little time to learn them it's hard to not use them.

    Remember the standard for FOR loops is i is the counter variable and increases to a number in this case x. You have to use a sum variable to hold the ongoing result of the for loop unless you want each i square to be output. The FOR loop is only one statement here so the braces are optional. The pow() statement is of the format pow(number, power); No equals or the like are needed. I think that pretty much covers it.

    #include <iostream>
    #include <cmath>
    using namespace std;

    int main()
    {
    int x;
    int sum = 0;
    cout << "Please enter a number: ";
    cin >> x;
    for (int i = 1; i <= x; i++)
    sum += pow(i,2);

    cout << "The sum of the square of all integers from
    1 to the number you have entered is: "
    << sum << endl;
    return 0;
    }
    Last edited by raum; 07-07-2004 at 05:33 AM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. What kind of job...
    By Discolemonade in forum A Brief History of Cprogramming.com
    Replies: 5
    Last Post: 08-15-2005, 08:23 PM
  2. what kind compiler should I use
    By ilove in forum C++ Programming
    Replies: 9
    Last Post: 06-22-2005, 05:07 PM
  3. Getting three of a kind
    By Kons in forum C Programming
    Replies: 8
    Last Post: 08-19-2003, 12:44 PM
  4. What kind of code do u want a front-end designer generating?
    By MovingFulcrum in forum A Brief History of Cprogramming.com
    Replies: 4
    Last Post: 10-15-2001, 06:45 PM
  5. Physics: Kind of like a cannonball...
    By Cheeze-It in forum Game Programming
    Replies: 11
    Last Post: 09-12-2001, 01:53 PM