New coder help!

I have some codes I want to get feedback on. I am new to coding and would like to know what improvements could be made to my codes. My codes all work, but I want to know what improvements I could make to make them run faster, easier, be more readable, etc. Thanks!! Also if theres a forum that i should use for this instead lmk sorry


EDIT: I also would like to know why it was recommend to use a pointer to output rather than just using "cout << maxNum;"

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <iostream>

using namespace std;

int main()
{
  int userNum;
  int arrayNums[userNum];
  int maxNum;

  cout << "Enter number of values: ";
  cin >> userNum;

  cout << "Enter array values: ";
  cout << endl;
  for(int i = 0; i < userNum; i++)
  {
    cout << i + 1 << ": ";
    cin >> arrayNums[i];
  }

  for(int i = 0; i < userNum; i++)
  {
    if(arrayNums[i] > maxNum)
    {
      maxNum = arrayNums[i];
    }
  }

  int* pointer = &maxNum;

  cout << "Largest number is: " << *pointer;

  return 0;
}
Last edited on
initialize variables. Your max finder loop won't work on all compilers, what if maxnum had randomly been the biggest possible int value? It could be, as it has no initial value. Variables with no initial value can be any value!


also it is not allowed to use variables in array sizes in normal c++. some compilers allow it, but it won't compile on anything set to enforce c++ rules.

also userNum is uninitialized so even if you allow variable arrays, it is still unknown size just like max, what if it were value 0?

I ran your program in the built into the site tool and this was the output:

Enter number of values: 4
Enter array values:
1: 1
2: 2
3: 3
4: 4
Largest number is: 1173834560

it is NOT recommended to use a pointer to write output. Whoever told you that is mistaken. Your question version is correct, don't use a pointer unless you need a pointer.

Last edited on
Topic archived. No new replies allowed.