need to output max and min (without array) - c++

I'm writing a program that prompts the user to enter integer numbers.
The program stops reading when user inputs 0.
It should output the max and min element among inputed numbers.
I must write it without using arrays.
Input: 1 2 3 4 5 0
Output: min=1 max=5
My code:
#include <iostream>
using namespace std;
int main()
{
int n,max,min;
min=0;
max=0;
do{
cin>>n;
if(n>max){
max=n;
}
if(n<min){
min=n;
}
}
while(n!=0);
cout<<max<<endl;
cout<<min;
}
The problem is that when I enter the integers from my example the output is min=0 max=5, instead of min=1 max=5.
How can I fix it?

You may want to input a starting value first, then loop:
int main()
{
int n, min, max;
cin >> n;
min = n;
max = n;
if (n != 0)
{
while (cin >> n)
{
if (n == 0) break;
if (n > max) max = n;
if (n < min) min = n;
}
}
std::cout << "min: " << min << ", max: " << max << "\n";
return 0;
}
In the code above, the first value is read and checked for 0. The program stops input if the value is zero.
The minimum and maximum are assigned the first value.
Then the loop starts.

Related

Find Extreme Value in Integers Given

I'm trying to find the highest value in a given list, but in an input list like this
7 385 -390 305 470 -145 255 30
my output is wrong, 385 instead of 470.
Could anyone please guide me towards my error!
Task description:
Read in an input value for variable numIn. Then, read numIn integers from input and output the largest of the integers read. End with a newline.
Ex: If the input is 2 345 -5, then the output is:
345
my code below
#include <iostream>
using namespace std;
int main() {
int numIn;
int high = 0;
cin >> numIn;
for (int i = 0; i < numIn; i++) {
cin >> numIn;
if (numIn > high) {
high = numIn;
}
}
cout << high << endl;
return 0;
}
First of all, your list has negative numbers. You can't set the default value of high to 0 since a list with all negative numbers won't work if you do this.
The error in your loop occurs because you overwrite numIn. Use a different variable for the number of input numbers.
cin >> numIn; // numIn is the number of input numbers
for (int i = 0; i < numIn; i++) {
cin >> numIn; // oops, numIn is now the first input number. it has been overwritten.
if (numIn > high) {
high = numIn;
}
}
A correct solution would look like this:
#include <iostream>
int main() {
int N; // assume that N >= 1. You could also replace this with numIn.
std::cin >> N;
int max;
std::cin >> max; // take in the first integer outside the loop
for (auto i = 1; i < N; i++) { // loop which runs N - 1 times
int E;
std::cin >> E;
max = std::max(max, E);
}
std::cout << max << '\n';
}
Without using std::max()
If you don't want to use std::max(), replace the line where you use it with a normal comparison (this is what std::max() does internally too)
if (E > max) { max = E; }

Program not loading array correctly

