Click here to Skip to main content
15,898,222 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
i am trying to code a program but there is a problem in this code,the problem of storing and remembering 2(may be more) values in a single variable using for loop.
e.g-
C++
int a,i;
 for(i=0;i<2;i++){
   scanf("%d",&a);
 }
 for(i=0;i<2;i++){
    printf("%d ",a);
}

let we enter 3 5 using scanf but it prints 5 5.
but i want 3 5 how to do that. where is the problem.

What I have tried:

In this program variable a,should prints the entered values 3 5,but it returns both 5 5,how does it remember it when printing,print 3 first then print 5.
Posted
Updated 20-Mar-18 8:48am
v2

You have to use multiple variables or - if they are of same type - an array:
C++
#define MY_ARRAY_SIZE 2

int a[MY_ARRAY_SIZE];
for (i = 0; i < MY_ARRAY_SIZE; i++) {
    scanf("%d", &a[i]);
}
for (i = 0; i < MY_ARRAY_SIZE; i++) {
    printf("%d ", a[i]);
}
 
Share this answer
 
Either you merge the 2 loops:
C++
int a,i;
for(i=0;i<2;i++){
    scanf("%d",&a);
    printf("%d ",a);
}

Either you learn about arrays
Arrays in C[^]
C Arrays: Declare, Initialize and Access Elements (With Examples)[^]
 
Share this answer
 
Well, you could use a character array like this:

Kind of an end-around, but it would work.

int  a, i;
char inval[20], intxt[1000];

intxt[0] = 0; // <== NULL termination of string
for( i = 0; i < 2 ; i++ )
{
    inval[0] = 0; // <== Null terminate input just for safety
    printf( "Enter Item #%0d:", i ); 
    gets( inval );
    strcat( intxt, "=" );  // <== some token ('=')
    strcat( intxt, inval ); 
}

i = 0;
do
{
    if ( intxt[i] != 0 )
    {
        if ( intxt[i] == '=' )
        {
            sscanf( &intxt[i+1], "%d", &a ); 
            printf( "%d ", a );
        };
    };    
    
} while ( ( intxt[i] != 0 ) && ( i < 1000 ) );

printf( "\n" );


-Doug
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900