You have come up with a requirement with which most C and C++ books start – a hello world program that starts with printing some output on the screen. I hope you appreciate how much you could already accomplish without ever having to print anything on the screen. But now, the time has come to show the stereotypical hello world program.
#include "stdio.h" int main() { printf(“Hello World!”); return 0; }Printf is a function that outputs a formatted string to the screen. For the printf function to work, we need to include a file that comes with most C implementations. Hence we write #include
The printf function outputs a formatted string, but also has some “magic” characters which are output differently. One of them is “\” known as the escape character or escape sequence. The character after the \ gives it a special meaning. \t stands for tab, \n stands for a new line \r for carriage return, \b for backspace, \% for percentage sign and \\ for backslash (more info). Another such character is the % sign. It has substitution power. The characters following the % will determine the type of substitution. For example, the quoted string inside printf for outputting the area will be “Area=%d”
The %d will be replaced by value of some integer variable which should follow the quoted string as in:
printf(“Area=%d”, area);
Similarly, %f stands for floating point numbers, %c for a single character, %s for a string, %l for long integers and %e for double floating point number. A complete list is here.
Now that we know how to print an output we can solve the problem of calculating cost for the paving of the area of your uncle’s garden:
#include "stdio.h" int main() { const int len1 = 10; const int len2 = 7; const int width1 = 8; const int width2 = 5; int rate = 100; int area = (len1 * width1) – ( len2 * width2); printf(“Cost @Rs.100 = %d\n”, rate * area); rate = 150; printf(“Cost @Rs.150 = %d\n”, rate * area); rate = 170; printf(“Cost @Rs.150 = %d\n”, rate * area); rate = 200; printf(“Cost @Rs.200 = %d\n”, rate * area); return 0; }Note that rate is not declared const since its value changes during the execution of the program. Area is also not defined but could have been since it is calculated only from other constants.
[Exercise] Modify the above program to support floating point lengths and widths. A float is defined as “float” instead of “int”.
No comments:
Post a Comment