Question at hand: Write a function primeTableInRange to generate a table to show whether each number in the range from startNum up to endNum is a prime number. When the number is not a prime number, we will only show a ‘*’. When the number is a prime number, we will show the number.
My code:
#include <iostream>
#include <ctime>
#include <cmath>
#include <cstdlib>
using namespace std;
int primetableinarray(int userarray[], int arraysize);
int main()
{
int startNum, endNum;
cout<< "Enter your first number in the range" << endl;
cin>>startNum;
cout<< "Enter your last number in the range" << endl;
cin>>endNum;
int arraysize = endNum - startNum;
int userarray[arraysize];
for (int i=startNum;i<=endNum;i++)
userarray[i]= startNum++;
primetableinarray(userarray, arraysize);
return 0;
}
int primetableinarray(int userarray[], int arraysize)
{
for (int i=2;i<arraysize;i++)
{
bool prime=true;
for (int r=2;r*r<i;r++)
{
if (i % r ==0)
{
prime=false;
break;
}
}
if(prime) cout << i << endl;
else
if(true) cout<< "*" << endl;
}
}
Issue is it doesn't start at "startNum" and doesn't end at "endNum". It actually goes from 0 to arraysize. Also it calculates 4 as a prime number. What am I missing here?
Be careful! Arrays always start at 0 and end at arraysize in your case. You cannot have arbitrary indexing. You could do the following:
int arraysize = endNum - startNum + 1;
int userarray[arraysize];
for (int i=0;i<arraysize;i++)
userarray[i]= startNum+i;
Also, since we start at 0 you need to add +1 in ´arraysize´ to include ´endNum´ in your ´userarray´
try to change this
from:
for (int r=2;r*r<i;r++)
to
for (int r=2;r<i;r++)
At nowhere in your printing function do you even recognize your array. You simply begin looping numbers up to your array size. If you took the array out of your function arguments it would still work, so why are you including it? Your for loops just disregard any values in your array and begin looping from 2 arbitrarily.
As for why 4 is calculated as a prime number, it is because when your second loop starts it sees that 2*2=4 and therefore not less than 4, which is the number you are testing. This results in it skipping over the loop and never setting prime to false. Make the condition in the second for loop to <= or else any perfect square with no other factors will be labelled as prime, such as 25.
Also on a side note, how did this ever compile? You use a dynaimc variable to initiate an array size. That doesn't work and when I tried to run your code to see the output I got errors. Try using std::vector<int>. When you use the for loop to fill the vector you use the values as indexes which is completely and utterly wrong. This is when you should loop from zero to your arraysize because that it the address within the array. You also include unecessary headers like ctime and cmath, and have if(true) in your code for no reason.
#include <iostream>
#include <ctime>
#include <cmath>
#include <cstdlib>
using namespace std;
int primetableinarray(int userarray[], int arraysize);
int main()
{
int startNum, endNum;
cout<< "Enter your first number in the range" << endl;
cin>>startNum;
cout<< "Enter your last number in the range" << endl;
cin>>endNum;
int arraysize = endNum - startNum + 1;
int userarray[arraysize];
for (int i=startNum;i<endNum;i++)
userarray[i]= startNum++;
primetableinarray(userarray, arraysize);
return 0;
}
int primetableinarray(int userarray[], int arraysize)
{
for (int i=2;i<=arraysize;i++)
{
bool prime=true;
for (int r=2;r<i;r++)
{
if (i % r ==0)
{
prime=false;
break;
}
}
if(prime) cout << i << endl;
else
if(true) cout<< "*" << endl;
}
}
The declaration for the array (int userarray[arraysize];) is illegal, the array bounds need to be known at compile time. This should not even compile, or it produces a zero-size array.
Afterwards, you randomly access unallocated memory, whcih is UB
Change
int arraysize = endNum - startNum + 1;
int userarray[arraysize];
To
int userarray[1];
int arraysize = endNum - startNum;
userarray[arraysize];
Also, add a return value to the primetableinarray function.
Here is the correct program .
#include <iostream>
using namespace std;
void primetableinarray(int low, int high) ;
int main()
{
int low, high, i, flag;
cout<< "Enter low numbers ";
cin>> low;
cout<< "Enter high numbers ";
cin>>high;
cout<< "Prime numbers between " << low << "and are: " << high <<endl;;
primetableinarray(low, high);
return 0;
}
void primetableinarray(int low, int high) {
int i, flag;
while (low <= high)
{
flag = 0;
for(i = 2; i <= low/2; ++i)
{
if(low % i == 0)
{
flag = 1;
break;
}
}
if (flag == 0)
cout<< low <<endl;
else
cout<< "*" <<endl;
++low;
}
}
Output :
Enter low numbers 1
Enter high numbers 10
Prime numbers between 1and are: 10
1
2
3
*
5
*
7
*
*
*
There are copule of problem in your code :
int arraysize = endNum - startNum;
int userarray[arraysize];
How does it compile , it will be compilation error. you can allocate memory dynamically and use it .
for (int i=startNum;i<=endNum;i++)
userarray[i]= startNum++;
this is wrong i = startNum and arraysize = arraysize +1 if you are comparing " i<=endNum " .
Correct way is :
for (int i=0;i<=endNum;i++)
userarray[i]= startNum++;

Print all prime number lower than n in C++ ( file crash )

