+ 2

Please look this cpp code.

https://code.sololearn.com/cW8jNRs7r9Dn/?ref=app if I enter less than 5 inputs it generates some random numbers. why?

29th Dec 2017, 7:30 AM
Qwqwq Rt
Qwqwq Rt - avatar
6 Answers
+ 4
Simply because it takes some garbage value. You asked the user to enter 5 numbers in the array. Now a memory location is allocated for 5 members. If u enter less than 5 elements, the remaining places are filled with some garbage value. To avoid this u can either generalize the code to n elements or you can use a counter to count the actual number of elements the user entered(if less than 5) and print upto the counter limit only.
29th Dec 2017, 8:51 AM
Abhishek Tandon
Abhishek Tandon - avatar
+ 4
Well what I was thinking would work is not actually happening here. Actually this was the method i used while using arrays in C language. In C you have to have give some length to the array even before the user enters something and therefore I used the counter method there! This will not work that easy in C++ I thought we could use the length(); function to calculate the array length, but that too is not possible since u have already set the limit to 5. So the last option left is to generalize the code to n. Though.. I will still try to tell u some method to do that anyway
29th Dec 2017, 1:22 PM
Abhishek Tandon
Abhishek Tandon - avatar
+ 2
@infinity I know how to generalise it for n but I don't know how about counter limit. can you tell me, how to do that.
29th Dec 2017, 8:59 AM
Qwqwq Rt
Qwqwq Rt - avatar
+ 2
@infinity°° Hey, just try your code with no input. i.e click run then click submit, without clicking any value, it gives a random output.
29th Dec 2017, 1:03 PM
Qwqwq Rt
Qwqwq Rt - avatar
+ 2
even when there are two inputs there are garbage numbers appearing. Ahh! I need your help again.
29th Dec 2017, 1:05 PM
Qwqwq Rt
Qwqwq Rt - avatar