data types different in C - arrays

how to do we declare parallel arrays in C. And also , how to add more than one data type in a single array. for example, i want to declare int and char data type in the same array
#include <stdio.h>
int main()
double linetotal= qty*price;
printf("line total =%lf\n",linetotal);
double subtotal = line total - discount ;
}
}

Check the solution now.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define NUM_CODE 10
const char *CODE[NUM_CODE] = {"B100","B122","B134","B138","B145","B160","B165","B178","B186","B194"};
double PRICE[NUM_CODE]={12.8,18.7,20.5,11.5,25.5,20.55,25.65,14.85,22.2,24.25};
int main()
{
char name[20];
printf("Enter buyer name: ");
scanf("%s",name);
int entry;
printf("Enter number of entries for the invoice: ");
scanf("%d",&entry);
char code[10];
int quantity;
double price,linetotal=0;
int i;
for(i=1;i<=entry;i++)
{
printf("Enter Code: ");
scanf("%s",code);
printf("Enter Quantity: ");
scanf("%d",&quantity);
printf("Enter Unit Price: ");
scanf("%lf",&price);
int j;
int flag=0;
for(j=1;j<=NUM_CODE;j++){
// how do i print values like B100 without getting errors//
printf("%s ",CODE[j-1]);
// how to match the user input with parallel arrays?//
if(strcmp(CODE[j-1],code)==0 && PRICE[j-1]==price){
//If correct code and price found do
printf("\nValid Code and price found\n");
//set the flag and break from the loop
flag=1;
break;
}
}
if(flag==0){
//Exit the program with invalid entry
printf("\nInvalid Code and price found\n");
printf("The program will close now...\n");
exit(1);
}
// how do calculate line total,and subtotal after discount//
// discount is 10% if line total is greater than Rs5000//
linetotal = price * quantity + linetotal;
printf("\n");
}
double subtotal;
if(linetotal>5000){
subtotal = 0.9*linetotal;
}
else if(linetotal>=1000 && linetotal<=5000){
subtotal = 0.95*linetotal;
}
else{
subtotal = linetotal;
}
printf("Discount: %0.2lf%%\nTotal Price: %lf\n",((linetotal-subtotal)/linetotal)*100,subtotal);
return 0;
}

Related

Why is my Struct member changing when it isn't supposed to?