I wrote a C++ program that prints all prime numbers lower than n, but the program keeps crashing while executing.
#include <iostream>
using namespace std;
bool premier(int x) {
int i = 2;
while (i < x) {
if (x % i == 0)
return false;
i++;
}
return true;
}
int main() {
int n;
int i = 0;
cout << "entrer un entier n : ";
cin >> n;
while (i < n) {
if (n % i == 0 && premier(i))
cout << i;
i++;
}
;
}
As Igor pointed out, i is zero the first time when n%i is done. Since you want only prime numbers and the smallest prime number is 2, I suggest you initialise i to 2 instead of 0.
You want to print all prime numbers less than n and has a function to check primality already.
Just
while (i < n){
if ( premier(i) == true )
cout<<i;
i++;
}
And while printing, add a some character to separate the numbers inorder to be able to distinguish them like
cout<<i<<endl;
P.S: I think you call this a C++ program. Not a script.
Edit: This might interest you.

Sum of factoriais to be equal a given number

I'm trying to solve the following problem:
What is the smallest number of factoriais summed that are needed to be equal an given number a? (1 ≤ a ≤ 10^5)
Example:
Input: 10, Output: 3. (10 = 3! + 2! + 2!)
Input: 25, Output: 2. (25 = 4! + 1!)
My code:
#include<bits/stdc++.h>
using namespace std;
int a;
int rec(int vet){
int count = 0;
a = a - vet;
if(a >= vet){
count++;
rec(vet);
}
count++;
return count;
}
int main(){
int vet[8] = {1}, count = 0;
cin >> a;
for(int i = 2; i <= 8; i++){
vet[i-1] = vet[i-2]*i;
}
for(int i = 7; i >= 0; i--){
if(a < vet[i]){
continue;
}
count += rec(vet[i]);
}
cout << count << endl;
}
My logic:
1°: a max is equal to 100000, so the maximum fatorial we have to
compare is 8!;
2°: I take a factioral that is equal or nearest small to a,
subtract the factorial from it and count++; If after the subtraction,
a still bigger then my factorial, I do the same step recursively.
This code pass on the base cases, but I got a wrong answer. I wasn't capable to find what case it didn't pass, so I'm here.
Can you find where am I wrong? Or if my solution is not good and I should try another approach.
Thanks for the help!
The problem is easily solved by a recursive approach.
Here is checked code:
#include <iostream>
using namespace std;
int factorial(int n) {
return n<=1 ? 1 : n * factorial(n-1);
}
int MinFact(int number)
{
static int num_of_facts;
int a = 1;
if (number)
{
while(factorial(a+1)<=number)a++;
cout << a << "!" << endl;
num_of_facts++;
MinFact((number-factorial(a)));
}
return num_of_facts;
}
int main()
{
int num;
cout << "Enter number" << endl;
cin >> num;
num = MinFact(num);
cout << "Number of factorials: " << num;
return 0;
}
As I mentioned in the comment, the issue is with the rec function. Due to rec being local, the count is not being incremented correctly.
A simple solution would be to replace the rec function as follows
int rec(int vec) {
int count = a / vec;
a = a % vec;
return count;
}
Edit : for a failing case try 18. The solution will be 3 but you will get 2.
I guess you can figure out how this logic works. If not you could do it with a loop.

Nearest value in an array

I am supposed write a function that is passed two parameters: a one-dimensional array of int values, and an integer value. The function finds the value in the array that is closest in value to the second parameter. My code works but not when I enter numbers 1-5 my output is 0. When I enter numbers above 5 then I start getting accurate results. I am not too sure why this is happening but here is my code so far:
#include <iostream>
#include <cmath>
using namespace std;
const int MAX = 5;
int searchNearest(int anArray[],int key)
{
int value = abs(key - anArray[0]);
int num = 0;
for(int x = 0;x < MAX; x++)
{
if(value > abs(key - anArray[x]))
{
value = abs(key - anArray[x]);
num = anArray[x];
}
}
return num;
}
int main()
{
int A[MAX] = {3,7,12,8,10};
int search;
int nearest;
cout << "Enter a number to search: ";
cin >> search;
nearest = searchNearest(A,search);
cout << "The nearest number is: " << nearest << endl;
system("pause");
return 0;
}
In your original code, numbers 1-5 are closest to the first element of the array. Because of this, the code in the if statement is never executed, and when you return num, you return its initial value, which happens to be 0. To fix this, just initialize num differently:
int num = anArray[0]; // <-- used to be 0