Solved

Help me debug this program

Posted on 2003-02-24
Medium Priority
211 Views
How do you use the for loop to find the sum of a five digit number?
ex) 12345 should have the sum of 15
23456                      = 20

but the way I program it, the answer is always = 15.  Help me fixed this problem.

this is what I got so far

#include <iostream>

using std::cout;
using std::cin;
using std::endl;

int main()
{
int number;
cout <<"Enter a five digit number: " << endl;
cin >> number;
int sum = 0;
for ( int i = sum;i <= 5; i++)
sum += i;
cout <<"Sum is " << sum << endl;

return( 0 );
}
0
Question by:Svy-20
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

• Help others & share knowledge
• Earn cash & points

LVL 8

Accepted Solution

akshayxx earned 180 total points
ID: 8013862
this should work for u.. not only for 5 digits but for more or less digits supported by the platform

#include <iostream>

using std::cout;
using std::cin;
using std::endl;

int main()
{
int number;
cout <<"Enter a five digit number: " << endl;
cin >> number;
int sum = 0;
while(number!=0){
sum+=number%10;
number=number/10;
}
cout <<"Sum is " << sum << endl;

return( 0 );
}
0

LVL 2

Expert Comment

ID: 8013874

There are probably a few different ways to do it, but the way I would approach it is read the number into a string

char buf[5];

[0] [1] [2] [3] [4] [5]
------------------------
buf: 1 | 2 | 3 | 4 | 5 |\0 |
------------------------

now you can probably see the solution.

using a character buffer, you can loop across the elements and then sum them up.  There's still a few other things you have to do to get it to fly, but I'll leave that as an excercise for you

hope this helps you on your way to solving the assignment

sincerely,
J
0

LVL 1

Expert Comment

ID: 8013898
Svy-20,
akshayxx's program does the job.
The reason why your pogram is always printing 15 is that your for loop is effectively:

for(int i = 0 ; i <= 5 ; i++)
sum += i

number actually has no impact on the for loop in your program, so it's just calculating sum(0,1,2,3,4,5) everytime which is 15.
0

Author Comment

ID: 8014127
Thank! this work
BUT
I need to know how to use the (FOR statement) for this program, if you know how, help me.

0

LVL 8

Expert Comment

ID: 8014410
while(number!=0){
sum+=number%10;
number=number/10;
}

when written in for loop will be

for(;number!=0;number=number/10)sum+=number%10;

this sounds pretty much home assignment.. use the FOR loop :P
0

Author Comment

ID: 8077449
Hey akshayxx can you help me out with this

How do you calculate the percentage for this program (count the wrong answer only once)

Here's the source.

#include <iostream>
#include <ctime>
#include <cstdlib>

using std::cout;
using std::cin;
using std::endl;

void congrats (int);
void regret (int);
int main()
{
int home, home1, home2, home3;
//int total, correct=0, wrong=0;
//double percentage;
//total = correct + wrong;
//percentage = (correct/total)*100;

srand ( time( 0 ));
cout << "Would You Like To Practice Your Multiplication Tables\n";
cout << "Please enter y to continue or n to quit: ";
home = (rand() % 10 );
home1 = (rand() % 10 );
cout <<"\nHow much is "<< home <<" times "<< home1 << "? : ";
home2 = 1 + rand() % 4;
if( answer1 == home * home1 )
congrats (home2);
else
regret (home2);
while ( answer1 != home * home1 ) {
cout << "? : ";
home3 = home * home1;
home2 = 1 + rand() % 4;
if(answer1 == home * home1 )
congrats (home2);
else
regret (home2);
}
cout <<"\nWould you like to continue, y/n: ";
}

//cout <<"Your Score is " << percentage <<"%" << endl;
return 0;
}

void congrats (int CongratPicker) {               switch ( CongratPicker ){                    case 1:                                   cout << "Very good! " << endl;                    break;                                   case 2:                                   cout << "Excellent! " << endl;                    break;                                   case 3:                                   cout << "Nice work! " << endl;                    break;                                   case 4:
cout <<"Keep up the good work! " << endl;          break;                                   }
}
void regret (int regretPicker) {
switch ( regretPicker ){                    case 1:                                   cout <<"No. Please try again. " << endl;          break;                                   case 2:                                   cout <<"Wrong. Try once more. " << endl;
break;                                   case 3:                                   cout <<"Don't give up! " << endl;
break;
case 4:
cout <<"No. Keep trying. " << endl;
break;
}
}
0

LVL 8

Expert Comment

ID: 8077585
in ur program . it doesnt let u leave the question .. if u have wrong answer it keeps u asking .. so u mean to say for all those answers that he cudnt give correct answer in first attempt .. shud be counted as wrong answers..
and for each question .. i shud count the 'wrong' only once ..even if he takes more than 2 attempt to solve it
0

LVL 8

Expert Comment

ID: 8077640
if that is the case .. here is your program with desired changes..

#include <iostream>
#include <ctime>
#include <cstdlib>

using std::cout;
using std::cin;
using std::endl;

void congrats (int);
void regret (int);
int main ()
{
int
home,
home1,
home2,
home3;
int total=0, correct=0, wrong=0;
char
unsigned
double percentage;
//total = correct + wrong;

srand (time (0));
cout << "Would You Like To Practice Your Multiplication Tables\n";
cout << "Please enter y to continue or n to quit: ";
{
total++;
home = (rand () % 10);
home1 = (rand () % 10);
cout << "\nHow much is " << home << " times " << home1 << "? : ";
home2 = 1 + rand () % 4;
if (answer1 == home * home1){
congrats (home2);
correct++;
}
else{
regret (home2);
while (answer1 != home * home1)
{
cout << "? : ";
home3 = home * home1;
home2 = 1 + rand () % 4;
if (answer1 == home * home1)
congrats (home2);
else
regret (home2);
}
wrong++;
}
cout << "\nWould you like to continue, y/n: ";
}
percentage=100*(double)correct/(double)total;
cout<<"total= "<<total<<endl<<"correct = "<<correct<<endl<<"wrong= "<<wrong<<endl;
cout <<"Your Score is " << percentage <<"%" << endl;
return 0;
}