I've written this code in C where I want to increment the balance of a account if it is found with a matching string ID using the increaseBalance function, and although it does increment the balance value, it also changes the value of the structs ID as well. Here is my code
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAX_ACCOUNT_NUM 1000
#define NAME_LEN 15
#define ACCOUNT_NUM_LEN 6
#define FILE_LEN 20
struct bank_account
{
char owner_first_name[NAME_LEN], owner_last_name[NAME_LEN], account_num[ACCOUNT_NUM_LEN];
int balance;
};
typedef struct bank_account Account;
void reg_new_acc(Account account_reg[], int *nrOfAccounts);
Account create_user(char owner_first_name[], char owner_last_name[], char account_num[]);
void accountManagement(Account account_reg[],int *nrOfAccounts);
void print_account(Account account_reg[], int *pNrOfAccounts);
int checkAccountNum(Account account_reg[],char account_num[], int *nrOfAccounts);
void increaseBalance(Account account_reg[], char accountNum[], int amount, int *nrOfAccounts);
int main(void)
{
Account account_reg[MAX_ACCOUNT_NUM];
int nrOfAccounts = 0;
char accountFile[FILE_LEN];
//readFromFile(account_reg, &nrOfAccounts, accountFile);
accountManagement(account_reg, &nrOfAccounts);
return 0;
}
void accountManagement(Account account_reg[],int *nrOfAccounts)
{
int choice = 0;
do
{
printf("(1) Create New Account \n(2) Print All Accounts\n(3) Increment Account Balance\n");
printf("\n\nEnter Number: ");
scanf("%d", &choice);
switch (choice)
{
case 1:
reg_new_acc(account_reg, nrOfAccounts);
break;
case 2:
print_account(account_reg, nrOfAccounts);
break;
case 3:
printf("Please Enter the Account Number: ");
char accountNumber21[ACCOUNT_NUM_LEN];
scanf("%126s", accountNumber21);
printf("Please Enter the Amount: ");
int amount=0;
scanf("%d", &amount);
increaseBalance(account_reg, accountNumber21,amount, nrOfAccounts);
break;
}
} while ( choice != 9);
}
void reg_new_acc(Account account_reg[], int *nrOfAccounts)
{
char owner_first_name[NAME_LEN], owner_last_name[NAME_LEN], account_num[ACCOUNT_NUM_LEN];
while (*nrOfAccounts < MAX_ACCOUNT_NUM)
{
printf("\nRegistering User\n");
printf("Please enter (6-dig) ID number (q for quiting): ");
scanf("%s%*c", account_num);
if (strcmp(account_num, "q") == 0)
{
printf("Avslutar\n");
return ;
}
while(checkAccountNum(account_reg, account_num, nrOfAccounts)==0)
{
printf("This Already Exists\n");
printf("Please Enter Again: ");
scanf("%s%*c", account_num);
}
printf("Enter Name and Lastname: ");
scanf(" %s",owner_first_name);
scanf(" %s", owner_last_name);
account_reg[*nrOfAccounts] = create_user(owner_first_name, owner_last_name, account_num);
(*nrOfAccounts)++;
}
}
int checkAccountNum(Account account_reg[],char account_num[], int *nrOfAccounts)
{
if(strcmp(account_num, "q") == 0)
{
accountManagement(account_reg , nrOfAccounts);
}
for(int i = 0; i < *nrOfAccounts; i++)
{
if(strcmp(account_num,account_reg[i].account_num) == 0)
{
return 0;
}
}
return 1;
}
Account create_user(char owner_first_name[], char owner_last_name[], char account_num[])
{
Account account;
strcpy(account.account_num, account_num);
strcpy(account.owner_first_name, owner_first_name);
strcpy(account.owner_last_name, owner_last_name);
account.balance=0;
return account;
}
void print_account(Account account_reg[], int *pNrOfAccounts)
{
int i;
printf("\nPrinting All Accounts\n");
printf("ID\tFull Name\t\tBalance (kr)\n");
printf("____________________________________________\n");
for(i = 0; i < *pNrOfAccounts; i++)
{
printf("%s\t\t%s\t%s\t\t%d\n\n", account_reg[i].account_num, account_reg[i].owner_first_name, account_reg[i].owner_last_name, account_reg[i].balance);
}
}
void increaseBalance(Account account_reg[], char accountNum[], int amount, int *nrOfAccounts)
{
for(int i = 0; i < *nrOfAccounts; i++)
{
if(strcmp(accountNum,account_reg[i].account_num) == 0)
{
printf("In Increase");
account_reg[i].balance+=amount;
}
}
}
If you run this code and after adding a user, try to increment the user account balance and then print out the user details, you will see that something strange has happened to the user ID number. I don't know why this is happening. Thank you for the time.
From the code, change the value for ACCOUNT_NUM_LEN to 7 to take care of the null terminator. This should fix your problem.
Remember that c string are null terminated. The null terminator also takes up some space and should be accounted for.
"(6-dig) ID number" need 'char[7]' minimum, but ACCOUNT_NUM_LEN == 6
In function reg_new_acc(), after enter "123456" for account and "last" for owner_last_name, account variable contains "123456last".
In function create_user() strcpy(account.account_num, account_num) write "123456" to account.account_num, "last" to account.balance and '\0' cause 1-byte buffer overflow.
But operator 'account.balance=0' reset balance to 0 and account.account_num to "123456", because next byte write to '\0'.
After increaseBalance() account_reg[i].balance not 0. Therefore, the string account. account_num can get non-zero bytes after "123456" and will be printed as " 123456???".
P.S. Strictly speaking, in this program there is not a single correct operation with strings and not only with strings.
P.P.S. A good idea would be to use the latest versions of gcc or clang with stack-protector, mudflap, and _FORTIFY_SOURCE enabled, which provide some control over the use of arrays for storing strings.

New to programming. Need help adjusting code to allow for undetermined number of students

