Public Group

# help me newbie

This topic is 3219 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

#include <iostream>
using namespace std;

int main(){
int x = 11;
int y = 12;
int a[5];
int u = 31;
int v = 32;

//filling values
for(int j= 0; j < 5 ; j++){
for (int x = 21; x <= 25; x++)
a[j] = x;
}

cout << "Printing changed value " << endl;
for (int i = 0; i < 5 ; i++)
cout << "Value of " <<  i << " is " <<  a << " ." << endl;

system("pause");
return 0;
}

I am trying to change arrays value to 21,22,23,24,25 But it is showing all value 25 What is wrong

##### Share on other sites
Taking thi snippet:
for (int j= 0; j < 5 ; j++) {  for (int x = 21; x <= 25; x++)    a[j] = x;}

Consider what is happening if we unroll the inner loop:
for (int j= 0; j < 5 ; j++) {    a[j] = 21;    a[j] = 22;    a[j] = 23;    a[j] = 24;    a[j] = 25;}
See what's going on? :)

To find an algorithm that works, let's take a look at the results we're ultimately looking for:
a[0] = 21;a[1] = 22;a[2] = 23;a[3] = 24;a[4] = 25;
Notice the pattern, the relationship between the index of the array element and its desired value: value = index + 21.
Using our new found insight:
for (int j= 0; j < 5 ; j++) {    a[j] = j + 21;}

##### Share on other sites
Thanks a lot you helped me...
It is true we need to think logically in C++

1. 1
2. 2
3. 3
4. 4
Rutin
15
5. 5

• 13
• 26
• 10
• 11
• 9
• ### Forum Statistics

• Total Topics
633724
• Total Posts
3013554
×