Counting how many times variable has changed - c++

I have to write the program, when after terminating infinite while loop "while(cin>>a)" by, let's say "-1", program says me how many times value increased. For input "0 0 2 2 3 4 8 8 8 -1" it should print "4". First part isn't problem, but I have no idea how to count how many times it had changed over time. Any tips? Thanks a lot.

You should use counters which will basically increase each time your value increases. Check the code bellow:
int value, highestValue, counter = 0, counter2 = 0;
do{
cout << "Enter the value: ";
cin >> value;
if(counter2 == 0){
highestValue = value;
}
if(value > highestValue){
counter++;
highestValue = value;
}
counter2++;
}while(value != -1);
cout << "The number increased " << counter << " times!\n";
The second counter (counter2) is required in the first if statement to store the first value you enter as the highest value.

int p = -1, k, a, b;
while( cin >> a ) //infinite loop
{
if ( k != a )
p++;
b = a - k;
if(a=-1)
exit(0);
k = a;
}
cout << "value increased by" << b;
cout << "number of times it has changed over time = " << p;

Related

Why do we use if(i==n-1) condition when we don't find the searched item in the array? How does it even work?

int main()
{
cout << "Enter the number whose index no. you want to find " << endl;
cin >> a;
for (int i = 0; i < n; i++)
{
if (numbers[i] == a)
{
cout << "Its index no. is " << i << endl;
break;
}
if (i == n - 1)
{
cout << "No. not found in Array" << endl;
}
}
return 0;
}
What's the use of the if(i==n-1) in this? How is it functioning? Please help!
Since your loop will go from 0 to n-1 and if the value is not there at the last element also, then the code is printing the message.
This loop:
for (int i = 0; i < n; i++)
{
if (numbers[i] == a)
{
cout << "Its index no. is " << i << endl;
break;
}
if (i == n - 1)
{
cout << "No. not found in Array" << endl;
}
}
is just a bad code that can confuse readers.
It could be rewritten the following way:
int i = 0;
while ( i < n && numbers[i] != a ) i++;
if ( i != n )
{
cout << "Its index no. is " << i << endl;
}
else
{
cout << "No. not found in Array" << endl;
}
That is if the number is found in the array that is if the condition numbers[i] != a evaluates to false then it means that the target number is at the position i. Otherwise all elements of the array will be checked and in the case i will be equal to n because the valid range of indices is [0, n - 1).
In the original loop if the target number is found within the for loop then the corresponding message is outputted and the control exits the loop due to the break statement. Otherwise if it is the last element of the array (that is with the index n - 1) and it is not equal to the target number then it means that there no more elements in the array to compare. This iteration when i is equal to n - 1 is the last iteration so the element in the array that is equal to the variable a is not found.

How to assure the loop is entered (C++)

My professor is saying that The while loop runs provided n>=1. But I did not put any value into the variable n so depending on its “default” value, the loop may not be entered. And I'm not sure how to fix what he is talking about!?
#include <iostream>
using namespace std;
int main()
{
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(2);
int n, count;
double sum;
while (n >=1)
{
cout << "Enter a positive integer N (<1 to stop): ";
cin >> n;
sum = 0;
for (count = 1; count <= n; count++)
sum = sum + (1.0/count);
cout << "Sum = " << sum << endl;
}
cout << "Bye! ";
return 0;
}
Here is the line where n is declared
int n, count;
In this case the value of n is unspecified as it is left uninitialized. You should initialize it
int n = 1;
If you always want a loop to run at least once then you want a do...while(); loop. It will always enter the loop on the first iteration and execute the loop body then it will check the while condition to determine if it loops again or exits. A do...while(); has the form of
do
{
statements
} while (condition);
In this case it would save you from having to initialize n before you get the input from the user.
In this case though that doesn't seem like exactly what you want as you want nothing to happen if the user enters a number less than 1. One way you can solve that is to put your output and input into the while loop along with the check for n. This will stop anything from happening if the user enters less than 1 but still allowing you to prompt the usr and get the input on each iteration.
while (cout << "Enter a positive integer N (<1 to stop): " && cin >> n && n >= 1)
{
sum = 0;
for (count = 1; count <= n; count++)
sum = sum + (1.0 / count);
cout << "Sum = " << sum << endl;
}
The problem is that n has not been initialized. Unlike in other languages like Java or C#, primitive variables do not have any pre-defined "default" value. The simply occupy whatever stack space was there previously; for all intents and purposes, the default value of uninitialized variables can be considered "random".
To fix this, simply initialize the variable before entering the loop.
n = 1;
Set n to a value greater than or equal to 1 so the loop is guaranteed to enter. Since you aren't setting it yourself, the default value can be something less than 1 meaning that the look has a chance, but isn't guaranteed to fire.
int n = 1
Also, you should set count = 0 in your for loop, because if n and count is equal to each other, the for loop automatically breaks and doesn't execute at all, leaving sum at 0.
To make sure your dividing by 0, set count to count + 1.
for (count = 0; count <= n; count++)
sum = sum + (1.0 / (count + 1) );
You need simply to use another kind of loop that is the do-while loop. For example
do
{
cout << "Enter a positive integer N (<1 to stop): ";
cin >> n;
sum = 0;
for (count = 1; count <= n; count++)
sum = sum + (1.0/count);
if ( n > 0 ) cout << "Sum = " << sum << endl;
} while ( n > 0 );
cout << "Bye! ";
And instead of the declaration
int n, count;
you should use declaration
unsigned int n, count;
You could else check whether the input is valid. For example
if ( !( cin >> n ) || n == 0 ) break;
Taking this into account you could use also the following kind of loop
while ( true )
{
cout << "Enter a positive integer N (<1 to stop): ";
unsigned int n;
cin >> n;
if ( !( cin >> n ) || n == 0 ) break;
sum = 0;
for (unsigned int count = 1; count <= n; count++)
sum = sum + (1.0/count);
if ( n > 0 ) cout << "Sum = " << sum << endl;
}
cout << "Bye! ";

