While loop not stopping in C programmming - c

int math=0,phy=0,che=0,avg=0,cprg=0,n,i=1,sum=0,large;
char name, roll_no, dept;
printf("\n How many students : ");
scanf("%d", &n);
while(i<=n)
{
printf("NAME : ");
scanf("%s", &name);
printf("DEPARTMENT :");
scanf(" %s", &dept);
printf("ROLL NUMBER :");
scanf("%s", &roll_no);
printf("☻ MATHS MARK :");
scanf(" %d", &math);
printf("☻ PHYSICS MARK : ");
scanf("%d", &phy);
printf("☻ CHEMISTRY MARK :");
scanf(" %d", &che);
printf("☻ C Programming :");
scanf(" %d", &cprg);
printf("\n");
avg = math+phy+che+cprg;
avg=avg/4;
append(&head, avg);
i++;
}
return 0;
}
Here is some of my code. I need to run this loop for the number of times the user enters in the input,
and the loop is not ending in VS Code even though it works fine in online GDB.

Your variables name, roll_no, and dept are just a single character, but you treat them (with scanf) as though they are strings. I think you want to declare them as strings as follows:
char name[50], roll_no[10], dept[10];
adjusting the string sizes as needed to hold the data. Because you are writing data beyond what is allocated you get undefined behavior.
You will also need to remove the & in the scanf call for each of these variables, e.g.:
scanf("%49s", name);

Related

How do I repeat entering data in a struct using C?

I'm new to C, and currently trying to practice on some simple codes, and I'm currently stuck with that next one.
After entering the first customer data, and repeat the code... View_customer function fails to show the saved data, and when I try to go to enter a second account data, it fails at the second entry.
#include<stdio.h>
#include<stdlib.h>
typedef struct cust{
char name[60];
int acc_no,age;
char address[60];
char citizenship[15];
double phone;
char acc_type[10];
} cust;
void new_account(int num);
void view_account(int num);
int main()
{
cust customers[10];
char answer;
int n;
int cutomer_number=1;
int cutomer_num2;
printf("Welcome To The program X: \n");
do{
printf("\n How can we serve you today? \n 1.Create a new account \n 2.Print an existing Account info \n ");
scanf("%d",&n);
if (n==1)
{
new_account(cutomer_number);
cutomer_number++;
}else {
printf("Please enter your Cust number: ");
scanf(" %d",&cutomer_num2);
view_account(cutomer_num2);
};
printf("\n Press Y to continue. Press any Key To Exit: ");
scanf(" %c",&answer);
}while (answer == 'Y' || answer == 'y');
return 0;
}
void view_account(int n)
{
cust customers[n];
printf("Your name is %s \n ", customers[n].name);
printf("Your age is %d \n", customers[n].age);
printf("Your address is %s \n", customers[n].address);
printf("Your citizenship is %s \n", customers[n].citizenship);
printf("Your phone number is %f \n", customers[n].phone);
printf("Your account type is %s \n", customers[n].acc_type);
};
void new_account(int n)
{
cust customers[n];
customers[n].acc_no = n;
printf("You are the customer number %d \n", customers[n].acc_no);
printf("Please, Enter your name: ");
scanf("%s", &customers[n].name);
printf("Please, Enter your age:");
scanf(" %d", &customers[n].age);
printf("Please, Enter your address: ");
scanf(" %s", &customers[n].address);
printf("Please, Enter your citizenship: ");
scanf(" %s", &customers[n].citizenship);
printf("Please, Enter your phone number: ");
scanf(" %f", &customers[n].phone);
printf("Please, Enter your account type: ");
scanf(" %s", &customers[n].acc_type);
}
>
Each of your three functions declares its own customers array variable, so each of them has their own memory for the customer data. Moreover, the array of new_account goes out of scope at the end of the function, so you can no longer safely access the data. Because of how C compilers typically work, the customer data is not immediately erased from memory, so your view_account function might still be able to read it, but that is what is called "undefined behavior". Which means it might work, or it might not.
Try to pass down the array from the main function to the other two functions in parameters. Or, to make things simpler at first, you could also turn the local customers variable of main into a global variable.
cust customers[10];
int main(int argc, char *argv[])
{
char answer;
int n;
int cutomer_number=1;
int cutomer_num2;
printf("Welcome To The program X: \n");
...
}
void view_account(int n) {
printf("Your name is %s \n ", customers[n].name);
...
}
void new_acccount(int n)
{
customers[n].acc_no = n;
...
}
Note that there are further issues in your code, like not checking the return value of scanf or overflowing the char arrays of the struct if you enter too many characters (missing bounds and length checking), or being able to enter more than 10 customers and accessing out of bounds of the customers array, or not using customers[0] (because your customer_number starts at 1, but array indices are 0-based). But I will not go into further details here to keep the answer focused.

