We would need to edit the file to change the assignment statements in the program, recompile it and run it again each time. In a volitile stock market, this could be tedious.
It might be better to write a more general program that would work for any data values, so we can compile it once and allow the user to enter the data at run time.
To make this change, we go back to step 3 and modify the algorithm to get the data values instead of setting them. The algorithm would become:
Get the number of shares Get the selling price Print the data value Compute the portfolio value Print the result
printf("Enter number of shares: "); scanf("%d",shares);One thing to note is that the printf() format string does not have a newline ('\n') character at the end. This is so that the curser will stay on the same line as the prompt.
But we said that printf() is "buffered" - that the output does not appear on the screen until a complete line (indicated by '\n') is output. In this case, since we next use scanf() to read data, scanf() will flush the contents of the buffer to the screen to make it available for its use.
Unfortunately, we still have a problem. If we added this to the program and ran it, when we typed a value for the number of shares at run time, we would get the the following message:
Enter number of shares: 57 Segmentation faultThis is a run time error, the program "crashed".
scanf("%d",shares);We are passing the format string and the VALUE of the variable shares to scanf(). What scanf() needs to do is read an integer and put that value into the cell corresponding to shares. It needs to know where shares is, not its value.
C provides an operator to find the location of a variable, the address of operator &. So we really need to call scanf() as:
scanf("%d",&shares);The code for the modified program is in stock2.c.