Solution for Exercise 20-12
ex2012
#include <stdio.h> #include <stdlib.h> #include <string.h> #define ITEMS 5 struct stk { char symbol[5]; int quantity; float price; struct stk *next; }; struct stk *make_structure(void); void fill_structure(struct stk *a,int c); void show_structure(struct stk *a); int main() { struct stk *first; struct stk *current; int x; /* create the ITEMS-sized linked list */ for(x=0;x<ITEMS;x++) { if(x==0) { first=make_structure(); current=first; } else { current->next=make_structure(); current=current->next; } fill_structure(current,x+1); } /* cap the list */ current->next=NULL; /* output the database */ puts("Investment Portfolio"); printf("Symbol\tShares\tPrice\tValue\n"); current = first; while(current) { show_structure(current); current=current->next; } return(0); } /* allocate a new structure */ struct stk *make_structure(void) { struct stk *a; a=(struct stk *)malloc(sizeof(struct stk)*1); if(a==NULL) { puts("Some kind of malloc() error"); exit(1); } return(a); } /* fill the structure with data */ void fill_structure(struct stk *a,int c) { printf("Item #%d/%d:\n",c,ITEMS); printf("Stock Symbol: "); scanf("%s",a->symbol); printf("Number of shares: "); scanf("%d",&a->quantity); printf("Share price: "); scanf("%f",&a->price); } /* output the structure */ void show_structure(struct stk *a) { printf("%-6s\t%5d\t%.2f\t%.2f\n",\ a->symbol, a->quantity, a->price, a->quantity*a->price); }
Output
Item #1/5:
Stock Symbol: IBM
Number of shares: 50
Share price: 116.98
Item #2/5:
Stock Symbol: MSFT
Number of shares: 25
Share price: 183.16
Item #3/5:
Stock Symbol: TWTR
Number of shares: 250
Share price: 29.0
Item #4/5:
Stock Symbol: QCOM
Number of shares: 67
Share price: 75.77
Item #5/5:
Stock Symbol: CSCO
Number of shares: 50
Share price: 44.27
Investment Portfolio
Symbol Shares Price Value
IBM 50 116.98 5849.00
MSFT 25 183.16 4579.00
TWTR 250 29.00 7250.00
QCOM 67 75.77 5076.59
CSCO 50 44.27 2213.50
Copyright © 1997-2024 by QPBC.
All rights reserved