Though my program runs, the variables(age and favourite_number) are not highlighted and in the problem section it highlights a problem

`#include <stdio.h>
int main(){
char firstInitial , lastInitial;
int age , favourite_number;
printf("Enter Initial character of your name : \n");
scanf(" %c" ,&firstInitial );
printf("Enter initial character of your surname : \n");
scanf(" %c" , &lastInitial);
printf("Enter your age : \n");
scanf(" %d",&age);
printf("Enter your favourite number : \n");
scanf(" %d",&favourite_number);
printf("Your name is %c.%c. and your age is %d.\n", firstInitial , lastInitial ,age);
printf("Your favourite number is %d \n", favourite_number);
return 0;
}`There is an error mentioned in the problem section even though I have put the semicolon and the program runs.
Why are the variables not highlighted?

How do I get multiple lines to print after ending this logical loop

Me again. The C rookie. I am working on an assignment to write a program that prompts a user to enter info after which the program should list back out the data that was entered. My code only prints the last record info that is entered.
For example, I enter the following info for employee #1 "Rookie Coder" as the first employee name and enter 25 and 40 for hourly wage and hours worked, respectively. Then, I enter the following info for employee #2 "Slow Learner" as the 2nd employee name and enter 20 and 45 for hourly wage and hours worked, respectively. The program only prints the info related to "Slow Learner". But I want to print out the info for both records entered.
Can someone please offer guidance on what I'm missing to get both records to print? Thank you from the C Rookie
// C Libraries Used
#include <stdio.h>
#include <math.h>
#include <string.h>
// Constant declerations
const float OTPAYFACTOR = 1.5;
FILE *userinputfile; //disk file (for input)
// Variable declerations
char deptname [21];
char firstname [10];
char lastname [10];
char fullname [21];
float hrsworked;
float hrwage;
int count;
char again;
// Function Prototypes
// M A I N F U N C T I O N
int main (void){
printf("Mountain Pacific Corporation\nDepartment Salary Program\n\n");
printf("Please enter the name of the department: ");
scanf("%s", &deptname);
count = 0; // Initialize this "counting" variable to zero to start
printf("\n");
count = 0; // Initialize this "counting" variable to zero to start
printf("\n");
do {
count++; // Increment the counting variable
printf("Enter employee #%d: ", count);
scanf("%s %s", &firstname, &lastname);
strcpy(fullname, firstname);
strcat(fullname, " ");
strcat(fullname, lastname);
printf("Enter the hourly wage of %s: ", fullname);
scanf("%f", &hrwage);
printf("Enter total number of hours: ");
scanf("%f", &hrsworked);
printf("\nThank you. Process another employee? ");
scanf ("%s", &again);
printf("\n");
} while (again != 'N' && again != 'n');
printf("End of processing.");
printf("%s, $%0.2f, %0.2f: \n", fullname, hrwage, hrsworked);
return 0;
}
You only have one set of variables that you use on each iteration of the loop. Anything stored the first time through the loop is overwritten the second time through the loop. So you'll only ever store the most recently entered set of values.
You want to declare each of the variables that are taking data as an array, that way you can save multiple values.
char deptname [5][21];
char firstname [5][10];
char lastname [5][10];
char fullname [5][21];
float hrsworked[5];
float hrwage[5];
...
do {
printf("Enter employee #%d: ", count+1);
scanf("%s %s", &firstname[count], &lastname[count]);
strcpy(fullname[count], firstname[count]);
strcat(fullname[count], " ");
strcat(fullname[count], lastname[count]);
printf("Enter the hourly wage of %s: ", fullname[count]);
scanf("%f", &hrwage[count]);
printf("Enter total number of hours: ");
scanf("%f", &hrsworked[count]);
printf("\nThank you. Process another employee? ");
scanf ("%s", &again);
printf("\n");
count++; // Increment the counting variable
} while (again != 'N' && again != 'n');
Then you need to loop through the array to print each element:
int i;
for (i=0; i<count; i++) {
printf("%s, $%0.2f, %0.2f: \n", fullname[i], hrwage[i], hrsworked[i]);
}
:) naive from your side but don't worry. You are storing only the last data into the fullname, hrwage, hrsworked, so only the last output is saved there. You need a better data structure to store the data as they are inserted by user.
1) If you know how many inputs there will be you can use a predefined array of strings for strings for the name and floats for the hours and wage.
2) if you don't know then you will need an scaling data structure like for example a list in order to put/add/append elements to it ;)
for C Arrays check this and for Lists in C check this
Then last but not least after you fill them with the input you just need to loop with a for / while loop in order to print the array or list.
Hope this will help!
remove the & symbol from below statement because deptname itself is string
scanf("%s", &deptname);
do same from below statements also
scanf("%s %s", &firstname, &lastname);
you want to print all records but at last there is only one printf so obviously it prints only last employee records
printf("%s, $%0.2f, %0.2f: \n", fullname, hrwage, hrsworked);
if you wants to prints all employee data after giving 'N' option, you should store information before that, my suggestion is put all entries inside structure and then take array of structure and store every time.

