Sign in to follow this  
drjulio2002

How do I assign numbers to an array?

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

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