2

I'm a beginner in programming and as you can see, I created a program where the user is asked to input three numbers. It will display the greatest among the numbers given. But after I finished the code, a question came into my mind, what if the user was asked to input a hundreds of numbers and should display the greatest among the numbers given. So the question is, is it possible to do that? what are the things I need to learn to produce that result? is there any hints you can give me?

#include <iostream>
#include <string>

using std::cout, std::cin, std::endl, std::string;
int main() {

  string result = " is the greatest among the numbers given";
  double x, y, z;

  cout<<"Enter three numbers to decide which is the largest: "<<endl;
  cin >>x;
  cin >>y;
  cin >>z;

  system("clear");

  if(x>y && x>z){
    cout<< x << result;
  } else if (y>z && y>x){
    cout << y << result;
  } else
    cout<< z << result;
  return 0;
}
Kanra
  • 21
  • 7
  • 1
    You'll need to learn about arrays/vectors and loops in order to do that. Do you need example of such task? – dh4ze Sep 15 '21 at 12:47
  • 2
    I suggest you get [a good book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) to learn from. An introductory level book should get you through all the basic concepts that are required for task you describe – Yksisarvinen Sep 15 '21 at 12:48
  • I'd be glad to learn from that example @dh4ze – Kanra Sep 15 '21 at 12:55
  • 1
    I see you've changed your code based on my answer. You can also remove every instance of `<< result` and add `cout << " is the greatest among the numbers given"` after the if-else statements. You can also get input in a single statement: `cin >> x >> y >> z`. – glibg10b Sep 16 '21 at 12:25

5 Answers5

2

One solution would be to store your inputs in a list and sort them afterwards. Just google "sorting alorithms". Also there are nice youtube visualizations.

Another one would be to not save the inputs into dedicated variables - in your case x, y, z - but to always save the largest given input:

int largestInput = std::numeric_limits<int>::min();

int input;

