Alok
Alok

Reputation: 9018

Printing elements of an array up to the key specified in C programming

I've been working on my coding skills and I have started my journey here. Since I'm stuck at one place and trying to figure it where I'm going wrong. The code goes like this:

#include<stdio.h>
int main(){
   int a[10],i,j,arr_size;

   printf("Enter the size of the array");
   scanf("%d",&arr_size);

   printf("Enter the array:");
   for(i=0;i<arr_size;i++)
   scanf("%d",&a[i]);

   //here key is 42
   //so we'll find the key and print the elements up to that
   for(j=0;j<arr_size;j++){
      if(j==42)
        break;

      //loop for the array up to the key
      for(i=0;i<j;i++)
      printf(" %d",a[i]);  
   }

   return 0; 
}

The output came was : The output of the above code

The output shows that the loop is going up to the key i.e., 42 but prints in a varied manner 1 1 2 1 2 42. Now this is strange.

The required output must be in format : 1 2 only if input is given 1 2 42 33

Upvotes: 0

Views: 641

Answers (3)

Arvindsinc2
Arvindsinc2

Reputation: 714

The bracket had been misplaced. This what you are looking for:

#include<stdio.h>
int main(){
   int a[10],i,j,arr_size;

   printf("Enter the size of the array");
   scanf("%d",&arr_size);

   printf("Enter the array:");
   for(i=0;i<arr_size;i++)
   scanf("%d",&a[i]);

   //here key is 42
   //so we'll find the key and print the elements up to that
   for(j=0;j<arr_size;j++){
        if(a[j]==42) 
          break;
    }
   //loop for the array up to the key
   for(i=0;i<j;i++)
    printf(" %d",a[i]);  


   return 0; 
}

Upvotes: 1

Nithin
Nithin

Reputation: 1424

Try this..

#include<stdio.h>
int main(){
   int a[10],i,j,arr_size;

   printf("Enter the size of the array");
   scanf("%d",&arr_size);

   printf("Enter the array:");
   for(i=0;i<arr_size;i++)
   scanf("%d",&a[i]);

   //here key is 42
   //so we'll find the key and print the elements up to that
   for(j=0;j<arr_size;j++){
        if(a[j]==42) 
          break;
    }
   //loop for the array up to the key
   for(i=0;i<j;i++)
    printf(" %d",a[i]);  


   return 0; 
}

this code will give the requied output.. 1 2

Upvotes: 5

Some programmer dude
Some programmer dude

Reputation: 409482

You don't check the array values for 42, you check the index.

The reason your loop prints what it prints now, is because the nested loops. You print (part of) the array multiple times.

Instead of the nested loop, you could do something simple like

for (int j = 0; j < arr_size && a[j] != 42; ++j)
{
    printf(" %d", a[j]);
}

I also recommend you add a check to make sure that arr_size is not out of bounds for your array.

Upvotes: 1

Related Questions