Reputation: 13
I have to write a program which will compare weight of persons with required weight. When the person's weight is greater than 65 then that first person will get selected and it will not check further.
#include <stdio.h>
#include <stdlib.h>
struct person {
int age;
float weight;
};
struct person p1 = {18, 60.2};
struct person p2 = {20, 80.8};
struct person p3 = {22, 75.4};
struct person p4 = {40, 65.9};
struct person p5 = {15, 40.2};
int main()
{
float requiredWeight = 65;
}
I am from Mechanical engineering so don't know much of coding. I can use if statement but my list is much longer so it will be tedious to type everything.
Upvotes: 1
Views: 50
Reputation: 9804
Make an array out of the people and iterate over them:
#include <stdio.h>
struct person {
int age;
float weight;
};
int main(void) {
struct person p[] = {{18, 60.2}, {20, 80.8}, {22, 75.4}, {40, 65.9}, {15, 40.2}};
const float requiredWeight = 65;
for (int i = 0; i < sizeof p /sizeof *p; ++i)
if (p[i].weight > requiredWeight)
{
printf("the %d. person weight too much\n", i + 1);
break;
}
return 0;
}
sizeof p /sizeof *p
results in the number of elements in the array p
.
Upvotes: 3