Code is not adding last defualt value - c++

Im writing an application for my intro to programming class and the objective is to
set up a simple program that prompts the user to enter a series of positive integer numbers between 50 and 100 (inclusive) using the keyboard. Your prompt should tell the user to enter a negative number to stop the input process.
As the user enters the numbers, you should keep track of the number of valid entries they have made (those that fall in the allowed range), and add up those numbers entries. You do not need to store more than the single entered number, the count, and the current total you are calculating.
Once the user completes the data entry, produce output similar to this:
A total of 5 values were entered.
The sum of those numbers is 127
make a program that will have one variable and it will retrieve the users
Here is the code I wrote
#include <cstdlib>
#include <iostream>
using namespace std;
int main(int argc, char *argv[]) {
int loop = 1;
int value;
int times = 0;
cout << "Enter a negavtive number to quit" << endl;
cout << "\nPlease Enter Any Number Between 50 - 100" << endl;
while (loop == 1) {
cin >> value;
times++;
value += value;
if(value < 0) {
cout << "You entered " << times - 1 << " numbers" << endl;
cout << "Total: " << value << endl;
system("PUASE");
return EXIT_SUCCESS;
}// end if statement
} //end while loop
system("PAUSE");
return EXIT_SUCCESS;
}
Here is the output
http://www.flickr.com/photos/62751645#N08/6286454476/
I think it may have something to do with the fact that I am using the int value to do two different tasks.
How might I go about fixing this?
revision
thanks to all of you for the "fix"
I add a new variable and it works like a charm, but now the math is not adding correctly
http://www.flickr.com/photos/62751645#N08/6286526294/in/photostream

There are a few problems, but the major one is this:
cin >> value;
This means "overwrite value with the number the user inputs", and of course if you do that you will never be able to store a sum inside value because it will be overwritten each time with the new number.
Solution: use another variable to keep the running total.
You also have a bug in that you do
times++;
value += value; // which as described above will not "stick"
before checking if value is negative. These operations should only be performed when value is not negative; otherwise, data entry should stop immediately and the negative number should not be taken into account for summing the total.

add a sum variable to hold the sum, you overwrite the input value in every loop iteration.
sum += value;

Don't use value to do two different tasks.
Have another variable called sum and accumulate the total there.
The way you're doing things you are writing over your sum every time the user enters a number:
cin >> value; // sum of previous values is overwritten!
Also there's another problem in that when the user enters a negative number you add that to the sum as well.

Your code does not check whether the values are in range (i.e. between 50 and 100). You can put a condition on the line where you do the addition as below:
if (value >= 50 && value <= 100)
sun += value;
Also, you can use 'value' to break the loop also.

Related

Why isn't my code running the whole program but not producing any errors?

I need to calculate the digits of a rational number that I get from the user.
The problem is that even though there is no errors in the code, the program running only part of the code. I'm working in Visual Studio.
int sumDigits(int a);
// main function
int main()
{
int ratioNum;
// Ask from the user to enter a rational number
cout << "Hello" << endl;
cout << "Please enter a rational number: ";
// Get the number from the user
cin >> ratioNum;
// Inform the user what is the sum of the digits
cout << "The sum of the digits are: " << sumDigits(ratioNum) << "." << endl;
return 0;
}
// Definition of function
int sumDigits(int a)
{
int digit = 0, sum = 0;
// As long as number is bigger than 0, continue
while (a > 0)
{
// Define a new verible - digit, as a number mudolo 10
digit = a % 10;
}
// kick out the units digit that we used
a / 10;
// Sum the digits of the number
sum = digit + a;
// Return sum to the main function
return sum;
}
You need a /= 10 instead of a / 10, and you need it inside the loop. Otherwise the loop will run forever because a never gets modified inside of it, so it can never become 0.
This will fix the infinite looping issue but the result will still not be correct. Why that is would be a different question though, and I'd invite you to learn proper debugging first (google how to debug C)! This will help you a lot more than copying a solution from here.
Your code isn't running the whole program because of these lines:
while (a > 0)
{
// Define a new verible - digit, as a number mudolo 10
digit = a % 10;
}
Inside the while loop, you're only assigning the value to the digit variable, but not changing the value of a, so the value of a always remains greater than 0. So your code gets stuck inside the while loop.
You should write
// kick out the units digit that we used
a /= 10;

C++ Loop - Finding smallest and second smallest value