How to check how many times a number has been entered

I'm trying to solve one of the questions on a task sheet I've been received, to help me further in my understanding of C++ code from my class.
The question is (and I quote):
Write a program that:
Asks the user to enter 10 numbers between 1 and 5 into an array and displays the array on screen
Creates a second array of size 5 and fills it with zeros
Counts how many 1s, 2s, , … 5s have been entered into the first array and stores this number in the second array.
Displays the second array as shown in the example below.
The problem is how to go about checking how many times a number was entered. I was thinking of a for loop, but the way I wrote it is fundamentally incorrect, so I find myself struggling to see the mistake I am having. Perhaps I am missing something simple? Any help would be great.
Here is my (terrible) for loop attempt, so you can see my error.
#include <iostream>
#include <windows.h>
using namespace std;
int main()
{
int input[10];
const int MAX_NO = 5;
int COUNT[5] = { 0,0,0,0,0 };
int count = 10;
for (int i = 0; i < count; i++)
{
cout << "Please enter a number for value " << i + 1 << " :";
cin >> input[i];
while (input[i] < 1 || input[i] > 5)
{
cout << "Error: Enter another number between 1 and 5: ";
cin >> input[i];
}
}
cout << endl << "You entered ";
for (int i = 0; i < count; i++)
{
cout << input[i] << " ";
}
cout << "\n";
// show how many times 1 number appears
for (int i = 1; i <= 5; i++)
{
if (input[i] == i)
{
COUNT[i]++;
}
}
for (int i = 0; i < MAX_NO; i++)
{
cout << i + 1 << " appears " << COUNT[i]
<< " times in the input" << endl;
}
cout << endl;
system("pause");
return 0;
}
Put
COUNT[ input[i]-1 ]++;
in your first loop (after validation). Once you do that, you don't need a second loop to tally up the results.
This works from the inside out by first getting what input[i] is, then using it to modify the (input[i]-1)'th location in the COUNT array. If the user enters 4 on the first run of the loop, then i == 0 and input[i] == 4. Since arrays are 0-based, it will increment COUNT[input[i]-1] which in this case is COUNT[4-1] == COUNT[3].
After your initial loop runs the number of 1's will be in COUNT[0], the number of 2's will be in COUNT[1] and so on.
#include <iostream>
#include <windows.h>
using namespace std;
int main()
{
//declare a constant values
int input[10];
int count = 10; //all constant MUST be in capital letters
//second array filled with zeros
const int MAX_NO = 5;
int COUNT[5] = { 0, 0, 0, 0, 0 };
//ask user for 10 input values
for (int i = 0; i < count; i++)
{
cout << "Please enter a number for value " << i + 1 << " :";
cin >> input[i];
//check if input numbers are between 1 and 5 inclusive
while (input[i] < 1 || input[i] > 5)
{
cout << "Error: Enter another number between 1 and 5: ";
cin >> input[i];
}
/* show how many times 1 number appears.
this section should be in the main loop which would enable the program to check how many times a
number is entered so that it is stored in the second array. changed i to secondCount because this is the counting index of the second array not the first which you've called i (one of the reason you'd all zero as output when u ran your code)*/
for (int secondCount = 1; secondCount <= MAX_NO; secondCount++)
{
if (input[i] == secondCount)
{
COUNT[secondCount-1]+= 1; //use minus 1 from i and increment. += 1 is the same as COUNT++
}
}
}
//display number entered in the first array
cout << endl << "You entered ";
for (int i = 0; i < count; i++)
{
cout << input[i] << " ";
}
cout << "\n";
//display how many times a number is entered.
for (int secondCount = 0; secondCount < MAX_NO; secondCount++)
{
cout << secondCount + 1 << " appears " << COUNT[secondCount]
<< " times in the input" << endl;
}
cout << endl;
system("pause");
return 0;
}
OUTPUT:
Please enter a number for value 1 = 1
Please enter a number for value 2 = 1
Please enter a number for value 3 = 1
Please enter a number for value 4 = 2
Please enter a number for value 5 = 3
Please enter a number for value 6 = 2
Please enter a number for value 7 = 4
Please enter a number for value 8 = 4
Please enter a number for value 9 = 3
Please enter a number for value 10 = 2
You entered: 1 1 1 2 3 2 4 4 3 2
1 appears 3 times in the input
2 appears 3 times in the input
3 appears 2 times in the input
4 appears 2 times in the input
5 appears 0 times in the input
for (int i = 1; i <= 5; i++)
{
if (input[i] == i)
{
COUNT[i]++;
}
}
Let's examine what this is doing. It starts by checking input[1]. (This should be input[0] as array indices start at 0). Then it checks if input[1] is equal to 1. If it is, then it increments COUNT[1].
Next, it checks input[2]. Then it checks if input[2] is equal to 2. If it is, it increments COUNT[2]. And so on until it has gone through input[5].
Do you see the problem with this? You're only checking the first 5 inputs and only checking them against a single value.

