1

How do i assign a value to a different variable every time the loop activates? I want to change the variable inside a scanf() so that when a new number is assigned to a different variable. Like in:

int a,b,c,i;

for(int i=1;i<=3;i++)

{

    printf("enter a number:");
    scanf("%d",&a);
}

The loop asks for numbers 3 times, and i want to enter 1,2, and 3. How can i assign them in a different variable each? Like 1 is assigned to a, b=2, and c=3?

1
  • 2
    You will need to use an array instead if you want to keep the loop. Commented Nov 5, 2020 at 6:48

2 Answers 2

2

You cannot change variable names at run-time, because simply they don't exist at runtime. If the type of inputs are of the same type, say, integer, you can use an array of integers to store multiple inputs.

Sample:

int array[3] = {0};

//input

for(int i=0;i<3;i++)
{
    printf("enter a number:");
    scanf("%d",&(array[i]));
}

//output

for(int i=0;i<3;i++)
{
    printf("Number %d is %d", i+1, array[i]);
}
Sign up to request clarification or add additional context in comments.

Comments

2

Thats what arrays were made for!

int numbers[3];

for(int i=0;i<3;i++)
{
    printf("enter a number:");
    scanf("%d",&numbers[i]);
}

Then your three numbers are available via:

numbers[0], numbers[1], numbers[2]

3 Comments

Almost. C arrays are zero indexed, so it's convention to use [0], [1], etc. Don't add in a dummy slot just to accommodate 1-based indexing. It's wasteful and looks like a bug.
@tadman and, numbers[0] value remain indeterminate.
@tadman you're right. I kept author's structure, hence the code. I've edited the answer not to confuse anybody.

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.