Home > database >  Learning C basics and need some help:
Learning C basics and need some help:

Time:10-30

Basically, I'm trying to create a program where you can read up to 100 inputs from the keyboard. The inputs must be numbers between [1,100] and when "0" is entered, the program exits the loop and displays an array of all the numbers entered except the number zero. I'm trying to work with "while,for,if" statements but it's a bit difficult to understand the logic. Could you guys help me and give me some tips and feedback? Sorry for my ignorance but I'm programming for the first time.

#include <stdio.h>

int main(){

    int long ship;
    int array[100];
    
    for(ship = 0; ship < 100; ship  ){
        printf("Repaired ship: ");
        scanf("%li", &ship[array]);

        while(ship[array] == 0){
            printf("\n\t");
            for(ship = 0; ship < 100; ship  )
                printf("%li ", ship[array]);
            printf("\n\nRepaired ships: %li", ship);
        }
    }

    if(ship == 100){
        printf("\n\t");
        for(ship = 0; ship < 100; ship)
            printf("%li ", ship[array]);
        printf("\n\nRepaired ships: %li", ship);
    }
    return 0;
}

CodePudding user response:

Below, I have re-edited your code with minor corrections. Use comments mentioned below the code to understand those corrections. Hope this helps!

CODE

  #include <stdio.h>

int main(){

    int ship;  
    int long array[100]; 

    for(ship = 0; ship < 100; ship  )
    {
        printf("Repaired ship: ");
        scanf("%ld", &array[ship]);   

      if(array[ship]==0)  
      break;
    }

      ship=0;  

      while(array[ship] != 0) 
        {
            printf("\n\t");

            printf("%ld ", array[ship]);
           ship  ;
        }

        printf("\n\nRepaired ships: %d", ship);
        
       return 0;
}

long int is not needed for ship as 100 is not that big value

long int(if required) will be used for array as used above

%ld is the format specifier for long int

for loop above deals with input taking

no need of for loop in while as while loop already deals with required output

use array[ship] type notation instead of ship[array] as array[ship] notation is more common

**//this portion of if statement not needed as while loop already dealt with it

      if(ship == 100){

  printf("\n\t");

  for(ship = 0; ship < 100; ship)

     printf("%li ", ship[array]);

 printf("\n\nRepaired ships: %li", ship);

}**

  • Related