I'm very very new to C++. Here I'm trying to write a program without any extra library. Using loops to find both the smallest value and the second smallest value from the user's inputs ( 0 is excluded and exits the program ).
Here is what I tried to do.
#include <iostream>
using namespace std;
int main()
{
int value=0;
int SmallestNumber=0;
int SmallestNumber2=0;
cout << "Enter number to find the smallest and second smallest(or 0 to exit): ";
cin >> value;
while (value != 0) {
if (value< SmallestNumber && value != 0 )
{
SmallestNumber = value;
}
else if (value<SmallestNumber && SmallestNumber2 >SmallestNumber && value != 0)
{
SmallestNumber2 = value;
}
cout << "Enter number to find the smallest and second smallest(or 0 to quit): ";
cin >> value;
}
cout << "Smallest number is: " << SmallestNumber << '\n' << endl;
cout << "Second Smallest number is: " << SmallestNumber2 << '\n' << endl;
return 0;
}
However, this program is not functioning properly. The smallest number finder works only if I input a negative value **, and the second smallest number value always outputs **0.
Since I'm very new to C++, I tried many other solutions, but this is what I can really think of.
Can somebody please tell me what is wrong with the program, and how I can correct it?
A million thanks! Please help me :'(
Thanks for answering my question!
I changed the initialization into this.
int value;
int SmallestNumber=0;
int SmallestNumber2=0;
but how do I initialize the smallest and the second smallest values..?
This is what I wanted my program to do
displaying the smallest and second smallest
50
1
61
93
-35
38
0
-35 smallest
1 second smallest
You start with a smallest value set to 0, so you will always get values only smaller than 0, that's why you have std::numeric_limits<int>::max().
Then for your second smallest, you are never checking against the current second smallest value, you are just checking against the biggest, which you now is going to work. So change this:
if (value>SmallestNumber2 && value != 0)
You should probably check value != 0 outside the main if statements as well. And as #Caleb reminded me, what happens to the previous largest value if it gets replaced?
Also, if you want to keep the same concept and do the algorithm "yourself" there is few things to change.
First the initial value of SmallestNumber and SmallestNumber2 need to be as high as possible otherwise the numbers saved can only be the one lower than your initial value. Therefore you can use INT_MAX.
Second, the second smallest number, need to be set in 2 cases :
when a new value is entered that is the second smallest
when a new smallest value is set, the old smallest value become the new second smallest.
Third there are a lot of unnecessary code here. You check too many time if value is not null which you know from the while condition. And you have code duplication with the cout/cin statement. Which is prone to mistakes.
Here is a version of what it could look like :
int value= INT_MAX;
int SmallestNumber=INT_MAX;
int SmallestNumber2=INT_MAX;
while (value != 0) {
if(value > SmallestNumber && value < SmallestNumber2)
{
SmallestNumber2 = value;
}
else if (value< SmallestNumber)
{
SmallestNumber2 = SmallestNumber;
SmallestNumber = value;
}
cout << "Enter number to find the smallest and second smallest(or 0 to quit): ";
cin >> value;
}
cout << "Smallest number is: " << SmallestNumber << '\n' << endl;
cout << "Second Smallest number is: " << SmallestNumber2 << '\n' << endl;
return 0;
ps : the version of #darune is a nicer solution.
You have no position at which the former smallest value becomes the second smallest value, which can't work.
Consider this code:
int value;
int smallest = std::numeric_limits<int>::max()-1;
int second_smallest = std::numeric_limits<int>::max();
while(true)
{
cin >> value;
if(value == 0) break;
if(value >= second_smallest) continue;
if(value == smallest) continue; // assuming that a double value does not change anything
if(value > smallest) // is between them
{
second_smallest = value;
continue;
}
//now the case left is that the new value is the smallest
second_smallest = smallest;
smallest = value;
}
Basic idea: first of all, rule out things and from then on, assume that they do not hold. We begin with the break case (I prefer a while(true) in such cases to have manual control over breaking it inside). Then we rule out the case in which nothing happens. The two cases left are that we are between the old values and that we are below both, and we handle them accordingly.
In your code, your ifs get to bloated. Makes it hard to keep track of what is done and what is to be done.
One example of this is that you have several times && value != 0 in your code despite this always being true due to the condition of your while.
In general, you should really learn how to use a debugger, or at least how to use helpful messages for debugging. Your mistake of setting your variables to zero at the start would have been easy to detect.
Other minor things: You should decide for a style and stick to it. It is quite unusual to name variables with a major first letter. Camel case is fine though, smallestNumber would have been fine. Second, try to avoid using namespace std;. This can lead to collissions. Rather use single members of std, like using std::cout;. It is not that problematic in a source file (very problematic in a header) but I recommend to do it consistently to keep a good routine.
A thing left to do in the code would be to later catch if the variables are still at std::numeric_limits<int>::max() and that minus one, signalling that there was no user input, and printing a fitting message instead of those values.
Note that as you read in an integer, negative values are legal, which might not be what you want, given that you use zero to break. You might want to add a case
if(value < 0)
{
cout << "Value was ignored due to being negative" << endl;
}
This is relatively simpel by using a a few different concepts, namely stdvector, stdstream and last stdsort
First off, the input part can be simplified to:
std::vector<int> numbers;
std::cout << "Enter multiple numbers, separated by spaces: ";
std::getline(std::cin, line);
std::istringstream stream(line);
while (stream >> number) {
numbers.push_back(number);
}
Now, since you would like the 2 smallest numbers, my suggested method would be to simply sort the vector at this point:
std::sort(numbers.begin(), numbers.end());
Now the list of numbers are sorted in ascending order and it is matter of printing the 2 first values. I leave that as an exercise to you.