opening stream using a 2d array

Can anyone fix this sample code that will print a file in 2D array. Here is the code and the output.
while (!file.eof())
{
int counter =0;
file>>n;
cout<< setw(4)<< n << " ";
if (counter == 5)
{
cout << endl;
counter = 0;
counter ++;
}
}
}
The output is not in table form.
The output is:
Index Size Weight (lb/ft) Diameter (in) 0 2 0.167 0.250 1 3 0.376 0.375 2 4 0.668 0.500 3 5 1.043 0.625 4 7 1.502 0
6 9 2.670 1.000 7 12 3.400 1.128 8 14 4.303 1.270 1.270
Press any key to continue . . .
Two options:
Define coutner as static
while (!file.eof())
{
static int counter =0;
file>>n;
cout<< setw(4)<< n << " ";
if (counter == 5)
{
cout << endl;
counter = 0;
counter ++;
}
}
}
or have it define external to the while loop:
int counter = 0;
while (!file.eof())
{
file>>n;
cout<< setw(4)<< n << " ";
if (counter == 5)
{
cout << endl;
counter = 0;
counter ++;
}
}
}
If you define it and initialized it to 0 in ever iteratoin of the while loop - it will never reach 5 to print endl;
It seems to be that not only the counter is initialized in every loop, as others pointed out before me, but moreover, it is never actually increased. The only increase I see is within the condition that it is equal to five. As it is never increased outside the condition, it never reaches five (even if it is declared as static or outside the loop), hence the condition is never met.
You have an uneven number of opening and closing curly braces, too.
I am not exactly sure what you want to achieve. If you want a line break after every fifth iteration, the following should work:
int counter = 0;
cout << setw(4) // suffice to set once
while (!file.eof())
{
file >> n;
cout << n << " ";
if (++counter == 5) // increase here before checking condition
{
cout << endl;
counter = 0;
// do not increase here again
}
}

C calculating sum correctly

I can get the sum every time the user inputs an integer until either a negative number or non-integer is inputted. Problem is my sum calculations are off. I.E user putting 1000; sum outputs 1111, then user inputs 2000, it adds up to 3333. Just any advice is appreciated. I'll still experiment around with my coding.
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
int j , i = 0, k = 0,number;
double sum = 0;
cout << "Enter Positive integer number: ";
while(cin >> number)
{
cout << endl;
if( number < 0)//test if the number is negative
{
cout << "Ending program since user has input a negative number" <<endl;
break;
}
int temp = number;
int p = 1;
while( temp > 0) //counting number of digits
{
sum = sum+temp; //Sum attempt.
temp /= 10;
p *= 10;
i++;
}
cout << sum << endl;
j = i % 3;
p /= 10;
while( i > 0 )//display integer number with 1000 seperator
{
//this is giving me error
cout << char ((number/p) +'0');
number %= p;
p /= 10;
i--;
k++;
j--;
if ((k % 3 == 0 && i > 0)||(j == 0 && i > 2) )
{
cout <<",";
k = 0;
}
}
cout << endl << endl;
cout << "This program will exit if you input any non-integer characters\n";
cout << "Enter another integer number: ";
}
return 0;
}
It looks like you're trying to output an integer number with commas inserted at 1000 boundaries. ie: 1000000 would be displayed as 1,000,000.
This being the case, the easiest way to approach it might not be involving maths but simply to get a string representation of the int (atoi() for example) and count through that. From the back, count forward three chars, insert a comma, repeat until you run out of string.
The specifics of string handling are left as an exercise for the reader - looks like it's his homework after all. ;-)