C LANGUAGE ELEMENTS
- Processor Directives
- Standard header file
- Comment
- Constant
- Variable
- Reserved word
- Standard identifier
- Special symbol
VARIABLE DECLARATIONS AND DATA TYPES
- C input/out (scanf and printf)
C LANGUAGE ELEMENTS
Processor Directives
The preprocessor directives are commands that give instructions to the C preprocessor , whose job it is to modify the text of a C program before it is compiled. A preprocessor directive begins with a number symbol (#) as its first non blank character.
The two most common directives are :#include and #define .The C language explicitly defines only a small number of operations: Many actions that are necessary in a computer program are not defined directly by C. Instead, every C implementation contains collections of useful functions and symbols called libraries.A C system may expand the number of operations available by supplying additional libraries; an individual programmer can also create libraries of functions. Each library has a standard header file whose name ends with the symbols .h.
Preprocessor directive
A C program line beginning with # that provides an instruction to the preprocessor.
Preprocessor
A system program that modifies a C program prior to its compilation.
Library
A collection of useful functions and symbols that may be accessed by a program.
Figure: C Language Elements in Miles-to-KilometersConversion Program
The #include directive gives a program accessto a library. This directive causes the preprocessor to insert definitions froma standard header file into a program before compilation.
The directive #include /* printf,scanf definitions */ notifies the preprocessor that some names used in theprogram (such as scanf and printf ) are found in the standard header file .
#define KMS_PER_MILE 1.609 /* conversion constant */
associates the constant macro KMS_PER_MILE withthe meaning 1.609 . This directive instructs the preprocessor to replace eachoccurrence of KMS_PER_MILE in the text of the C program by 1.609 beforecompilation begins. As a result, the line
kms = KMS_PER_MILE * miles;
would read
kms = 1.609 * miles;
by the time it was sent to the C compiler. Only data values that never change (or change very rarely) should be given names using a#define , because an executing C program cannot change the value of a name defined as a constant macro. Using the constant macro KMS_PER_MILE in the text of a program for the value 1.609 makes it easier to understand and maintain the program.
The text on the right of each preprocessor directive,starting with /* and ending with */ , is a comment . Comments providesupplementary information making it easier for us to understand the program,but comments are ignored by the C preprocessor and compiler.
Constant macro
A name that is replaced by a particular constant valuebefore the program is sent to the compiler.
Comment
Text beginning with /* and ending with */ that providessupplementary information but is ignored by the preprocessor and compiler.
Function main
The two-line heading
int main(void)
marks the beginning of the main function where programexecution begins. Every C program has a main function. The remaining lines ofthe program form the body of the function which is enclosed in braces {, } .
A function body has two parts: declarations and executable statements. The declarations tell the compiler what memory cells are needed in the function (for example, miles and kms in the figure above)
To create this part of the function, the programmer uses the problem data requirements identified during problem analysis.
The executable statements (derived from the algorithm)are translated into machine language and later executed.
Declarations
The part of a program that tells the compiler the names of memory cells in a program
Executable statements
Program lines that are converted to machine language instructions and executed by the computer
The main function contains punctuation and special symbols ( * , = ). Commas
separate items in a list, a semicolon appears at the end of several lines, and braces
( { , } ) mark the beginning and end of the body off unction main .
Syntax:
Figure: Constant syntax
Figure: Main function syntax
Reserved Words
A word that has special meaning in C
All the reserved words appear in lowercase; they have special meaning in C and cannot be used for other purposes.
Reserved Word | Meaning |
int | integer; indicates that the main function returns an integer value |
void | indicates that the main function receives no data from the operating system |
double | indicates that the memory cells store real numbers |
return | returns control from the main function to the operating system |
Standard Identifiers
Are identifiers that come in two varieties: standardand user-defined. Like reserved words, standard identifiers have specialmeaning in C.
The standard identifiers printf and scanf are names ofoperations defined in the standard input/output library. Unlike reserved words,standard identifiers can be redefined and used by the programmer for otherpurposes—however, we don’t recommend this practice. If you redefine a standardidentifier, C will no longer be able to use it for its original purpose.
User-Defined Identifiers
We choose our own identifiers (called user-definedidentifiers ) to name memory cells that will hold data and program results andto name operations that we define.
Rules For Defining Your Own Identifiers
- An identifier must consist only of letters, digits, and underscores.
- An identifier cannot begin with a digit.
- A C reserved word cannot be used as an identifier.
- An identifier defined in a C standard library should not be redefined.
- There should not be any spacing of words or spacing of letters when naming identifiers
Most programmers separate words in identifiers usingeither an underscore or toggling the case of the first letters in the words.
Valid Identifiers
letter_1, letter_2, inches, cent, CENT_PER_INCH,Hello, variable, firstName, LastName, first_name, last_name
Although the syntax rules for identifiers do not place a limit on length, some ANSI
C compilers do not consider two names to be different unless there is a variation within
the first 31 characters. The two identifiers
per_capita_meat_consumption_in_1980
per_capita_meat_consumption_in_1995
would be viewed as identical by a C compiler that considered only the first 31 characters
to be significant.
Invalid Identifiers
Invalid Identifier | Reason |
1Letter | begins with a digit (1) |
double | reserved word |
int | reserved word |
TWO*FOUR | character * not allowed |
joe's | character ' not allowed |
first name | space character not allowed |
Summary
Reserved Words | Standard Identifiers | User-defined Identifiers |
int, void, double, return | printf, scanf | KMS_PER_MILE, main, miles, kms |
Uppercase and Lowercase Letters
You as a C programmer must take great care in the use of uppercase and lowercase letters because the C compiler considers such usage significant. The names Rate , rate , and RATE are viewed by the compiler as different identifiers.
Adopting a consistent pattern in the way you use uppercase and lowercase letters is helpful to the readers of your programs. You will see that all reserved words in C and the names of all standard library functions use only lowercase letters. One style that has been widely adopted in industry uses all uppercase letters in the names of constant macros.
Program Style
Choosing Identifier Names
A program that “looks good” is easier to read and understand than one that is sloppy. Most programs will be examined or studied by someone other than the original programmers.
In industry, programmers spend considerably more time on program maintenance (that is, updating and modifying the program) than they do on its original design or coding. A program that is neatly stated and whose meaning is clear makes everyone’s job simpler.
Pick a meaningful name for a user-defined identifier,so its use is easy to understand.
For example, the identifier salary would be a good name for a memory cell used to store a person’s salary, whereas the identifiers or bagel would be a bad choice. If an identifier consists of two or more words, placing the underscore character (_) between words will improve the readability of the name (dollars_per_hour rather than dollars per hour ).
Choose identifiers long enough to convey your meaning,but avoid excessively long names because you are more likely to make a typing error in a longer name.
Data Types
A data type is a set of values and a set of operations on those values. Knowledge of the data type of an item (a variable or value)enables the C compiler to correctly specify operations on that item. A standard data type in C is a data type that is predefined, such as char , double , and int . We use the standard data types double and int as abstractions for the real numbers and integers (in the mathematical sense).
Data Type int
In mathematics, integers are whole numbers. The int data type is used to represent integers in C.
You can store an integer in a type int variable,perform the common arithmetic operations (add, subtract, multiply, and divide),and compare two integers.
Data Type double
A real number has an integral part and a fractional part that are separated by a decimal point. In C, the data type double is used to represent real numbers (for example, 3.14159 , 0.0005 , 150.0 ).
You can store a real number in a type double variable,perform the common arithmetic operations (add, subtract, multiply, and divide),and compare them.
Differences Between Numeric Types
Less storage space is needed to store type int values than double values. Therefore even though you can use double type to store integer values, much more space will be used for that storage.
Data Type char
Data type char represents an individual character value a letter, a digit, or a special symbol. Each type char value is enclosed in apostrophes (single quotes) as
shown here.
'A' 'z' '2' '9' '*' ':' ' "' ' '
Declaring Variables
Syntax:
data type variable_name;
Thus the data type then a space then the name of the variable you want to declare to store your data.
Examples
int age;
int year;
double salary;
double rate;
char gender;
You can declared more than one variable with a single data type by separating the variables by a comma (,).
Examples
int age,year;
double salary,rate;
Assignment Statements
An assignment statement stores a value or a computational result in a variable, and is used to perform most arithmetic operations in a program. The assignment statement
kms = KMS_PER_MILE * miles;
assigns a value to the variable kms . The value assigned is the result of the multiplication
( * means multiply) of the constant macro KMS_PER_MILE(1.609) by the variable miles . The memory cell for miles must contain valid information (in this case, a real number) before the assignment statement is executed.
In C the symbol = is the assignment operator.Read it as “becomes,” “gets,” or “takes the value of” rather than “equals”because it is not equivalent to the equal sign of mathematics.
In mathematics, this symbol states a relationship between two values, but in C it represents an action to be carried out by the computer.
Syntax
variable = expression;
Assignment statement: an instruction that stores a value or a computational result in a variable
Figure: Effect of kms = KMS_PER_MILE * miles;
Assignment to a char Variable
The char variable next_letter is assigned the character value 'A' by the assignment
statement
next_letter = 'A';
Input/Output Operations and Functions
Data can be stored in memory in two different ways:either by assignment to a variable or by copying the data from an input device into a variable using a function like scanf .
You copy data into a variable if you want a program to manipulate different data each time it executes.
This data transfer from the outside world into memory is called an input operation .
The most common input/output functions are supplied as part of the C standard input/output library to which we gain access through the preprocessor directive
#include
In C, a function call is used to call or activate a function. Calling a function is analogous to asking a friend to perform an urgent task. You tell your friend what to do (but not how to do it)and wait for your friend to report back that the task is finished.
After hearing from your friend, you can go on and do something else.
What you will need to know from your friend is the things he/she might need to accomplish the task (analogous to arguments / input of a function).
The printf Function
To see the results of a program execution, we musthave a way to specify what variable
values should be displayed.
Figure: Displaying a stored variable(s) value(s).
The function printf (pronounced “print-eff”) is calledto display a line of program output.
A function call consists of two parts: the functionname and the function arguments
, enclosed in parentheses. The arguments for printfconsist of a format
string (in quotes) and a printlist (the variable kms ). The function call above displays
the line
That equals 16.090000 kilometers.
printf arguments
Can be only a string (A text in quotes)
Examples:
printf(“My name is Godwin Ashong \n”);
printf(“I am enjoying C Programming \n”);
NOTE: The \n makes the cursor or next display to move to the next line (New line)
Can have placeholder(s) where the stored variables to display will be replaced
A placeholder starts with the % as shown in the printf function above (%f).
Anytime a placeholder is used, the order of the variable names to replace the placeholders is listed in the print list as shown in the printf function above. If more than one variable is to be displayed, the print list variables are separated by a comma (,).
Examples
#include
#include
int main()
{
double salary = 1200;
printf("My monthly salary is GHC %f",salary);
return 0;
}
Explanation:
The placeholder %f is replaced by the value of the variable, salary. When the above program is run, the output below is shown:
Figure: Output for the above code
Example 2 (Multiple Placeholders)
#include
#include
#define HOURLY_RATE 8.00
int main()
{
double salary = 1200;
printf("My monthly salary is GHC %f at an hourly rate of GHC %f",salary,HOURLY_RATE);
return 0;
}
Explanation:
There are two placeholders (%f). The first placeholder is to hold the salary value and the second placeholder is to hold the HOURLY_RATE value. Since there were more than one placeholder, the variables to replace the placeholders are separated by a comma and written in the order of their corresponding placeholders. The output of the above program is shown below:
Figure: Output for the above code
NOTE: The letter that follows the % in the placeholder varies for each data type. The f letter is used for double datatype. The table below shows the list of data types and their corresponding placeholders.
Placeholder
| Variable Type
| Function Use
|
---|
%c
| char
| printf/scanf
|
%d
| int
| printf/scanf
|
%f
| double
| printf
|
%lf
| double
| scanf
|
The scanf Function
The statement
scanf("%lf", &miles);
calls function scanf (pronounced “scan-eff”) to copy data into the variable miles .
Where does function scanf get the data it stores in the variable miles ? It copies the data from the standard input device. In most cases the standard input device is the keyboard; consequently, the computerwill attempt to store in miles whatever data the program user types at the keyboard.
Thus the syntax for taking a data from a user is:
scanf(“placeholder”,&variable_name);
The placeholder for the scanf for char and int is thesame as the printf except the double which is %lf for the scanf. and %ffor printf.
Example:
Write a program that that’s the First letter for both the first name and last name of a user, the age of the user and the GPA of the user. The program should output for instance if the entered first letter for first name is G and the last name is A and the age is 20 and the GPA is 4, the program should output something like this:
Hello G.A, you are 20 years old and your GPA is 4.0
Sample Code
#include
#include
int main()
{
char f,l;
int age;
double gpa;
//Inform the user to enter first letter of first name and last name
printf("Enter the first letter of your first and last name > ");
//Get the entered letters from the keyboard
scanf("%c%c",&f,&l);
//Inform the user to enter age
printf("Enter your age > ");
//Get the entered age from the keyboard
scanf("%d",&age);
//Inform the user to enter the gpa
printf("Enter your gpa > ");
//Get the entered gpa from the keyboard
scanf("%lf",&gpa);
//Output the result to the screen
printf("Hello %c.%c, you are %d years old and your GPA is %f",f,l,age,gpa);
return 0;
}
EXERCISE
Write a program that takes the length and kilogram mass of a cuboid. Your program should compute the pressure of the cuboid and output to the user.
Formula: Pressure = Force / Area
Force = Mass x Acceleration due to gravity
Acceleration due to gravity = 10
Area of a cuboid = Length x Length
Program Display Should Be Something Like This:
****************************************
DEGREE TO FAHRENHEIT CONVERTER
****************************************
Enter the length of the cuboid > 20
Enter the Kilogram mass of the cuboid > 18
Force of cuboid : 180 N
Area of cuboid: 400
Pressure of cuboid: 0.45 Pa