Unexpected array behavior in basic averaging program

It seems like I always come here to ask silly questions, but here it goes. As of right now I am in my first compsci course and we are learning c++. I've had an extremely basic introduction to c before, so I had thought I'd go above and beyond my current assignment. Now I was doing this just to showboat, I felt like if I didn't practice my previous concepts they would eventually fade. Anyways, on to the problem! I was supposed to write some code that allowed the user to input their initials, and a series of exams. Now this was supposed to accomplish three things: average the exams, print out the entered exams, and print out their initials. Well, what was a simple assignment, got turned into a huge mess by yours truly.
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
int main()
{
string uInitials;
float avgExam = 0, tExam = 0;
int aExams[10] = {'0'};
int i, nExam = 0, cExam;
cout << "Enter your three initials!";
cin >> uInitials;
do
{
cout << "Enter your exam(s) to be averaged. Enter 0 when complete!\n";
cin >> cExam;
aExams[nExam] = cExam; //I used this before nExam was incremented, in order to get nExam while it was '0' That way the first exam score would be properly saved in the first space
nExam++;
tExam += cExam; //This is just to add all the exams up to later calculate the average
}
while(cExam != 0);
avgExam = tExam/(nExam - 1); //subtracted '1' from nExams to remove the sentinel value from calculations.
cout << "The average for initials: " << uInitials << " is: " << avgExam << endl;
cout << "This average was obtained using the following scores that were entered: \n";
for(i = 0; i < (nExam+1); i++)
{
cout << aExams[i] << endl; //Used a for loop to prevent redundancy
}
return 0;
}
The previous is my code, and the problem is that I'm getting output errors where it adds two '0's when I print out the list of entered exams. Also I feel like I made the whole do{}while() loop one huge clunky mess, so I'd like to refine that as well. If anyone could assist this poor, ignorant, beginner I would greatly appreciate it. Thank you for your time!
Some advice that i can give is for example in the 5th line there is no need
to put the 0 between ' ' and not even need to use the assign = operator.
You can initialize the array like this:
int aExams[10]{0};
Which will initialize all elements to 0,but can't be used for other value.
For example you won't have all the elements with value 1 if you write
int aExams[10]{1};
If your intention to initialize all elements in an array is with value other than 0 you can use fill_n(); function.
fill_n(aExams, 10, 1);
The first argument is the name of the array, the second is up-to which element you want to be initialized with the third argument, and the third is the value you want all elements to have.
Do not leave uninitialized variables like in line 6 with cExam and i variables. Initialize it like cExam=0; (copy-assign initialization) or cExam(0); (direct initialization). The latter calls the constructor for int built-in type.
A negative i see in your do-while loop is that you do not make sure that the user will enter under 10 exams,bad things will happen if the user tries to input 15 exams in an array that can hold only 10.
Just change the while to something more like this:
while( cExam != 0 && (nExam<10) );
You can also write the first two lines of the do-while loop outside the loop.
It is needed only once to tell the user that to stop the loop he/she needs to enter 0. There is no need to tell them this on every iteration plus that you will have a good performance benefit if you put those two lines outside the loop.
Look here how i would write the code and ask if you have any questions.
http://pastebin.com/3BFzrk5C
The problem where it prints out two 0's at the end of your code is a result of the way you wrote your for loop.
Instead of:
for(i = 0; i < (nExam+1); i++)
{
cout << aExams[i] << endl; //Used a for loop to prevent redundancy
}
Use:
for (i = 1; i < (nExam); i++)
{
cout << aExams[i - 1] << endl; //Used a for loop to prevent redundancy
}

