Fundamentals of C
Structure of a C Program
1 Our First Simple Program
Comments - Different Modes
2 Comments - Rules
Preprocessor Directives
Preprocessor directives start with # e.g. #include copies a file into the source code before compilation
2 forms…..we will usually see the first #include
3 We will almost always use #include
• stdio.h is the standard input/output header • Contains code required for I/O (Input/Output) •.hfiles are header files Includes header ; The .obj part on Linking NO code is generally included except on linking • Header files contain definitions
The function : main()
ALL Programs must have a main() function. Later we will have add other functions. Different Formats: main( ) int main (void ) ***The book likes this void main(void) int main( )
4 main( ) , void main(void) End with return;
************************** int main (void ) , int main( ) End with return 0;
Back To Our First Program
5 Variables A Variable is a block of memory that stores data.
A variable has a particular “Type”, i.e. it stores a particular kind of data
A variable is named with an appropriate Identifier (or Name)
Suppose we have a variable declared as follows:
int number_of_days
This reserves a block of memory which holds an integer
6 Schematic view: number_of_days 365
In the course of the program we might want to change the value in the variable. So that later we might want: number_of_days 7361
• The “actual” view of memory: 4 bytes
number_of_days 01100000 11001010 10010100 00100111
So a variable takes a fixed number of bytes in memory
7 Rules for Naming Variables
1. First character: alphabetic or underscore
2. Consist only of alphanumeric or underscores
3. Only first 31 characters count
4. Cannot duplicate a reserved word
Legal/Illegal Variable Names
Use meaningful names
Legal Illegal a $sum student_name 2names salary stdnt number time_of_day int
8 Standard C Data Types
Primitive C Data Types
Data Type C-Implementation void void character char (1 byte) unsigned short int (1 byte) unsigned int (2 or 4 bytes) unsigned long int (4 or 8 bytes) integer short int (1 or 2 byte) int (2 or 4 bytes) long int (4 or 8 bytes) float (4 bytes) floating point double (8 bytes) long double (10 bytes)
9 Variables : Declaration
Variables : Initialization How we put a value in a variable
• At compile time in the declaration:
e.g. int x=5;
• At run time by an assignment:
e.g. x =5;
• At run time by an input statement:
e.g.scanf(“%d”,&x);
10 No variable is initialized until you do so!
You can initialize a variable in the declaration char code = ‘B’; char letter = ‘B’; int i = 0; int age = 65; float pie = 3.1415; float salary 27.57; double variable2 = 3.1415926535;
Special Characters
ASCII Character Symbolic Name Null character ’\0’ Alert (bell) ’\a’ Backspace ’\b’ Horizontal tab ’\t’ Newline ’\n’ Vertical Tab ’\v’
11 Special Characters
ASCII Character Symbolic Name Form Feed ’\f’ Carriage return ’\r’ Single quote ’\’’ Double Quote ’\”’ Backslash ’\\’
Strings : Constants
12 Preprocessing : #define Defines constants #define name token
Replaces the name with the token
Example: #define PI 3.1415926535 #define SIZE 1000
Syntax for Define : #define
•Noequals sign
•Nosemicolon at the end
13 Constants
To define a constant define a “variable” (usually, U.C.) with keyword: const This is how it works: const float PI = 3.1415926; This does NOT work: const float PI; PI = 3.1415926; /* not allowed to change it */
May be collected into a header file for general use
Standard Input and Output
14 To OUTPUT you require
#include
printf(format string, data list);
Field specifiers are inside the format string i.e. Controls how the data looks when printed
Standard printf statements #include
{ int a = 57; int b = 145;
printf( "%d\n%d\n", a,b); return; }
15 What happened? The statements int a = 57; a 57 int b = 145; b 145
The statement printf( "%d\n%d\n", a , b); prints: 57 145
Field Specifiers
%
Codes: Size Code Type Example none c char %c h d short int %hd none d int %d l or L d long int %Ld none f float %f none f double %f L f long double %Lf
16 Specification of Width
Value %d %4d
12 12 12
123 123 123
1234 1234 1234
12345 12345 12345
Precision specification for floats:
%7.2f
/* this prints the float in a field of seven characters with two characters after decimal: nnnn.dd */
17 Another Example of printf #include
{ int months = 9; float salary = 145.35; printf( "%d\n%7.2f\n", months , salary); return 0; }
Another Example of printf #include
18 The output
the number of months is 9 the salary is 145.35
Input: Getting information into memory: (reading) Requires: #include
Again : Field specifiers inside the format string
19 Standard scanf Statements scanf(format string, address list); scanf(“%d%f”, &age, &weight);
At keyboard type 23 60.75
60.75 Result: weight age 23
Field Specifiers
%
20 Rules for scanf formats
Addresses of a variable are specified with: &variableName
A variety of rules apply to conversion
Rules for scanf formats
1. Initial whitespace is ignored (except %c) 2. The conversion operation process until: i. End of file is reached ii. Maximum characters are processed iii. A whitespace character is found after a digit iv. An error is detected
21 Rules for scanf format strings
1. A field specifier for each variable
2. Other characters must be exactly matched
3. Cannot end format string with whitespace
Examples of scanf
scanf(“%d%d%d%c”,&a,&b,&c,&d); scanf(“%d%d%d %c”,&a,&b,&c,&d); scanf(“%-8d%-8d%d”,&a,&b,&c); %-8d /* left justify flag */
22 Working with the variables:
We want to operate on variables: e.g add two variables or subtract them. An Expression: rateOfPay*hours – tax
Operators e.g., + plus -minus * multiply / divide % mod
You create expressions out of operators.
23 Some Expressions 35 2 * 3 + 4 23 + b * 6 -salary Use parenthesis to clarify complicated expressions:
(food + drinks)*(1+gst+pst)
Assignment Assignment expressions evaluate to the expression on the right of the assignment operator.
24 Simple Assignment
Contents of Contents of Expression Value of Result of Variable x Variable y Expression Expression
10 5 x=y+2 7 x = 7
10 5 x=x/y 2 x=2
10 5 x=y%4 1 x=1
Operator Precedence
Operators have a built in order of precedence which is over ridden by using parenthesis
1+2*3+4 answer 11 1*2 + 3*5 answer 17 -5*6+2 answer -28
25 Operators precedence (on the same level they are equal)
1. ( ) takes precedence 2. unary minus -7 unary plus +3 3. * Multiply / Divide 4 % Modulus 5. + add - subtract
Examples Operators • Examples of C statements using these : • The following is a program fragment only • int i, j ,k, l, m; • i = j + k; • i = j + k * l / m; • /* Here i gets the value j + (k*l/m) */ • i = j * k + l * m • /* Here i gets the value (j*k) + (l*m) */
26 Examples Operators
• Examples of C statements using these : • There is one division operator for integer and float but it means different things. • 2 / 5 → 0 • 2.0 / 5.0 → 0.4 • % is the modulus (remainder) operation • 5 % 2 → 1 • 2 % 5 → 2
Unary operator + and -
+a – evaluates to the contents of a
-a – evaluates to the negative contents of a
27 Unary Expressions
Contents of Expression Value of Contents of x Before Expression x After
10 ++x 11 11
10 --x 9 9
Unary operator ++ and --
Post-increment and decrement i++ i-- /*First use the value ; then do operation*/
Pre-increment and decrement ++i --i /*First do operation; then use the value */
28 Unary operator ++ and --
Examples for int i , j , k; • i=1; • i++; /* i → 2 */ • j = i++ ; /*j → 2 and then i → 3 • j =++i ; /* i → 4 and then j → 4 • j = i-- /* j → 4 and then i → 3 • Note that i++ and i=i+1 are equivalent • Note that i-- and i=i-1 are equivalent
Binary Compound Operators
Often a variable is changed as follows : • i = i + 5; /* Take the value of i add 5 and put the result back into the variable i*/. Leads to new assignment operators += -= *= /= %= •i = i + 1; same as i += 1; • j = j * k; same as j *= k ;
29 Compound Assignment
Contents of Contents of Expression Value of Result of Variable x Variable y Expression Expression
10 5 x *= y 50 x = 50
10 5 x /= y 2 x = 2
10 5 x %= y 0 x = 0
10 5 x += y 15 x = 15
10 5 x -= y 5 x = 5
A Simple Program #include
30 A Simple Program The OUTPUT >Please input two real numbers: 23.4 45.6 x= 23.40 y= 45.60 z=69.000
/* A simple program to average 3 numbers*/ #include
31 Whats the problem with the previous program?
What if you wanted to average 50 numbers?
It would be very clumsy to repeat 50 times.
Also you have to change the program each time you have a different number of numbers.
Program to calculate tax on a bill
First you have to know the facts. Subtotal = food and drink PST = 0.08 GST =0.06 Tax = subtotal (PST+GST) Total = subtotal + tax
32 /* A simple program calculate restaurant bill: input: food and drink amounts output: subtotal, tax, total bill*/ #include
Whats the problem with the previous program?
The rule is not right. If the subtotal is less than $3.00 the no GST
So we need decision possibility
So we need “CONTROL STRUCTURES”
33 Unary Operator sizeof sizeof is an operator. It is NOT a function
Evaluates to number of bytes for that item sizeof(int) sizeof(x) sizeof(3.256)
34