+ 1

Why I Need this If?

Hello Guys, i'm new in this community and new in programming. I have a question about c++'s program. Why i need if in the first For? If i don't use it and if i put n<=15, the program cout 0 and after the result. Why this? https://code.sololearn.com/c55qASGg0YL2/?ref=app https://code.sololearn.com/c55qASGg0YL2/?ref=app

10th Dec 2018, 10:18 PM
FireLion137
4 Answers
+ 1
Ok, thank you. Look again the code, now how the initialization is? Another think: I can't input 0 because in the For i used n>0 and not n>=0. If i use n>=0 in the For my program crash,why this?
10th Dec 2018, 11:19 PM
FireLion137
+ 9
int n,i; int arr[i]; I find this particular code segment dangerous. Variable i has not been initialized. Assuming that i is 0 at the time of initialization for arr, you have an array of size 0 and will then be writing to memory addresses that are not allocated to you. Running it on a local machine (after compiling it w/ your own compiler) may give you segfaults. Now, moving on from the rant. cout<<"Number:\n"; cin>>n; for (i=0;n>0;n=n/16) { arr[i]=n%16; if(n>15) i++; } Here, you are trying to convert a decimal value (base 10) to a hexadecimal value (base 16). If you take a closer look at the code, this segment is the only place where you increment the value of i. The variable i is used to determine which slot of array arr you are writing to, and should be incremented for each loop iteration. However, doing so without checking the value of I will force the program to increment i at the last iteration of the loop, "initializing" an extra slot at the end.
10th Dec 2018, 10:41 PM
Hatsy Rei
Hatsy Rei - avatar
+ 4
(cont) This, of course, is a sloppy fix. Instead of using a fixed-size array, I would suggest utilizing vectors, which allow you to append elements dynamically.
10th Dec 2018, 10:43 PM
Hatsy Rei
Hatsy Rei - avatar
0
Nothing?
12th Dec 2018, 5:55 AM
FireLion137