Function call passing incorrect number (C++ 11)

I'm currently working on a project that is meant to teach the usage of functions in C++. I've worked with python in the path and have a reasonable understanding of functions in code (or so I thought) but for some reason I'm getting some alarming errors when I pass values through to my current function.
This is the entire code, my problem lies within the narc_num(153,3) call made in main. I added some cout statements into the narc_num function to see why I was getting wonky results and found that the num argument was getting passed as a completely different number. Why would this be?
#include<iostream>
#include<cmath>
using std::cin;
using std::cout;
using std::endl;
/*
Function: order_parameters
Purpose: If first is greater than second reassign the values so second is greater than first
Algorithm:
1.Pass arguments as references to first and second
2.if statement that runs if first is greater than second
3.within if statement switch values using a temporrary variable
4.if else doesnt run nothing happens
*/
void order_parameters(long & first,long & second)//passing long references of first and second
{
if(first > second)//start if when the ref to first > ref to second
{
long temp; // initialize temp
temp = second; //value temp is = to second
second = first; //second will now be first, temp is still = to first though as well
first = temp; //second is now set = to temp, which is first. dat swap
}//end if
}
/*
Function: narc_num
Purpose: check if a number is indeed a narcisstic number
Algorithm:
1.Pass num, the number to be checked, and power, the order the number will be checked against
2.use a while loop to iterate through digits of number
-mod10 takes the last digit, the digit is raised to the power passed as an argument
-the value found is added to the total
-the number is then divided by 10 to remove the last digit, reiterates again.
3.the total found by the while loop is checked against the number passed an as argument
-if the total is equal to the number it is narcisstic.
*/
bool narc_num(long num, long power)// will return a boolean value, passing num and power integers
{
//split all digits into seperate numbers, add together raised to power
long total = 0,digit,num_copy;
bool narc = false; //value to check if number is narcissitic or not
num = num_copy;
cout << "number"<< num << endl;
while(num > 0)
{digit = num%10;
cout <<"digit" << digit << endl;
total += pow(digit,power);
cout <<"total" << total << endl;
num /= 10; //divides by 10 to go to the next digit down
}
if (total == num)
narc = true;
cout << total << endl;
return narc;
}
long check_range(long first,long last,long power)
{
bool check;
order_parameters(first,last); //make sure parameters are in correct order
for(first;first == last;first++);//iterate through all numbers from first to last
{check = narc_num(first,power); //check = True if narc number otherwise false
if (check == true)
{cout << first <<" is a narcissistic number of order " <<power<< endl;
};
cout << "gothere"<< endl;
};
cout << "dick canoe"<< endl;
}
int main(){
narc_num(153,3);
}
You are assigning the value of num_copy (an uninitialized long) to num near the top of the narc_num function. I believe you meant to assign num_copy the value of num. This is probably the cause of your unexpected results.

Why am I not getting correct value when attempting to find the average value of n elements?

I'm going through an O'reilly programming book, and one of the questions is to "write a program to average n elements".
This is the code that I have:
#include <iostream>
int n; //number of numbers
int number; //the numbers to be averaged
float avg; //the average of the elements
int counter; //iterator
int main()
{
std::cout << "Please enter the number of elements you want averaged: ";
std::cin >> n;
avg = 0;
counter = 0;
while (counter < n)
{
std::cout << "enter number: ";
std:: cin >> number;
number += number;
++counter;
}
avg = number/n;
std::cout << "Average of your " << n << " elements is: " << avg;
return 0;
}
For some reason, when I try to use 3 values of 3, i get a average of 2. I'm certain there's a problem with my declaration of "number" because it doesn't take the value of each number I enter and add it with each other. Could someone help me fix my mistake. I want my code to work for the general case; not just 3 elements. Thanks.
Two problems.
1)
std:: cin >> number;
number += number;
I assume that number is meant to be the sum of all numbers, but here you are also using it to store a single number, and when you assign a value to a variable it overrides what was already there. You must use two different variable names, such as
std:: cin >> number;
sum += number;
2)
number/n; is integer division since number is integer and n is integer. Integer division rounds down. Having the result of the expression assigned to a float is not enough - it is too late, the expression was already computed as integer division.
You want float division, so do sum/(double)n for example.
You read the number 3. The you say number += number, which makes it 6, and increment counter to 1. Then you read number again, it becomes 3, add it again, again 6, increment, counter. The third time, the same happens.
So you get 6/2 which is 3.
You read the input into number, but you aren't actually keeping a total of all the numbers entered which is what you really need for this problem.