C Program, Array inside a case in continuous Switch Menu loop - c

My array inside case 4 in looping Switch Menu doesn't print/display the value of the last array when the user input goes beyond array[4].
I tried to take the case 4 out and make it a single program to check if it doesn't really work on its own but it works fine, but when I put it back into the Switch, same issue again. I thought that maybe the initialization part is the problem. Help
`
#include <stdio.h>
int main ()
{
char first[20],last[20];
float math,eng,sci,avg;
int a,b,c,d,diff,array[diff],e,i,input;
do{
printf("\nMAIN MENU\n");
printf("[1] Basic Input Output\n[2] Conditional Statement\n[3] Looping Construct\n[4] Array\n[5] About\n[6] Exit");
printf("\n\nChoose: ");
scanf("%d",&input);
printf("\n");
switch (input)
{
case 1:
printf("\nEnter your given name:");
scanf("%s",first);
printf("Enter your surname:");
scanf("%s",last);
printf("\nHello %s %s!\n",first,last);
break;
case 2:
printf("\nEnter your grade in Math:");
scanf("%f",&math);
printf("\nEnter your grade in Science:");
scanf("%f",&sci);
printf("\nEnter your grade in English:");
scanf("%f",&eng);
avg=(math+eng+sci)/3;
if(math>eng&&sci)
{
printf("\nHighest grade is in: Math");
}
if(eng>math&&sci)
{
printf("\nHighest grade is in: English");
}
if(sci>eng&&math)
{
printf("\nHighest grade is in: Science");
}
if(math==eng)
{
printf("\n--Math and English tied grades--");
}
if(math==sci)
{
printf("\n--Math and Science tied grades--");
}
if(eng==sci)
{
printf("\n--Science and English tied grades--");
}
printf("\nYour average in 3 subjects:%f\n",avg);
break;
case 3:
printf("Enter beginning number: ");
scanf("%d",&b);
printf("Enter ending number: ");
scanf("%d",&c);
printf("\nCounting from %d to %d\n",b,c);
while(b<=c)
{
printf("%d ",b);
b++;
}
printf("\n");
break;
case 4:
printf("Enter Starting Series of Numbers: ");
scanf("%d",&a);
printf("Enter Ending Series of Numbers: ");
scanf("%d",&d);
diff=(d-a);
array[diff]=d;
printf("Select Array Value to Display: 0 to %d: ",diff);
scanf("%d",&e);
for(i=0;i<=diff;i++)
{
array[i]=a;
if(i==e)
{
printf("%d\n",array[i]);
}
a++;
}
break;
case 5:
printf("Abouts\n");
break;
case 6:
printf("Thank you!");
break;
}
}while(input != 6);
return 0;
}
`

