Slide 2 C Fundamentals
Slide 2 C Fundamentals
}
Compiling and Linking
○ printf(“Hello,”);
○ printf(“world\n”);
Comments
C89 Style
/*
Name: hello.c
● Failure to end a comment
Purpose: Prints Hello, world
can result in program
Author: Mohammed Saidul Islam
statements being
● Example:
○ int
■ Limited range
Variables and Assignment
Types
● Example:
○ float
■ Short for floating point numbers
■ Can store much larger numbers than int
■ Can stores numbers with digits after the decimal point, like 379.125
■ Limitations are:
● Slower arithmetic operations
● Approximate nature of floating point values (i.e., round-off error)
Variables and Assignment
Declarations
● Shipping companies often charge extra for boxes that are large, but
very light based on their volume instead of weight
● Usual method followed in the US:
○ Divide the volume of the box by 166 (the allowed number of cubic inches per pound)
-> Dimensional weight
○ If the value exceeds its actual weight, shipping fee is based on dimensional weight
● Division is represented by / in C:
○ weight = volume / 166
Note: Attempting to access the value of an uninitialized variable may yield an unpredictable
result. With some compilers, worst behavior - even a program crash - may occur.
Reading Input
● scanf is the C library’s counterpart to printf
● scanf requires a format string to specify the appearance of the input
data
● Example of using scanf to read an int value:
○ scanf(“%d”, &i) //reads an integer and stores it into i
● The & symbol is usually (but not always) required when using scanf
Program (Revisited)
Computing the dimensional weight of a box
● We can modify our previous program to take inputs from user using
scanf
● Each call of scanf is immediately preceded by a call of printf that
displays a prompt.
● Sample output of the program:
Enter height of the box: 8
Enter length of the box: 12
Enter width of the box: 10
Volume (cubic inches): 960
Dimensional weight (pounds): 6
Defining Names for constants
● Both of the programs rely on the constant 166, whose meaning may
not be clear to someone reading the program.
● Using a feature known as macro definition, we can name this constant:
#define INCHES_PER_POUND 166
● When a program is compiled, the preprocessor replaces each macro by
the value that it represents
Defining Names for constants
● During preprocessing, the statement
weight = (volume + INCHES_PER_POUND - 1) / INCHES_PER_POUND;
will become
weight = (volume + 166 - 1) / 166;