i am confused about how does this code flows especially after inputtedin the set of integers.
for example how will the input be stored and then compared to find the largest among the set?
#include <iostream>
using namespace std;
int main()
{
int n, num, max, k=1;
cout << " Enter how many integers " << endl;
cin >> n;
cout << " enter " << n << " integers: "; // where input be stored
cin >> max; // this will input the last number right?
// if i entered 50 55 60 where they will be stored dont i need to store them in in 3 seprate places
while (k<n)
{
cin >> num; // what is the function of this line? from where the input will be
if (num > max)
max = num;
k++;
}
cout << " largest integer is :" << max << endl;
return 0;
}
Let's walk through this.
Let's consider the case the user selects n >= 1. (note also k = 1).
We first need the user to enter one number.
cin >> max;
We say that this number is the max, we don't know if it's true or not but we make this assumption.
We then read in integers while k < n is true.
while (k < n)
{
cin >> num;
if (num > max)
max = num;
k++;
}
So, we read a number into num (which we declared outside the while loop).
We then check if this number is greater than our assumption that the first number was the biggest, if it is we reassign max to be equal to num.
We then increment k.
We do this until we have read in n integers.
Resulting in max being the largest number we entered.
As for storage, we're not needing to store anything, inside the scope of the while loop we can do the check if the number is larger than max or not, if it wasn't we just discard it with the next iteration.
It doesn't store the entire set of numbers read.
It compares each new one entered to the current maximum. The initial maximum value is set to the first number read.
Problem statement of this program will be like : You are given n integers. Now you have to print the largest integer among all these integers.
cin >> max will take only one integer as input. max will hold the value.
cout << " enter " << n << " integers: "; will print this output in the console. For example, if value of n is 2, then this will print: enter 2 integers:
Look in the comment for further details:
#include <iostream>
using namespace std;
int main() {
int n, num, max, k = 1;
cout << " Enter how many integers " << endl; // print
cin >> n; // number of integer to input;
cout << " enter " << n << " integers: "; // print how many integers to enter as input
cin >> max; // input for 1st integer, assume it is the maximum integer
// this while loop will take input of the remaining n-1 intergers
// initially k=1, while loop will run until k is less than n
// while loop will run for n-1 times
while (k < n) {
cin >> num; // input for 1 integer
if (num > max) max = num; // if this input integer 'num' is greater than 'max', then update 'max'
k++; // increment 'k'
}
cout << " largest integer is :" << max << endl; // print the largest integer
return 0;
}
Related
I have been trying to solve this problem since yesterday. The program should accept N numbers from the user and will place them in an array. I have done this. However, I don't seem to know how to "warn" the user that the input is a duplicate and lets the user enter again.
Here is my code:
# include <iostream>
using namespace std;
int main () {
int N, pos = -1, arr [N], i, j;
int startLoop = 1;
// the 'startLoop' variable is used so that the first user input can have the break function
bool found = false;
while (startLoop != 0) {
cout << "Enter the number of integers to be entered: ";
cin >> N;
if (N <= 4) {
cout << "Invalid. \n";
}
if (N > 4) {
cout << "\n\nEnter " << N << " unique numbers: " ;
for (i = 0; i < N; i++) {
cin >> arr [i];
for (j = 0; j < N && !found; j++) {
if (arr [j] == arr [i]) {
found = true;
cout << "Enter again: ";
}
}
break;
}
}
}
The following is the copy paste of your code:
By adding break you will jump out of the outer for loop and you cannot read n inputs.
the inner loop range is not correct since i is the total number of values read by now. i.e. if N= 10 and in third iteration you are trying to loop among 10 elements to double check if the latest number is a duplicate, while you have read 3 elements by now.
if (N > 4) {
cout << "\n\nEnter " << N << " unique numbers: " ;
for (i = 0; i < N; i++) {
cin >> arr [i];
for (j = 0; j < N && !found; j++) {
if (arr [j] == arr [i]) {
found = true;
cout << "Enter again: ";
}
}
break;
}
}
How to fix?
One approach would be to read the input in a separate loop and then try to find the duplicates and remove them.
Time Complexity will be O(n) since you need to traverse through the list twice, however you need to implement removing elements from the array efficiently without shifting all the elements
Second approach is like what you are trying to implement but it is not efficient since every time a user is adding a new elements you need to re-evaluate i numbers (in worst case n numbers when you are filling the end of array). this process should be repeated every time user insert a repeated number.
The best approach would be store all input numbers inside a hash (set) and every-time a new number is inserted check whether it is already suggested by the user or not. Time complexity of searching elements through unordered_set will be O(1)
Problems:
Your code has many several problems:
You shouldn't use VLAs (Variable Length Arrays) as they are non-standard.
Using N before initializing it is UB (Undefined Behaviour).
Your approach is not efficient as it checks on average n/2 elements n times and therefore it has a time complexity of O(n^2).
You have many unused variables and variables that should be in a more specific scope.
Solutions:
Use std::vector insted of VLAs.
Resize the vector after initializing N.
Change your approach.
Change the scope of your variables.
Additional information:
using namespace std; is considered a bad practice (More info here).
You should probably add input checking to std::cin to verify that the input is a number.
Full code:
Checking duplicates once at the end of input with std::vector (Time complexity: O(n * log(n)). Space complexity: O(n)):
#include <iostream>
#include <vector>
#include <algorithm>
bool hasDuplicates(std::vector<int> toCheck)
{
std::sort(toCheck.begin(),toCheck.end());
for(unsigned int i = 1; i < toCheck.size(); i++)
if(toCheck[i] == toCheck[i-1])
return true;
return false;
}
int main () {
std::vector<int> arr;
int N;
while (true) {
std::cout << "Enter the number of integers to be entered: ";
std::cin >> N;
if (N <= 4) {
std::cout << "Invalid: The number of integers to be entered must be bigger than 4. \n";
}
else {
arr.resize(N);
std::cout << "\n\nEnter " << N << " unique numbers: " ;
for (int i = 0; i < N; i++)
std::cin >> arr [i];
if(hasDuplicates(arr))
std::cout << "Invalid: The numbers must be unique. \n";
else
break;
}
}
}
Checking duplicates each time a number is entered with std::unordered_map (Time complexity: Amortized O(n). Space complexity: O(n)):
#include <iostream>
#include <vector>
#include <unordered_set>
int main () {
std::vector<int> arr;
std::unordered_set<int> alreadyAppeared;
int N;
std::cout << "Enter the number of integers to be entered: ";
std::cin >> N;
while (N <= 4) {
std::cout << "Invalid: The number of integers to be entered must be bigger than 4. \n";
std::cout << "Enter the number of integers to be entered: ";
std::cin >> N;
}
arr.resize(N);
std::cout << "\n\nEnter " << N << " unique numbers: \n";
for (int i = 0; i < N; i++)
{
int entering;
std::cout << "Enter unique number: ";
std::cin >> entering;
if(alreadyAppeared.find(entering) == alreadyAppeared.end())
{
alreadyAppeared.insert(entering);
arr[i] = entering;
}
else
{
std::cout << "Invalid: The numbers must be unique. \n";
i--;
}
}
}
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! ";
My exercise is as follows: Given a list of N integers, find its mean (as a double), maximum value, minimum value, and range. Your program will first ask for N, the number of integers in the list, which the user will input. Then the user will input N more numbers.
Here is my code:
#include "stdafx.h"
#include <iostream>
using namespace std;
int main()
{
int n;
cout << "Input n: ";
cin >> n;
int first; //**LINE NUMBER 1**
cout << "No 1 is: ";
cin >> first;
int max = first;
int min = first;
for (int i=1; i<n;i++) //**LINE NUMBER 2**
{
int x;
cout << "No " << i+1 << " is: ";
cin >> x;
first = x; //**LINE NUMBER 3**
if (max < x)
{
max = x;
}
if (min > x)
{
min = x;
}
}
cout << "max is: " << max << endl;
cout << "min is: " << min << endl;
cout << "mean is: " << (double) (max+min)/2 << endl; //**LINE NUMBER 4**
cout << "range is: " << max - min << endl;
return 0;
}
However, the solution is a bit different:
For line number 1, it is int first=0; instead of int first;
For line number 2, it is for (int i=1; i<n;++i) instead of for (int i=1; i<n;i++)
For line number 3, it is first += x; instead of first = x;
For line number 4, it is cout << "mean is: " << (double) first/n<< endl; instead of cout << "mean is: " << (double) (max+min)/2 << endl;
I tried some examples but both codes produce exactly the same results. Why is that? Or am I wrong somewhere?
Well:
None of the lines are, per se, WRONG. More so, they are just preferably done another way. ie:
int first =0 just ensures that first == 0 to begin with. int first; can cause problems because it is assigned, initially to an arbitrary number (whatever happens to be at the memory address that the variable points to)
although ++i and i++ work the same way in for loops as an iterator, they have a very slight difference in other usages. read more about that here
first += x is essentially first = first + x which more clearly outlines the difference between your code and it. This also makes it very clear why int first = 0 is so important. If first was some random value, then the sum of all the numbers (which is what first is supposed to be) would be randomly assigned to start at a number, not always 0.
this last one is the only one where you are, in fact, wrong. the mean is defined as the sum of all your data divided by the number of data points (same as average) where as the median is described as the middle point of the data, or the number that describes the middle point between the max and min of your data. Where you are calculating what you think is the mean is actually the median. The intricacy of this is that sometimes, depending on your data, the mean = median. For example, if your data is 3,4,5 then both the mean and median is equal to 4
I hope this clarifies things for you :)
Here I have a program that prompts the user to enter size of array, then ask user for integers and calculate average. I'm missing something, the numbers are not being stored into the array.
int n;
int *sizeOfArr;
double total = 0;
double avg;
cout << "Please enter n, for size of array: ";
cin >> n;
sizeOfArr = new int[n]; //dynamically allocates n amount of memory
for (int i = 1; n >= i; i++){
cout << "Enter number " << i << ": ";
cin >> sizeOfArr[n];
if (sizeOfArr[n] < 0){
do{
cout << "Please enter postive number for number " << i << ": ";
cin >> sizeOfArr[n];
} while (sizeOfArr[n] <= 0);
}
total += sizeOfArr[n];
}
avg = total / n; //average formula
cout << "\nAverage of the numbers stored in dynamic array = " << avg << endl; //output
return 0;
system("pause");
Use std::vector instead of dynamic array int*. You do not need to ask the user for size(), you can just dynamically add a variable via std::vector.push_back(). The size can be obtained by calling std::vector.size().
Some mistakes in your Code: Your loop starts int i=1; That's wrong. The first index of the array is 0. Same thing when referencing the vector items: you have to set sizeOfArr[i] not sizeOfArr[n].
Now the point to calculate the mean value:
Your calculation runs with int. If you calculate that way your result will be wrong. You should use double to to so.
Actually it should be sizeOfArr[i-1] instead of sizeOfArr[n]
Your iteration index i starts from 1 but instead array index should start from 0
You're using the wrong variable to index sizeOfArr[] - you should be using the loop variable i as an index. Also, since you're iterating from 1 to n, and not the more usual 0 to n - 1, you need to adjust the index to compensate for this. So, either change all occurrences of:
sizeOfArr[n]
to:
sizeOfArr[i - 1]
or change the for loop to the more canonical form:
for (int i = 0; i < n; ++i)
and then just use:
sizeOfArr[i]
Use sizeOfArr[i] instead of sizeOfArr[n]
I bought the textbook C++ How to program 9th edition and I have come across a question that I am just stumped on, even though it is probably pretty simple. The question all summed up is this: "Use a while statement to determine and print the largest number of 10 numbers entered by the user". But here is the part that stumps me. The question wants me to use only 3 variables. counter, number, and largest. I know to make counter variable go up by 1 for each number entered until it gets to 10, and I know the number variable is used for input. I just can't seem to find out how to use the largest variable, or how to check to see what value is the largest without using other variables. This is all I have so far. Right now I put a break in the code so it wouldn't be an infinite loop.
UPDATED CODE
#include <iostream>
using namespace std;
void main()
{
int counter = 0;
int number = 0;
int largest = 0;
cout << "Please enter up to 10 numbers and I will print the largest one on the screen.\n\n";
while (counter <= 10)
{
cout << "Number: ";
cin >> number;
counter++;
if (number > largest)
{
largest = number;
}
else if (counter == 10)
{
cout << "The largest number was: " << number;
break;
}
}
}
cout << "The largest number was: " << number;
should be
cout << "The largest number was: " << largest;
Inside the while loop, if number is greater than largest, then set largest = number.
Then at the end you can output largest.
Solution(you don't even need a while loop)
#define MAX_NUM 8
//user input goes in myints
int myints[MAX_NUM] = {3,7,2,5,6,4,9};
// using default comparison:
std::cout << "The largest element is " << *std::max_element(myints,myints+MAX_NUM) << '\n';
Other Solution using int arrays even though you can replace int array with one variable
int main()
{
int largest = 0;
int myints[10] = {3,7,2,5,6,4,9,7,2,6};
for(int i =0 ; i< 10;i++)
{
if (myints[i] > largest)
{
largest = myints[i];
}
}
cout << largest << endl;
return 0;
}
Compiled Code
Second Compiled Code
You just need to add in while loop checking is the number you entered bigger than largest. If it is you just store it in largest. And actually you are entering 11 numbers because you count from 0 to 10. Just set counter to 1 or while(counter < 10)
int counter = 1;
int number = 0;
int largest = 0;
cout << "Please enter up to 10 numbers and I will print the largest one on the screen.\n\n";
while (counter <= 10)
{
cout << "Number: ";
cin >> number;
counter++;
if (largest < number)
{
largest = number;
}
}
cout << largest << endl;