Need help adjusting code to allow for undetermined number of students. Tried to modify with help I received last week, but it seems like I am not doing it correctly.
#include <stdio.h>
int main ()
{
/* variable definition: */
char StudentName[100];
float ExamValue, Sum, Avg;
int students,exams;
// Loop through 5 Students
for (students=0; students <5 ; students++)
{
// reset Sum to 0
Sum =0.0;
printf("Enter Student Name \n");
scanf("%s", StudentName);
// Nested Loop for Exams
for (exams=0; exams < 3; exams++)
{
printf ("Enter exam grade: \n");
scanf("%f", &ExamValue);
Sum += ExamValue;
}
Avg = Sum/3.0;
printf( "Average for %s is %f\n",StudentName,Avg);
}
return 0;
}
Not sure how I need to go about changing the code. Any help will be greatly appreciated
Not sure I understand correctly, I understood you want to loop an undertemined amount of students.
I will assume you want to stop if certain keyword is added as a student name, let's say "quit".
Without changing your structure much, it would look like this.
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
int main (){
char StudentName[100];
float ExamValue, Sum, Avg;
int students,exams;
bool in = true;
while (in) {
Sum =0.0;
printf("Enter Student Name \n");
scanf("%s", StudentName);
if( strcmp(StudentName, "Quit") == 0 || strcmp(StudentName, "quit") == 0){
in = false;
break;
}
for (exams=0; exams < 3; exams++){
printf ("Enter exam grade: \n");
scanf("%f", &ExamValue);
Sum += ExamValue;
}
Avg = Sum/3.0;
printf( "Average for %s is %f\n",StudentName,Avg);
}
return 0;
}

Structure C: Storing values in an array

Can anyone advise why values are not getting stored in struct array?
I tried to store values in buffer array and I notice values that are getting stored 0 or 1 not user input.
This is what I tried:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int menu(void);
struct item
{
int i_SKU;
int i_QUANTITY;
int i_PRICE;
};
int main()
{
int i,j = 0;;
int n;
int input;
//struct item item1[10] = { {0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0} };
struct item item1[]={0};
struct item buff[]={0};
//printf("size of %d", sizeof(item1)/sizeof(item1[0]));
printf("Welcome to the Inventory\n");
printf("===================\n");
B: printf("Please select from the following:\n");
A: menu();
scanf("%d", &input);
switch (input)
{
case 1:
printf("Inventory\n");
printf("=========================================\n");
printf("ku Price Quant\n");
for (i = 0; i < sizeof(buff)/sizeof(buff[0]); i++)
{
printf("%d %d %d\n", buff[i].i_SKU, buff[i].i_PRICE, buff[i].i_QUANTITY);
}
printf("=========================================\n");
goto B;
case 2:
//n = sizeof(item1)/sizeof(item1[0]) + 1;
//for (i=n; i < ; i++)
printf("Please input a KU number:");
buff[j].i_SKU=scanf("%d", &item1[j].i_SKU);
printf("Quantity:");
buff[j].i_QUANTITY=scanf("%d", &item1[j].i_QUANTITY);
printf("Price:");
buff[j].i_PRICE=scanf("%d", &item1[j].i_PRICE);
printf("The item added.\n");
j=j+1;
goto B;
case 0:
printf("bye!");
exit(1);
default:
printf("Invalid input, try again:\n");
goto A;
}
return 0;
}
int menu(void)
{
printf("1) Display.\n");
printf("2) Add to inventory.\n");
printf("0) Leave.\n");
printf("Select:");
return 0;
}
I tried to store values in buffer array and I notice values that are getting stored 0 or 1 not user input.
scanf doesn't return the value it reads, it returns the number of characters it reads.
So these lines:
buff[j].i_SKU=scanf("%d", &item1[j].i_SKU);
buff[j].i_SKU=scanf("%d", &item1[j].i_QUANTITY);
buff[j].i_SKU=scanf("%d", &item1[j].i_PRICE);
don't do what you want. They put the integer into item1[j].i_X, but assign buff[j].i_X to the number of characters read.
Also, I'm guessing you intended the left hand side of those three equations to differ, not all refer to i_SKU.
Another possible problem: your buffers don't have a length specified, so they will probably just have storage for one element.
EDIT:
I'm not sure what purpose the items1 array serves in your code, but if you want the value in both arrays, you can try the following:
int sku;
printf("Please input a KU number:");
buff[j].i_SKU=scanf("%d", &sku);
item1[j].i_SKU = sku;
buff[j].i_SKU = sku;
// etc.

Wrong output by C Program