for (int i = 0; i < 10000; i++)
{
     std::cin >> input;
     largestInput = input > largestInput ? input : largestInput;
}
Baumflaum
  • 749
  • 7
  • 20
  • Why -1 instead of `std::numeric_limits::min()`? – Stephen Newell Sep 15 '21 at 13:09
  • Sorting is not the best idea. A simple scan through the list is much faster. And much simpler, too. – CiaPan Sep 15 '21 at 13:19
  • What if the user inputs values of `-5` and `-17`...? – CiaPan Sep 15 '21 at 13:21
  • You are right. Corrected it. I agree, sorting is not the best solution but it is a solution; going through the list once is ofc preferable. – Baumflaum Sep 15 '21 at 13:34
  • Forgive me if I ask this beginner question, but could you guys explain what `std::numeric_limits::min()` is for? – Kanra Sep 15 '21 at 14:10
  • 1
    It just returns the minimum possible value for the type `int`. You can replace `int` with many other datatypes. See [here](https://en.cppreference.com/w/cpp/types/numeric_limits/min) – Baumflaum Sep 15 '21 at 14:26
2

With the program below, you can get as many numbers as you want from the user and find the largest of them.

 #include <iostream>
    
    int main()
    {
        int size=0, largestValue=0, value=0;
    
        std::cout << "Enter total numbers you want to add :" << "\n";
        std::cin >> size;
    
        for (int i{ 0 }; i < size; ++i)
        {
            std::cout << "Enter value to add : ";
            std::cin >> value;
    
            if (i == 0 || value > largestValue)
            {
                largestValue = value;
            }
        }
    
        std::cout << "Largest value = " << largestValue << "\n";
        return 0;
    }
east1000
  • 1,240
  • 1
  • 10
  • 30
  • Forgive me if I ask this question, but what is the brackets between the zero is for? why did you put ++i instead of i++ `for (int i{ 0 }; i < size; ++i);` and `if (i == 0 || value > largestValue) { largestValue = value` can you explain this part too? I can't wrap my head around this code yet – Kanra Sep 15 '21 at 13:36
  • @kanra There is no difference between typing `i=0` and typing `i{0}`.Initializing using `{}` is called `uniform initialization.`Don't worry about the reason why I use `++i` instead of `i++`. Both will work here.But if you're curious about the differences, you can have a look here. https://stackoverflow.com/questions/24901/is-there-a-performance-difference-between-i-and-i-in-c – east1000 Sep 15 '21 at 13:46
  • @kanra `if (i == 0 || value > largestValue)` In this part, if the number we receive from the user is the first number, we directly determine it as the largest value, since there is no other number received before.If it is not the first number we get from the user, then we are comparing whether it is greater than the largest value we set before.If the retrieved number is greater than the largest number we previously set, that number is now our new largest number. So `largestValue = value;` we are writing. – east1000 Sep 15 '21 at 13:51
2

If you know the inputs are large, you can use vectors.

#include <bits/stdc++.h>
using namespace std;

int main(){
  int total_num=0;
  cout << "Enter total numbers:" << "\n";
  cin>>total_num;
  int max_number = INT_MIN;
  vector<int> v;
  for(int i=0;i<total_num;i++){
        int x;
        cin>>x;
        v.push_back(x);
        max_number = max(max_number,x);
  }
  cout<<"Maximum number present: "<< max_number<<endl;
  return 0;
}

Although there is no need to store numbers. But it's your choice if you need it later you can use it in that program.

2

> what are the things I need to learn

what if the user was asked to input a hundreds of numbers

For this, you'll need to learn about arrays. I suggest you first learn about C-style arrays (int x[3]{};), and then std::array (std::array<int, 3> x{};). You also need to learn about loops.

and should display the greatest among the numbers given

Having to find the largest number in an array is very common. If you want to learn how to do so manually, the other answers here should answer your question. Otherwise, look towards the standard library algorithms std::ranges::max() (C++20) and std::max_element.

Examples

Example 1

Here's a program that uses a C-style array and a simple algorithm to get the largest number:

#include <iostream>

int main(){
    // Amount of numbers user should input
    constexpr int count{ 3 };

    std::cout << "Enter " << count
        << " numbers to decide which is the largest:\n";

    // The numbers entered by the user
    double numbers[count]{}; // Declare and zero-initialize a C-style array of 3 ints

    // Get each number from the user and put it in the array
    for (int i{ 0 }; i < count; ++i) {
        std::cin >> numbers[i];
    }

    // The biggest number found so far
    int max{ numbers[0] }; // Initialize it with the first number

    for (int i{ 1 }; i < count; ++i) { // Start at the second element (element 1)
        if (numbers[i] > max) { // If the current number is larger than max...
            max = numbers[i];   // ...assign it to max
        }
    }

    std::cout << max << " is the greatest among the numbers given\n";

    return 0;
}

Note:

  1. int numbers[count]{}; 
    

    This creates a C-style array called numbers which has count (3) elements. The first element's "index" is 0 and the last element's is 2. The {} initializes the values of all of the numbers to 0 (good practice).

  2. for (int i{ 0 }; i < count; ++i)
      std::cin >> numbers[i];
    

    This loops until i isn't less than count (3) and increments i (++i) each time. It starts at 0, so it loops 3 (0 1 2) times. On each iteration, it gets a number from the console and stores it in numbers[i].

Example 2

Here's a shorter program that uses the standard library:

#include <algorithm> // ranges::max()
#include <array>     // array<>
#include <iostream>  // cin, cout

int main() {
    // Amount of numbers user should input
    constexpr int count{ 3 };

    std::cout << "Enter "
        << count
        << " numbers to decide which is the largest:\n";

    std::array<double, count> numbers{}; // Declare an array of 3 ints

    for (int i{ 0 }; i < count; ++i) {
        std::cin >> numbers[i];
    }

    // Return the largest number in array "numbers"
    std::cout << std::ranges::max(numbers)
        << " is the greatest among the numbers given\n";

    return 0;
}

Note:

  1. std::array<int, count> numbers{};
    

    Declares an array of count (3) ints and zero-initializes it.

  2. std::ranges::max(numbers)
    

    This neat function finds the largest number in numbers. It was added in C++20 -- if you're using an older compiler, you should use *std::max_element(numbers.begin(), numbers.end()). If you want to learn how the latter works, you need to learn about iterators and pointers.


Here are some good practices that your tutorial hasn't taught you yet (if it ever will):

  1. DON'T use using namespace std. It's unsafe because it brings everything in the standard library into global scope. The standard library contains a lot of commonly used identifiers like count and list. Bringing these into global scope is dangerous because it can cause naming conflicts.

  2. Don't use copy initialization (int x = 3). Use uniform/brace/list initialization instead (int x{ 3 }). The former sometimes makes an unnecessary copy, whereas the latter doesn't. The latter also refuses to do narrowing conversions (e.g. initializing a short with a long).

  3. Always initialize variables (do: int x{}, don't: int x), even when it seems redundant. If you don't, then the value stored is undefined - it could be anything. Undefined behaviour is hard to debug but luckily easy to avoid.

  4. Use \n instead of std::endl. Both do the same, except std::endl does an extra buffer flush which is slow and unnecessary. \n is shorter anyways.

  5. DRY -- Don't Repeat Yourself. You have the string " is the greatest among the numbers given" three times in your code. You could have stored it in a std::string instead -- then it wouldn't have repeated.

    Repeating code is bad, because:

    1. It's harder to read
    2. It's harder to maintain (you would have to modify it everywhere it's repeated)
    3. Maintenance is more error-prone

If I were you, I'd immediately find a different tutorial/book. See this thread.

glibg10b
  • 338
  • 1
  • 11
  • TBH this should be accepted. ;) Although I have a nitpick with your second point of good practices: The compiler is allowed to omit the copy if it sees fit. For any sensible compiler implementation it will be done for all sanely programmed code. That means if `int x = 3` is more readable, prefer it to `int i{3}`. @OP These tips may seem arbitrary for now, but will prove very useful as soon as you start programming big and complicated projects. – Baumflaum Sep 17 '21 at 09:23
  • @Baumflaum I personally find `{}` more readable because it helps with distinguishing between initialization and assignment, and it can be used almost anywhere, unlike `=`. As for the second part of your comment, I agree. @Kanra It's good to establish good habits early on -- you'll thank yourself later. – glibg10b Sep 17 '21 at 12:16
