Click here to Skip to main content
15,896,444 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
i need to add a array terminator but dont have an idea how to swap my loops to it if its a terminator how do i print it in the next available slot to certify is correct?

#include <stdio.h>
#include <stdlib.h>

/* run this program using the console pauser or add your own getch, system("pause") or input loop */

int main(int argc, char *argv[]) {

    int arr[100]; 
    int i;  
    int x;
    printf("how many values would you like to imput :\n");
	scanf("%d", &x); 
	
    for(i=0; i<x; i++)  
    {  
	    printf("values array number %d : ",i);
        scanf("%d", &arr[i]);  
    }  
  
    printf("\n values inside the array arr: ");  
    for(i=0; i<x; i++)  
    {  
        printf("%d  ", arr[i]);  
    } 
    printf("\n");
	
return 0;
}


What I have tried:

i tried creating a rule with if and else but just come up error
Posted
Updated 30-Nov-17 21:52pm
v2
Comments
Patrice T 30-Nov-17 22:42pm    
You should ask where you have found that 'array terminator concept'.

In your code you must check that x is less than 100 like:
C++
for(i=0; (i<x) && (i<100); i++) 

Another and better option is:
C++
int *arr = new int[x];//dynamic allocation
//your code
delete arr;//cleanup
 
Share this answer
 
Remember to check the value of x is less than 100 when it is first entered.
C++
for(i=0; i<x; i++)
{
    printf("values array number %d : ",i);
    scanf("%d", &arr[i]);
}
arr[i] = -1; // set end of values marker. NB this only works if no values could be -1

printf("\n values inside the array arr: ");
for(i=0; arr[i] != -1; i++)  // use the marker as the loop terminator
{
    printf("%d  ", arr[i]);
}
printf("\n");
 
Share this answer
 
Array terminator for an int array, generally speaking, is NOT a good idea, because you use a valid item value (e.g. -1) for a different purpose (hence, in your code you have to be consistent. Moreover, if others use your code, then they must be well aware of such a convention). Anyway
C
#include <stdio.h>

#define SIZE 100

int main(int argc, char *argv[]) {

    int arr[SIZE];
    int i;
    printf("insert values (-1 to finish):\n");

    for (i=0; i<(SIZE-1); ++i)
    {
      printf("values array number %d : ",i);
      scanf("%d", &arr[i]);
      if ( arr[i] == -1) break;
    }

    arr[i] = -1; // the i==(SIZE-1) corner case

    printf("\n values inside the array arr: ");

    for (i=0; arr[i] != -1; ++i)
    {
        printf("%d  ", arr[i]);
    }
    printf("\n");

    return 0;
}
~  
 
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