Can any one find the flaw and explain the below program? I will brief you,
1) Using structures in the program to store information about a products.
2) Finding the lowest price and displaying it.
All works fine but output does not give the lowest value.
#include <stdio.h>
#include <malloc.h>
struct product{
int code;
char name[30];
float price;
int qty;
};
void prodata(struct product *p,int n){
int i;
for (i=0;i<n;i++){
printf("\n Enter the Item Code. : ");
scanf("%d",&p[i].code);
fflush(stdin);
printf("\n Enter the Item Name. : ");
scanf("%s",&p[i].name);
printf("\n Enter the Item Price. : ");
scanf("%f",&p[i].price);
printf("\n Enter the Item Quantity in hand. : ");
scanf("%d",&p[i].qty);
}
}
void dispdata(struct product *p, int n){
int i;
int min;
min = 0;
for ( i = 1 ; i < n ; i++ ){
if (p[i].price < p[min].price) {
min = i;
}
}
printf("\n ** The Cheapest Product ** \n");
printf("\n The Product Code : %d \n",p[min].code);
printf("\n The Product Name is : %s \n",p[min].name);
printf("\n The Product Price is : %f \n",p[min].price);
printf("\n The Product Stock : %d \n",p[min].qty);
}
main(){
struct product *p=NULL;
int n;
printf("\n Product Information. \n");
printf("\n Please Enter the Number of Items : ");
scanf("%d",&n);
while(n<=1){
printf("\n Please Enter correct number of items : ");
scanf("%d",&n);
}
p =(struct product*)malloc(sizeof(struct product)*n);
prodata(p,n);
dispdata(p,n);
return 0;
}
if (p[i].price < min) {
min = i;
}
You're setting the min to be the index, not the actual price of the object.
In addition to Daniel's response make sure to index i at 0. Your for statements should be:
for(i = 0; i < n; i++) {....
Right now your missing 1 whole product since your for loop starts counting at 1 and ends after i iterates to (n-1) and executes the code block in the for loop

2 questions on typedef struct and averages on grades. Am I doing it correctly In C?

I need help on two questions, Its not homework but its to study for an exam. I need to have these questions because i was allowed 1 full page of notes for the exam. If you could help me these two simple questions for me that would be great. Here are the questions:
"Write a function called getGrades. The function that repeatedly prompts the user for positive integers until the user enters a negative value to stop. The function should return the average of these grades and the highest grade."
"Write a function called Get_Info that takes a pointer to a student structure, (that has three fields: char array called name, an int id, and a double gpa) as its only argument. The function prompts the user for the required information to fill the structure and stores it in the appropriate fields."
What I have so far, Let me know if they are correct and if i need to add anything.
1.
double getGrades() {
double average;
double i;
For(i=1 ; i<i; i++)
{
printf("Enter Grade1:\n");
scanf("%lf", &i);
}
if (i<0)
{
(double) average == (grade1 + grade2 + grade3) / 3;
return average;
}
}
2.
typedef struct {
int id;
double gpa;
char name[SIZE];
} student;
void Get_Info(student list[], int num) {
int i;
for(i=0; i<num; i++) {
printf("\nName:%s", list[i].name);
printf("\nGPA:%lf", list[i].gpa);
printf("\nID: %d\n", list[i].id);
}
}
On #1: The requirement is that the function accept ints. You are scanning for doubles.
The requirement is "The function should return the average of these grades and the highest grade." You only return one double, when two different outputs are called for.
Your for loop is written as "For" (C is case-sensitive), and is based on the test i<i. When will i ever be less than itself??
Here's my version of it.
double getGrades(int* max)
{
int sum = 0;
int input;
int i = 0;
*max = 0;
printf("Enter Grade #%d:\n", i+1);
scanf("%d", &input);
while (input > 0) {
if (*max < input) {
*max = input;
}
sum = sum + input;
i++;
printf("Enter Grade #%d:\n", i+1);
scanf("%d", &input);
}
return i? ((double)sum / i) : 0;
}
Your #2 is much better than your #1, but still has some errors:
The requirement is that the function takes a pointer to a student struct, NOT an array.
It should then print a series of Prompts, and get a series of answers (just as you did in #1).
This is a sequence of printf/scanf.
And when using scanf, you typically pass the ADDRESS of the variable, using &.
(strings are a exception, however)
Here is my version:
typedef struct {
char name[SIZE];
int id;
double gpa;
} student;
void Get_Info(student* ps) {
printf("Enter Name\n");
scanf("%s", ps->name);
printf("Enter ID:\n");
scanf("%d", &ps->id);
printf("Enter GPA\n");
scanf("%lf", &ps->gpa);
}
Try this. It should seem intuitive enough:
double getGrades() {
double average;
double grade;
double total = 0;
int count = 0;
while (1) {
printf("Enter grade: ");
scanf("%d", &grade);
if (grade < 0) {
if (count == 0) {
average = 0;
break;
}
average = total/count;
break;
}
count++;
total += grade;
}
return average;
}

Resources