-1

#include <stdio.h>

 int main()
 {

    int num1, num2, num3, num4;

    printf("Enter num1\n");
    scanf("%d",&num1);
    printf("Enter num2\n");
    scanf("%d",&num2);
    printf("Enter num3\n");
    scanf("%d",&num3);
    printf("Enter num4\n");
    scanf("%d",&num4);

    if(num1>num2 && num1>num3 && num1>num4){
        printf("greatest number is %d",num1);
    }

    if(num2>num3 && num2>num1 && num2>num4){
        printf("greatest number is %d",num2);
    }

    if(num3>num1 && num3>num2 && num3>num4){
        printf("greatest number is %d",num3);
    }

    if(num4>num1 && num4>num2 && num4>num3){
        printf("greatest number is %d",num4);
    }

    return 0;
    }
  • This doesn't really answer the question, which is how to find the largest number out of an arbitrary number of inputs. – Kevin McKenzie Oct 12 '21 at 19:35
  • Yes but it works.. And it is easy to understand for beginner programmers.. – Gaurav Shinde Oct 13 '21 at 03:17
  • It works, but again, doesn't answer the question, which is "what if the user was asked to input a hundreds of numbers and should display the greatest among the numbers given." – Kevin McKenzie Oct 13 '21 at 15:21
  • Really am a begginer I just have learn something about loops and all so, And I know thats not the perfect way to do this programme but I tried my best.. But thank you for realising me my mistake. And I want some guidance from professionals so keep supporting.... – Gaurav Shinde Oct 13 '21 at 16:27
  • And I am finding another ways to do this problem suggest me a way that you think. Keep helping me bro. – Gaurav Shinde Oct 13 '21 at 16:28