Jump to content
  • Advertisement
Sign in to follow this  
atomicajay

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.

If you intended to correct an error in the post then please contact us.

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 this post


Link to post
Share on other sites
Advertisement
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 this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!