0

Let's say there is a variable that is letters[MAX], and I want to scan for each array index like letters[1], letters[2], etc. How is this done?

I tried doing a for loop something like

for (i = 0; i < MAX; i++)
{
   printf ("Letter: ");
   scanf ("%d", &letters[i]);
}

but this does not work properly. I mean it works, but it'll keep scanning until I reach whatever the MAX is (which is 100 in my program) and I tried putting it in a do while loop while (letters != 0) but it is outside of the for loop and doesn't end the loop when I enter 0.

So what I'm trying to do is assign a value to each array variable (letters[i]) by scanf'ing user input and ending the loop when 0 is entered, but the code I've tried does not work.

1
  • you want the address of letter[] or the value? Commented Nov 9, 2012 at 4:22

1 Answer 1

2

You can add

if(letters[i]=='0')
   break;

to the end of your for loop. This way it checks to see if the letter you just entered was a 0 character (hence the single quotes).

You end up with

for (i = 0; i < MAX; i++)
{
   printf ("Letter: ");
   scanf ("%d", &letters[i]);
   if(letters[i]=='0')
      break;
}
Sign up to request clarification or add additional context in comments.

2 Comments

hey i've run into another problem! I added 2 more array variables to my for loop so it looks like the code you gave me with the if statement added only with 2 more printf / scanf lines, and it is still the same if statement (if letters==0) but instead of letters ending the program when 0 is entered, it is the 3rd array variable that ends the program if 0 is entered even though letters is in the if statement!...EDIT: fixed it, i just added the if statement after the first scanf and put the other 2 below it and it fixed!
@user1808190 If you have a new question that's unrelated, it'd probably be better to finish this one and ask a new question. Either way, best to post code chunks in questions/answers, not comments. Also, accept the answers people give to you - other people have answered your other questions to your liking, so you should hit the checkmark for their answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.