This should be a comment, but I donĀ“t have enough reputation yet.
As Gerhardh said, the problem is that you use diff before being initialized (which causes undefined behaviour)
As you said, if you move the initialization of array inside the case 4: after diff being set the program should work as intended. If you want to keep it before the switch, try using int* and malloc/free inside the case 4: (and add #include <stdlib.h>) Anyway, you should check diff as positive value before using it to set the size of array
About optimizing the code, you can skip the line array[diff]=d; because you are setting the same value inside the for loop. And you can remove the line a++; if you changes array[i]=a; -> array[i]=a+i;

Related

Can someone explain me whats wrong with finding total part in this code

Whenever I run this I got something like ' 196875307' as the total, could
someone tell me whats wrong with it.Here I uploaded the whole code.It says my post is mostly code and to add more details,So forgive me for typing these unnecessory things XD
#include <stdio.h>
int room;
char name[20];
int i;
void main()
{
int answr,fc[6],z=0,tot;
char ans;
char food[8][30]={"Bread","Noodles","Salad","Popcorn","Chocolate ice
cream","Vanilla ice cream","Cold Coffee","Milk Shake"};
int price[8]={180,120,65,55,70,70,110,200};
printf("\n *********");
printf("\n MENU CARD");
printf("\n *********\n\n\n\n");
printf("\n Food Code\t\tprice\t\t Food Name\n");
for(i=0;i<8;i++)
{
printf("\n\t\t%d",i+1);
printf("\t\t%d",price[i]);
printf("\t\t%s",food[i]);
}
printf("\n\n\n\t *PRESS 0 TO GO TO THE MAIN MENU\n\t *PRESS 1 TO ORDER
FOOD");
scanf(" %d",&answr);
switch(answr)
{
case 0:
{
printf("Enter the main menu function here");
break;
}
case 1:do
{
printf("ENTER THE FOOD CODE YOU WANT TO HAVE :: ");
scanf(" %d",&fc[z]);
z++;
tot=tot+fc[z];
printf("total so far is %d",tot);
printf("DO YOU WANT MORE(Y/N) ::");
scanf(" %c",&ans);
}while((ans=='y')||(ans=='Y'));
printf("\nEnter your room number:");
scanf(" %d",&room);
printf("\nEnter your name:");
scanf(" %s",&name);
}
}
The issue lies in your do loop. You need to initialize tot to 0, and use the user-inputted "food code" as an array index into your price array. I don't see any use for the "fc" array you've declared. This code should work for case 1 in your switch statement.
Remember that the main function returns an int in C.
do {
tot = 0;
printf("ENTER THE FOOD CODE YOU WANT TO HAVE :: ");
scanf("%d", &z);
if (z < 1 || z > 8) {
printf("Invalid food code\n");
return -1; // main should return int in a C program
}
tot=tot+price[z-1];
printf("total so far is %d\n",tot);
printf("DO YOU WANT MORE(Y/N) ::");
scanf(" %c",&ans);
} while((ans=='y')||(ans=='Y'));
I think that you should increment your counter z after you do the addition of the total with your freshly added element into the array.
1)Get the value by scanf
2)add it by using vet[z]
3)increment z.
When your code hit the sum it will try to access to a segment of memory that is filled with some other values.

How can I delete an element of string array in C

case 3 is the troubled zone, an integer array is working, it's fine, but "first" and "last" string arrays aren't working at all. I don't know how to solve it.
I have to use only stdio.h and stdlib.h libraries."first" and "last" are 2d char pointers, I'd like to 20 elements and maximum 30 characters.Adding ,and editing are fine it's working, but "first[temp]=first[temp+1];" this code cause compiler error when I try "strcpy(first[temp],first[temp+1]);" there is no compiler error.
Eventually using strcpy. when I want to delete the strings remain the same, and the integers take the value of 0
int main(){
printf("Welcome to address book ! \n ");
printf("--------------------------------------------------------\n");
int a=0;
int temp=0;
char* first[20][30];
char* last[20][30];
int n[20];
int g=0;
while(a<=1000){
int b=0;
printf("What do you want? \n");
printf("1-New ID\n2-Edit ID\n3-Delete ID\n4-List All ID's\n5-Close the Program\n");
printf("--------------------------------------------------------\n");
scanf("%d",&b);
switch(b){
case 1:
printf("Enter Fist Name \n");
scanf("%s",&first[g]);
printf("Enter Last Name\n");
scanf("%s",&last[g]);
printf("Enter Student Number\n");
scanf("%d",&n[g]);
g++;
a++;
continue;
case 2:
printf("Which user you want to change ?\n");
printf("user sequence :");
scanf("%d",&temp);
temp=temp-1;
printf("Listed First Name : %s\n",first[temp]);
printf("New First Name : ");
scanf("%s",&first[temp]);
printf("Listed Last Name : %s\n",last[temp]);
printf("New Last Name : ");
scanf("%s",&last[temp]);
printf("Listed Number : %d\n",n[temp]);
printf("New Listed Number : ");
scanf("%d",&n[temp]);
temp=0;
a++;
continue;
case 3:
printf("which user do you want to delete :");
scanf("%d",&temp);
if(temp+1<=g){
// first[temp]=first[temp+1];
// last[temp]=last[temp+1];
n[temp]=n[temp+1];
}
else
printf("unavailable");
a++;
continue;
case 4:
printf("--------------------------------------------------------\n");
int u;
for(u=0;u<g;u++){
printf(">%d.user. ",u+1);
printf("%d\t",n[u]);
printf("%s\t",first[u]);
printf("%s\n",last[u]);
}
printf("\n--------------------------------------------------------\n");
a++;
continue;
case 5:
printf("\nThank you for the use this program !\n ");
temp= 1000-a;
a= a+temp;
a++;
continue;
}
}
return 0;}

C code, what am I missing for this control statement program?

