Wrong output for sum of digits using loop c++ [closed] - c++

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
i was required to make a program that asks users for a positive integer value, while the program uses loop to get the sum of all the numbers from 1 through n (user input). So lets say the user enters 5, the program would do 1+2+3+4+5 = 15
this is the code so far
#include <iostream>
using namespace std;
int main()
{
int number; int sum = 0; // variables
cout <<"Please input an integer greater than zero\n"
<<"Please refrain from using a negative integer." <<endl;
cin >> number; // user input
for (int i=1; i <= number; i++) // looping statement
{
sum = sum + i; // formula that takes user digits and finds sum
cout << sum;
}
My issue is that when i compile the program,for example, i enter 3, the program's output would be "136"
i want it to say 1+2+3 = 6 or much something like "the sum of the integer is 6" i just want to show the total of the value.
I'm new in c++ any help would be appreciated. Thank you!

You are writing cout << sum inside your loop. That means you get one number output every time your loop runs (it's really writing 1 then 3 then 6 which gets all smushed together and comes out as 136). Move that statement after the following }.

Here's how you can get your 1+2+3=6 output:
#include <iostream>
using namespace std;
int main()
{
int number; int sum = 0; // variables
cout <<"Please input an integer greater than zero\n"
<<"Please refrain from using a negative integer." <<endl;
cin >> number; // user input
for (int i=1; i <= number; i++) // looping statement
{
sum = sum + i; // formula that takes user digits and finds sum
if ( i == number )
cout << i;
else
cout << i << "+";
}
cout << "=" << sum;
}

Related

c++ numbering the inputs for simple program

so im new to c++ and im doing a program that takes user inputs for any amount number say 5 so i will get 5 inputs from user and calculate the sum of it ,i did make the program but what i want for the output is say
"Enter Input 1:xx
"Enter Input 2:xx
so on and on as the user input say 5 so it goes on for 5 times however my program takes the user input and i enter it, it dosnt say enter input 1 ,so i want to show the enter input 1 enter 2 part hope someone can help me with this sorry for my poor explanation
#include<iostream>
using namespace std;
int main() {
while (true) {
// prompts the user to ask how many inputs they want
int x;
cout << "Enter input : ";
cin >> x;
// If x = -1 dont repeat the loop
if (x == -1)
break;
// get the input from above and calculate the total of the input
int sum = 0;
for (int i = 0; i < x; i++) {
int value;
cin >> value;
sum += value;
}
// Output the total
cout << "Output total: " << sum << endl;
}
system("pause");
return 0;
}
Okay to start out, there are times when to use break and there are times not to. This scenario is not meant for them. Although, I used one in my code I did it because I am rushing. I would recommend to take the code snippet, learn from it, and see how to optimize it :)
Also, just for future purposes its important to understand your task at hand and be able to communicate it well so others can help debug and answer your question.
Heres what I think your question is:
"I want to make a program in cpp that allows the user to first submit how many numbers they would like to input. From there I would then ask them for the indicated number of inputs. After gathering all inputs I will then add those numbers together and output the sum. If at any point they decide to type in -1, I will stop asking for inputs and give their sum on the spot."
#include<iostream>
using namespace std;
int main() {
bool runProgram = true;
cout << "Hi welcome to my sum calculator program!\n";
cout << "This program will prompt you for a number of inputs and then calculate the total of them.\n";
cout << "If you no longer want to be prompted for numbers at any time type in -1!\n";
cout << "Press enter to begin!\n";
cin.get();
while (runProgram) {
// prompts the user to ask how many inputs they want
int x;
cout << "How many inputs?\n";
cin >> x;
// If x = -1 dont repeat the loop
if (x == -1){
runProgram = false;
}else{
// get the input from above and calculate the total of the input
int sum = 0;
int val = 0;
for (int i = 0; i < x; i++) {
cout<< "Input #" << i+1;
cin >> val;
if(val == -1){
runProgram = false;
break;
}
sum += val;
}
// Output the total
cout << "Your Output total is " << sum << endl;
}
}
system("pause");
return 0;
}

Sum of first and last digit of a number [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
The problem is to find sum of first and second digit of a number.
If number is smaller than 10 then print number itself.
I wrote this code but i don't know why output is wrong.
#include <iostream>
using namespace std;
int main()
{
int t,a,n,l;
cin>>t;
while(t--)
{
cin>>n;
if(n<10)
{
cout<<n;
}
else
{
a=n%10;
l=n/10;
cout<<a+l<<endl;
}
}
return 0;
}
The reason your solution is wrong because n/10 won't give you the first digit :)
If this is for a question for competitive programming(since you're taking in t test cases), I'll suggest taking input as a string assuming that input is always a valid int.
std::string s;
cin >> s;
if (s.size() == 1) std::cout << s << std::endl;
else std::cout << int(s.front() - '0') + int(s.back()-'0') << std::endl;
extracting of required digits is wrong in your solution.
Please find solution for adding first and last digit of a number at
https://onlinegdb.com/Byro9hCMI or below:
its small and hence pasting it here as well:
#include <iostream>
using namespace std;
int main()
{
int first, last, number;
cin>>number;
first = number % 10;
while((number = number/10)>0)
{
last = number;
}
cout << endl << first+last << endl;
return 0;
}
Two Add first two digit (unit and tens)at https://onlinegdb.com/SJXNThAzI or below:
#include <iostream>
using namespace std;
int main()
{
int first, second, number;
cin>>number;
first = number % 10;
number = number/10;
second = number %10;
cout << endl << first+second << endl;
return 0;
}

c++, ask the user to input a set of numbers to sum (unknown number of input), however numbers wouldn't add up

I want to write a simple program where I ask the user to input a set of numbers to sum. The user can input an unknown number of numbers.
Here's my code:
#include <iostream>
using namespace std;
//ask the user to input a set of numbers to sum (unknown number of input)
int main (){
int sum = 0, value = 0;
while (cin >> value){
sum += value;
cout << "sum is " << sum << endl;
return 0;
}
}
However, when I input several numbers, the result always equal to the first number, not the sum of all numbers entered. As in:
5 6 7 8
sum is 5
What I am doing wrong?
The problem is return 0. Put it outside of the while block.
You are doing it wrong. You must have to put the print method outside of the loop and the return too.If you want user to terminate at any time he wants then you need to take input at an specific keyword or any other keyword other than the data type(like char at place of integer) , so that it will terminate the loop.
#include <iostream>
using namespace std;
int main (){
int sum = 0, value = 0;
/*press any key other than number to terminnate*/
while (cin >> value){
sum += value;
}
cout << "sum is " << sum << endl;
return 0;
}

How to Create a Linear Searching Algorithm easier than what my textbook provides [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I need help on something. The textbook I am reading that teaches c++ does not do a good job at teaching students the linear searching algorithm. As a result I have tried recreating the algorithm without using any functions. The problem is, the code I have written seems to have some bugs. Just to note I am using the Microsoft Visual Studios 2013 IDE. As a result, can anyone please tell me what is wrong with my code? Here is the algorithm I have written in English. The Algorithm will not show the variable and array definitions but the source code will.
P.S. This is not a homework assignment. It is just for fun :)
P.S. For some reason the code formatting was very glitchy.
Algorithm:
Ask the user to enter a number
Create a for loop
Inside the for loop traverse through each element in the array and compare
it with the number the user inputted
If the element in the array is EQUAL to the number the user inputted, display a message saying it was found
If the element in the array is NOT EQUAL to the number the user inputted, display a message saying it WASN'T found.
code:
#include <iostream>
using namespace std;
int main()
{
// Create the array
int array[6] = {1,2,3,4,5,6};
int number;
// Ask the user to enter a number
cout << "Enter a number: ";
cin >> number;
// Create a for loop to traverse through each number in the array
//to see if it equals the user inputted number
for (int i = 0; i < 6; i++)
{
if (number == array[i])
{
cout << "Number Found: " << array[i] << endl;
}
else if (number != array[i])
{
cout << "Number Not Found!" << endl;
}
}
return 0;
}
The output if I entered 3 would be the following:
Number Not Found!
Number Not Found!
Number Found: 3
Number Not Found!
Number Not Found!
Number Not Found!
your logic output decision for each iteration. But it seems you've to output your decision only once.
So, for this reason declare a boolean variable globally and set false as a value of this value.
For each iteration check it is found. if found then set the boolean value to TRUE.
for Final output check global boolean value either true or false and print output
Remove the cout from inside the loop. Use a flag, ie if the number is found, set it to true and then write the print statement outside using an if.
int flag=0;
for(int i=0;i<6;i++){
if(number==arr[i])
flag=i+1;
}
if(flag) cout<<"found at position"<<flag;
else cout<<"Not found";
PS: Buy a better textbook
Easier and more fun:
#include <iostream>
#include <vector>
using namespace std;
int main() {
int number;
vector<int> nums{1,2,3,4,5,6};
cout << "Find a number: ";
cin >> number;
for_each(cbegin(nums), cend(nums),
[&](const int& x)
{
if(x == number)
cout << "found " << x << endl;
else
cout << "could not find " << endl;
});
}
But a good starting point for linear search would be:
template<typename I, typename T>
I find (I first, I last, const T& val)
{
while (first != last) {
if (*first == val) return first;
++first;
}
return last;
}

C++ For-Loop Gets stuck when entering new variables [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 8 years ago.
Improve this question
I'm new to C++ and trying to create a lottery game for a college project.
I have a for loop to check that there are no duplicate numbers in the array entered. This works absolutely fine when you take out the section of code to produce the random numbers.
As soon as I add the random number section back in, the for loop just gets stuck. It will continuously tell me that i have already entered the number when its trying to store the first number.
I have attached all of my code, apologies if you don't need it all.
#include <iostream>
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
using namespace std;
//int loto[6];
int main()
{
int numbers[6];
//void rand_num(int loto[6], int count);
int loto[6]; //used to store the loto numbers
//int james = 0;
//int l,j; //used in checking any duplicated
srand(time(0));
for(int count=0; count<6; count++)
{
loto[count] = (rand()%49)+1;
cout << loto[count] << endl;
}
//declares the variable i to increase each time a number is entered.
//this will only go as high as 6
for(int i=0;i<6;i++)
{
cout<<" " << i<<" : Please enter your lottery numbers: "<<endl;
cin>>numbers[i];
if ((numbers[i] >= 50) | (numbers[i] == 0))
do
{
{
//checks to see if the first number entered is above 50 or = to 0 and rejects it
cout << "The Number must be between 1-49, please select again. " << endl;
cin >> numbers[i];
}
}
while ((numbers[i] >= 50) | (numbers[i] == 0));
//----------------------------------------------------------------------------
//this section of code is a loop within a loop to check the number entered against all numbers already stored.
//makes l the same as i effectively
for(int l=0;l<6;l++)
{
//makes j one more than l
for(int j=l+1;j<7;j++)
{
if( numbers[l] == numbers[j] )
do
{
{
cout << "Number has already been chosen, please re-enter number " << endl;
cout << endl;
cin >>numbers[i];
//checks the number that is re-entered is not <50 or = 0
//if so it rejects it and asks for another as above.
if ((numbers[i] >= 50) | (numbers[i] == 0))
do
{
{
cout << "The Number must be between 1-49, please select again. " << endl;
cin >> numbers[i];
}
}
while ((numbers[i] >= 50) | (numbers[i] == 0));
}
}
while (numbers[l] == numbers[j]);
}
}
}
//----------------------------------------------------------------------------
//this displays the numbers that have been chosen.
cout << "Your Numbers are: " << endl;
for (int i = 0; i<6; i++)
{
cout << " " << numbers[i];
}
return 0;
}
I'm not sure this is the real problem but it is a bug. Try to correct it and see if it helps.
for(int l=0;l<6;l++)
{
//makes j one more than l
for(int j=l+1;j<7;j++)
{
if( numbers[l] == numbers[j] )
The inner-loop will reach j==6 so you will access outside the array. The outer-loop shall have 5 as the limit and the inner-loop shall have 6 as the limit.
EDIT:
After looking a bit more at your code I can see that you are using numbers[] without initializing it. The two nested for-loops will compare all elements in numbers. But if the user have only entered 2 numbers, the rest is unitialized and can give unintended results.
Further - you don't need to check all elements againt all elements every time. Just check the newly entered number (index by i) with all previous numbers.
Finally you will probably need something like:
if (!(cin >> numbers[i])) {
cout << "Please enter numbers only." << endl;
cin.clear();
cin.ignore(10000,'\n');
}
to handle input not being integer, e.g. "text"
And to minor things:
You should also check for negative numbers.
You are using | instead of ||. It will work fine but || seems more correct as it is the logical OR (while | is a binary OR).