Sign in to follow this  
atomicajay

help me newbie

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[i] << " ." << 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
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

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this