I am working on a program. This is what I am attempting to achieve;
The program should present a menu of pay rates from which to choose. Use a switch to select the pay rate. The beginning of a run should look something like this:
If choices 1 through 4 are selected, the program should request the hours worked. The program should recycle until 5 is entered. If something other than choices 1 through 5 is entered, the program should remind the user what the proper choices are and then recycle. Use #defined constants for the various earning rates and tax rates.
This is the code I have so far, what am I missing?;
#include <stdio.h>
#include <stdlib.h>
int main()
{
int choice, hour;
float taxe, total;
printf("****************************************************************\n");
printf("\nEnter the number corresponding to the desired pay rate or action");
printf("\n1)$8.75/hr");
printf("\n2)$9.33/hr");
printf("\n3)$10.00/hr");
printf("\n4)$11.20hr");
printf("\n5)Quit");
printf("**********************************************************\n");
scanf("%d", &choice);
printf("Please enter number of hours: ");
scanf("%d", &hour);
switch(choice){
case 1:
total = 8.75* hour;
break;
case 2:
total = 9.33*hour;
break;
case 3:
total = 10.00*hour;
break;
case 4:
total = 11.20*hour;
break;
case 5:
break;
return 0;
}
}
what am I missing?
What you are missing is the actual iteration.
The program should recycle until 5 is entered.
This means that you have to do all your work inside a loop, which will check each time if the value read is 5, which you need in order to stop iterating. You can use one of the following ways :
while loop:
scanf("%d", &choice);
while (choice != 5)
{
....
switch(choice){
....
}
....
scanf("%d", &choice);
}
for loop:
for (scanf("%d", &choice); choice != 5; scanf("%d", &choice);)
{
....
switch(choice){
....
}
....
}
do-while loop:
do{
scanf("%d", &choice);
....
switch(choice){
....
}
....
}while(choice != 5);
You did'nt used a loop. It can't recycle until 5 entered.
After taking the choice, insert a while loop :
while(choice != 5){
and process normally your switch, ignoring the 5 value, adding a "default" case if another value is entered.
If you want the total program to recycles, use a do{} while(); starting on your printf, ending afgter the switch.
you have yo use do while loop here like below
do
{
clrscr();
printf("****************************************************************\n");
printf("\nEnter the number corresponding to the desired pay rate or action");
printf("\n1)$8.75/hr");
printf("\n2)$9.33/hr");
printf("\n3)$10.00/hr");
printf("\n4)$11.20hr");
printf("\n5)Quit");
printf("**********************************************************\n");
scanf("%d", &choice);
printf("Please enter number of hours: ");
scanf("%d", &hour);
switch(choice){
case 1:
total = 8.75* hour;
break;
case 2:
total = 9.33*hour;
break;
case 3:
total = 10.00*hour;
break;
case 4:
total = 11.20*hour;
break;
case 5:
break;
default :
printf("\n please enter proper choice");
getch();
}
}while(choice !=5);

Not asking for char "choose" Before switch statement [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
This code executes itself without asking for char "choose" for further processing before the switch statement scanf("%c",&choose); switch(choose).
printf("enter option 1,2,3 or 4 \n\n");
scanf("%c",&choose); // why it not ask to input char
switch(choose)
{
case '1': case '+':
{
printf("enter 1st value\n");
scanf("%f",&a);
printf("enter 2st value\n");
scanf("%f",&b);
c=a+b;
printf("%f + %f = %f",a,b,c);
break;
}
case '2': case '-':
{
printf("enter 1st value\n");
scanf("%f",&a);
printf("enter 2nd value\n");
scanf("%f",&b);
c=a-b;
printf("%f - %f = %f",a,b,c);
break;
}
case '3': case'*':
{
printf("enter 1st value\n");
scanf("%f",&a);
printf("enter 2nd value\n");
scanf("%f",&b);
c=a*b;
printf("%f * %f = %f",a,b,c);
break;
}
}
printf("enter option 1,2,3 or 4 \n\n");
scanf("%c",&choose);
In your code if you are using any scanf before the above given code, then this behaviour is expected as the previous scanf reads the input leaving \n in the input buffer which is feeded as input to next scanf.
To overcome this issue please use fflush(stream) before scanf(...), this should solve the problem.
fflush(stdin);
or you can use getchar() function, this will alse solve your the issue.
Probably because you've already input something earlier, so that there are non-scanned characters left in the buffer which this "greedy" scanf() then scans without stopping.
You should check the return value of scanf() to learn if it succeeded or not.
And you should switch to using fgets() to read in a whole line, and then parse that. It's much safer and easier to predict, that way.
I've executed it without any problems (it gets the "choose" char):
#include <stdio.h>
int main(int argc, char *argv ) {
char choose;
float a,b,c;
printf("enter option 1,2,3 or 4 \n\n");
scanf("%c",&choose); // why it not ask to input char
switch(choose)
{
case '1': case '+':
{
printf("enter 1st value\n");
scanf("%f",&a);
printf("enter 2st value\n");
scanf("%f",&b);
c=a+b;
printf("%f + %f = %f",a,b,c);
break;
}
case '2': case '-':
{
printf("enter 1st value\n");
scanf("%f",&a);
printf("enter 2nd value\n");
scanf("%f",&b);
c=a-b;
printf("%f - %f = %f",a,b,c);
break;
}
case '3': case'*':
{
printf("enter 1st value\n");
scanf("%f",&a);
printf("enter 2nd value\n");
scanf("%f",&b);
c=a*b;
printf("%f * %f = %f",a,b,c);
break;
}
}
return 0;
}
Probably its something you didn't read before...
I'm guessing that you are doing a similar "scanf("%c",&choose);" before, so the next read you will get the carriage return.
You could try to change the following lines:
scanf("%c",&choose);
for:
scanf("%c%*c",&choose);
...so you discard the \n
If this don't solve your issue, maybe you should provide more code :)

Last array number keeps going wrong after switch statment

For example if i enter: "123456-7". The output at the first print statement would be: "123456-7" and at the 2nd print statement it would be "7". Which is correct.
But at any point after the break if I print the array again the print statement would go wrong in the last digit. It would look like: "123456-1" and the second would look like "1".
#include <stdio.h>
int main()
{
int lotoNumbers[6];
int ticketNumbers[6];
char option;
while(option != 'C')
{
printf("Your option:");
scanf(" %c", &option);
switch(option)
{
case 'W': printf("Please enter todays winning ticket number:");
scanf("%1d%1d%1d%1d%1d%1d-%1d", &lotoNumbers[0], &lotoNumbers[1], &lotoNumbers[2], &lotoNumbers[3], &lotoNumbers[4], &lotoNumbers[5], &lotoNumbers[6]);
printf("Your loto ticket number is: %d%d%d%d%d%d-%d\n", lotoNumbers[0], lotoNumbers[1], lotoNumbers[2], lotoNumbers[3], lotoNumbers[4], lotoNumbers[5], lotoNumbers[6]);
printf("----The following numbers matched! %d\n", lotoNumbers[6]);
break;
case 'T': printf("Please enter your ticket number:");
scanf("%1d%1d%1d%1d%1d%1d-%1d", &ticketNumbers[0],&ticketNumbers[1],&ticketNumbers[2],&ticketNumbers[3],&ticketNumbers[4],&ticketNumbers[5],&ticketNumbers[6]);
printf("Your loto ticket number is: %d%d%d%d%d%d-%d\n", ticketNumbers[0], ticketNumbers[1], ticketNumbers[2], ticketNumbers[3], ticketNumbers[4], ticketNumbers[5], ticketNumbers[6]);
break;
case 'C': printf("Computing....\n");
break;
case 'Q': printf("The program will now quit. Thank you for playing LOTO 649.\n");
return (0);
break;
default: printf("You entered an invalid option. The program will now terminate.\n");
return (0);
}
}
printf("The numbers are:%d%d%d%d%d%d-%d\n", lotoNumbers[0], lotoNumbers[1], lotoNumbers[2], lotoNumbers[3], lotoNumbers[4], lotoNumbers[5], lotoNumbers[6]);
printf("The number is: %d\n", lotoNumbers[6]);
return 0;
}
You didn't allocate enough space for your arrays. The number used to allocate space for an array is the number of entries in the array, not the last index number. Index 6 is the 7th item and is past the end of the array. The value of lotoNumbers[6] is undefined and can change randomly, because the program is using that memory for something else.
int lotoNumbers[6];
int ticketNumbers[6];
That 6 should be 7.

Resources