I am very new to programming.
I am trying to write a program that will call the price of fruit from an array. But I would like the code to also write the name of the fruit before writing the price like. If I type 2, how do make the output be "Orange price: 10" rather than just price: 10.
#include <stdio.h>
int main(void)
{
int i;
int a[3] = { 5,10,15 };
printf("1) Apple");
printf("2) Orange");
printf("3) grape");
while (1) {
printf("Which fruit would u like : ");
scanf("%d", &i);//Enter the fruit number
if (i <= 0 || i >= 4) {
printf("\nPlease use the correct number :");
}
else {
printf("Price :%d", a[i]);
break;
}
}
}
Just define an array of names like
int a[3] = { 5,10,15 };
const char *fruit[] = { "Apple", "Orange", "grape" };
and use it in a printf call. For example
printf( "%s price: %d", fruit[i], a[i] );
And these statements
printf("1) Apple");
printf("2) Orange");
printf("3) grape");
can be rewritten like
for ( i = 0; i < N; i++ )
{
printf( "%zu) %s\n", i + 1, fruit[i] );
}
Take into account that this if statement
if (i <= 0 || i >= 4) {
is incorrect. There must be
if (i < 0 || i > 2) {
Also it is a bad idea to use magic numbers.
You could write instead.
enum { N = 3 };
int a[N] = { 5,10,15 };
const char *fruit[N] = { "Apple", "Orange", "grape" };
size_t i = 0;
//...
scanf("%zu", &i);//Enter the fruit number
if ( !( i < N ) ) {
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.