void
congrats (int CongratPicker)
{
switch (CongratPicker)
{
case 1:
cout << "Very good! " << endl;
break;
case 2:
cout << "Excellent! " << endl;
break;
case 3:
cout << "Nice work! " << endl;
break;
case 4:

cout << "Keep up the good work! " << endl;
break;
}
}
void
regret (int regretPicker)
{
switch (regretPicker)
{
case 1:
cout << "No. Please try again. " << endl;
break;
case 2:
cout << "Wrong. Try once more. " << endl;
break;
case 3:
cout << "Don't give up! " << endl;
break;
case 4:
cout << "No. Keep trying. " << endl;
break;
}
}
0

Author Comment

ID: 8084609
Hey akshayxx help me out with this (GAME)
how do you clear the screen whenever the user wins and continue to play the game?

#include <iostream>                                                            // iostream header file
#include <windows.h>
#include <cstdlib>            // contains function prototypes for functions srand and rand
#include <ctime>            // contains prototype for function time

using std::cout;                                                            // program uses cout
using std::endl;                                                            // program uses endl
using std::cin;

void regrets (int);
void congrats (int);
int Game (void);
int rollDice( void );                                                      // function prototype

int main()                                                // function main begins program execution
{

enum Status { CONTINUE, WON, LOST };      // enumeration constants represent game status

int num, sum, wager;                                                      // declared
int home, home1;
int myPoint;                                                                  // declared
int bankBalance = 1000;                                                // initialize
int newbankBalance;

Status gameStatus;                  // can contain CONTINUE, WON or LOST
srand( time( 0 ) );                  // randomize random number generator using current time
sum = rollDice();                                                      // first roll of the dice

cout <<"You have \$1000 in the bank " << endl;

while (bankBalance = 1000)
cout <<"Please enter a wager: " << endl;
cin >> num;
if( wager > 1000 || wager < 0)
cout <<"Please bet a valid amount" << endl;
cin >> num;
Game ((int) sum);

home = 1 + rand() % 2;
if( gameStatus == WON )
congrats (home);
newbankBalance = bankBalance + wager;
cout <<"Your bankBalance is" << newbankBalance << endl;
else
regrets (home);
newbankBalance = bankBalance - wager;
if( newbankBalance = 0 )
cout <<"Sorry. You busted!" << endl;

int Game ( int sum ) {
switch ( sum ) {            // determine game status and point based on sum of dice

// win on first roll
case 7:
case 11:
gameStatus = WON;
break;
// lose on first roll
case 2:
case 3:
case 12:
gameStatus = LOST;
break;
// remember point
default:
gameStatus = CONTINUE;
myPoint = sum;
cout << "Point is " << myPoint << endl;
break;                                                                  // optional

}                                                                              // end switch

while ( gameStatus == CONTINUE ) {                              // while game not complete ...
sum = rollDice();                                                      // roll dice again

// determine game status
if ( sum == myPoint )                                                // win by making point
gameStatus = WON;
else
if ( sum == 7 )                                                // lose by rolling 7
gameStatus = LOST;

}                                                                              // end while

// display won or lost message
if ( gameStatus == WON )
cout << "Player wins" << endl;
else
cout << "Player loses" << endl;

return 0;                                                      // indicates successful termination

}                                                                                    // end main

// roll dice, calculate sum and display results
int rollDice( void )
{
int die1;
int die2;
int workSum;

die1 = 1 + rand() % 6;                                                // pick random die1 value
die2 = 1 + rand() % 6;                                                // pick random die2 value
workSum = die1 + die2;                                                // sum die1 and die2

// display results of this roll
cout << "Player rolled " << die1 << " + " << die2
<< " = " << workSum << endl;

return workSum;                                                            // return sum of dice

}                                                                                    // end function rollDice

return 0;
}

void congrats (int CongratPicker) {
switch (CongratPicker) {
case 1:
cout <<"Now's the time to cash in your chips!" << endl;
break;

case 2:
cout <<"Wow. You're so lucky!" << endl;
break;
}
}

void regrets (int SorryPicker) {
switch (SorryPicker) {
case 1:
cout <<"Oh, you're going for broke, huh?" << endl;
break;

case 2:
cout <<"Aw cmon, take a chance!" << endl;
break;
}
}
0

LVL 8

Expert Comment

ID: 8084714
>>>how do you clear the screen whenever the user wins and continue to play the game?

if you are on DOS/windows
use this function
clrscr();
0

Featured Post

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Written by John Humphreys C++ Threading and the POSIX Library This article will cover the basic information that you need to know in order to make use of the POSIX threading library available for C and C++ on UNIX and most Linux systems.   [sā¦
Container Orchestration platforms empower organizations to scale their apps at an exceptional rate. This is the reason numerous innovation-driven companies are moving apps to an appropriated datacenter wide platform that empowers them to scale at a ā¦
The goal of the tutorial is to teach the user how to use functions in C++. The video will cover how to define functions, how to call functions and how to create functions prototypes. Microsoft Visual C++ 2010 Express will be used as a text editor anā¦
The viewer will learn how to use the return statement in functions in C++. The video will also teach the user how to pass data to a function and have the function return data back for further processing.
Suggested Courses
Course of the Month10 days, 11 hours left to enroll