Simple read/display C program outputs incorrect value while user inputs data

Can someone run the following C program on your IDE and advise me what I am missing?.
#include<stdio.h>
#include<conio.h>
int main()
{
int a;
char s;
char n[10];
printf("What is your name?: ");
scanf("%s", &n);
printf("What is your age?: ");
scanf("%d", &a);
printf("Are you male or female?: ");
scanf("%c", &s);
printf("Your name is %s\nYour age is %d\nYour sex is %c\n", n, a, s);
getch();
return 0;
}
While we enter the age and hit the enter button, it slips and shows wrong output without evening asking for the third input "Are you male or female?". I tested it on Turbo C++, Dev C++, Code Blocks, all show the same error output.
Your problem is that the scanf("%c", &s); takes the new-line character. Maybe you could try the following scanf(" %c", &s); (important ist the white-space before %c) as described here Problems with character input using scanf() or How to do scanf for single char in C
It would be correctly to write
printf("What is your name?: ");
scanf("%s", n);
^^^
or even
printf("What is your name?: ");
scanf("%9s", n);
instead of
printf("What is your name?: ");
scanf("%s", &n);
and
printf("Are you male or female?: ");
scanf(" %c", &s);
^^^
instead of
printf("Are you male or female?: ");
scanf("%c", &s);
Otherwise in the last case a white space character is read into the variable s.

C program, designing a check

I'm writing a program that basically just takes a bunch of user input and Outputs it in the form of a check. My problem is that I'm entering 2 sentences and while the second one is fine it completly skips the first one! and the user last name is working but the first name just outputs "z" it is the weirdest thing and my teachers philosophy is figure it out yourself. So can anyone possibly help me?? Here is my code...
#include<stdio.h>
#include<string.h>
int main()
{
char date[8];
int checkNum;
char payeeFirst[10];
char payeeLast[10];
double amount;
char memo[50];
char wordAmount[100];
printf("Please enter the date: ");
scanf("%s", &date);
printf("Please enter the check number: ");
scanf("%d", &checkNum);
printf("Please enter the payee First name: ");
scanf("%s", &payeeFirst);
printf("Please enter payee last name: ");
scanf("%s", &payeeLast);
printf("Please enter amount: ");
scanf("%d", &amount);
printf("Please enter amount in words: ");
fgets (wordAmount, sizeof(wordAmount)-1, stdin);
printf("Please enter memo: ");
fgets (memo, sizeof(memo)-1, stdin);
printf(" \n");
printf("Date: %s .\n", date);
printf("Check Number: %d .\n", checkNum);
printf("Payee: [%s] [%s] .\n", payeeFirst, payeeLast);
printf("Amount: %d .\n", amount);
printf(" Check %d \n", checkNum);
printf(" Date: %s \n", date);
printf("Pay to the\n");
printf("Order of %s %s $%d \n", payeeFirst, payeeLast, amount);
printf("%s", wordAmount);
printf(" \n");
printf(" \n");
printf("Memo: %s \n", memo);
return 0;
}
Your scanf calls all leave the '\n' in the stream (the next scanf will ignore it though).
The first fgets reads an empty string (well ... a string containing a single '\n').
Try reading the numbers with fgets too (to a temporary buffer) and sscanf from the buffer to the correct variable. This way all the '\n' will be accounted for.

Resources