Jump to content
  • Advertisement
Sign in to follow this  
drjulio2002

How do I assign numbers to an array?

This topic is 5134 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

Hello Everyone! I'm having a problem assigning numbers to an int array may be it's because I don't know how to do it right:
#include <stdio.h>

int main()
{
 int scores[10]={0}, count=0;
 scores[10]={16,19,20,22,25,39,40,41,49,50};

 for(count=0;count<9;count++)
 {
  if(scores[count] > 20 && scores[count] < 40)
   printf("%d",scores[count]);
 }
 return 0;
}

Share this post


Link to post
Share on other sites
Advertisement
Option 1 is to specify the contents at creation time:


#include <stdio.h>

int main()
{
int scores[10]={16,19,20,22,25,39,40,41,49,50};
int count=0;

for(count=0;count<9;count++)
{
if(scores[count] > 20 && scores[count] < 40)
printf("%d",scores[count]);
}
return 0;
}



Option 2 is to specify the contents 1 by 1:


#include <stdio.h>

int main()
{
int scores[10];
scores[0] = 16;
scores[1] = 19;
.
.
.
scores[8] = 49;
scores[9] = 50;
int count=0;

for(count=0;count<9;count++)
{
if(scores[count] > 20 && scores[count] < 40)
printf("%d",scores[count]);
}
return 0;
}


Share this post


Link to post
Share on other sites
Quote:
Original post by drjulio2002
Hello Everyone!

I'm having a problem assigning numbers to an int array may be it's because I don't know how to do it right:

*** Source Snippet Removed ***


The second line of this


int scores[10]={0}, count=0;
scores[10]={16,19,20,22,25,39,40,41,49,50};



won't compile IMO because you can only initialize an array like that. Once it's been initialized, this syntax doesn't work anymore. What you can do is assign value to individual positions in the array like so


scores[ 0 ] = 16;
scores[ 1 ] = 19;
// and so on ...



Make sure you array is large enough though or you'll get an access violation if you try to index out of bounds.

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.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!