Different variables in for loop | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 3

Different variables in for loop

guys, for example i have 10 value called, p1, p2, p3, p4... and I want to change their value, Can't I change their value in for loop. I mean, can't it be like that, for (int i=0; i<11; i++) pi = 10; something like that.

27th Jan 2018, 7:48 PM
Mustafa K.
Mustafa K. - avatar
3 Answers
+ 17
u have to use array for that 1)run a loop for number of elements u have & assign value in each run
27th Jan 2018, 9:10 PM
Gaurav Agrawal
Gaurav Agrawal - avatar
+ 2
What you could do is try setting all of your values into a dictionary or an array, and go through them using the loop. My example in C++: int list = new int[100]; for(int i=0;i<10;i++){ list[i] = i + 5; }
27th Jan 2018, 7:59 PM
Faisal
Faisal - avatar
+ 2
The method stated in your question won't work in almost every programming language. The reason is the compiler will treat pi as a variable, and variable name cannot be changed in most programming languages (which means you cannot change the name from pi to p1, p2 etc). We usually handle this by using array in C++. Faisal's example is better cause he uses dynamic memory allocation, but you can try this if you are new to C++ and don't understand his example: int p[10]; for(int i = 0; i < 10; i++) { p[i] = 10; }
27th Jan 2018, 9:59 PM
Hanz
Hanz - avatar