0
#include <stdio.h>

struct Car {
  char brand[50];
  char model[50];
  int year;
};

int main() {
  struct Car car1 = {"BMW", "X5", 1999};
  struct Car car2 = {"Ford", "Mustang", 1969};
  struct Car car3 = {"Toyota", "Corolla", 2011};

  printf("%s %s %d\n", car1.brand, car1.model, car1.year);
  printf("%s %s %d\n", car2.brand, car2.model, car2.year);
  printf("%s %s %d\n", car3.brand, car3.model, car3.year);

  return 0;
}

/*
BMW X5 1999
Ford Mustang 1969
Toyota Corolla 2011
*/

Here the struct only has 3 variables (car1, car2, car3). But if it had numerous cars, how could I make this same code (print all values) using a loop?

4
  • Are you trying to iterate over an array of Cars or the members of a Car? If it's the latter, then it's not possible in C. Commented Jun 4, 2022 at 4:39
  • maybe I expressed myself wrong (my english is not very good), but what I wanted was the same output.. but with a for or while loop, as it would be useful in case I have more cars, so I don't have to use 100 , 200, 1000 print commands... Commented Jun 4, 2022 at 4:45
  • You want an array of Cars Commented Jun 4, 2022 at 4:58
  • and how would you do it? could you help me? Commented Jun 4, 2022 at 5:02

2 Answers 2

2

You need an array of Cars, something like this

#include <stdio.h>

struct Car {
  char brand[50];
  char model[50];
  int year;
};

int main() {
    struct Car cars[] = {
        {"BMW", "X5", 1999},
        {"Ford", "Mustang", 1969},
        {"Toyota", "Corolla", 2011},
        {"Mercedes", "C197", 2010 }
    };

    for(size_t i = 0; i < sizeof(cars)/sizeof(cars[0]); ++i) {

        printf("%s %s %d\n", cars[i].brand, cars[i].model, cars[i].year);
    }

    return 0;
}
Sign up to request clarification or add additional context in comments.

Comments

0

You need an array of struct Car.

It works pretty much the same as any other array in with the difference that each element now has extra fields, the ones on your struct.

Here is an example:

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

#define SIZE 100

struct Car {
  char brand[50];
  char model[50];
  int year;
};


int main(void) {
    struct Car cars[SIZE];

    for (int i = 0; i < SIZE; i++) {
        // Initialize
        strcpy(cars[i].brand, "BMW"); // or any other brand
        strcpy(cars[i].model, "X5");

        cars[i].year = 1999;
    }

    for (int i = 0; i < SIZE; i++) {
        // Print
        printf("Car %d:\n", i + 1);
        printf("%s %s %d\n", cars[i].brand, cars[i].model, cars[i].year);
    }

    return 0;
}

Comments

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.