Professional Documents
Culture Documents
Writing C Programs: File
Writing C Programs: File
L08IntroToC.ppt 1
3 Stages of Compilation
Stage 1: Preprocessing
Performed by a program called the preprocessor
Modifies the source code (in RAM) according to
preprocessor directives (preprocessor
commands) embedded in the source code
Strips comments and white space from the code
The source code as stored on disk is not modified.
L08IntroToC.ppt 2
3 Stages of Compilation (cont)
Stage 2: Compilation
Performed by a program called the compiler
Translates the preprocessor-modified source code
into object code (machine code)
Checks for syntax errors and warnings
Saves the object code to a disk file, if instructed to
do so (we will not do this).
o If any compiler errors are received, no object code file
will be generated.
o An object code file will be generated if only warnings,
not errors, are received.
L08IntroToC.ppt 3
L08IntroToC.ppt 4
Program Development Using gcc
Editor
Source File pgm.c
Preprocessor
Modified Source Code in RAM
Compiler
Program Object Code File pgm.o
Other Object Code Files (if any)
Linker
A Simple C Program
#include <stdio.h>
int main ( void )
{
printf ( Hello, World!\n ) ;
return 0 ;
}
L08IntroToC.ppt 6
Anatomy of a C Program
program header comment
L08IntroToC.ppt 7
What Is a Comment? #1
L08IntroToC.ppt 8
Program Header Comment
A comment is descriptive text used to help a
reader of the program understand its content.
All comments must begin with the characters /* and
end with the characters */
These are called comment delimiters
The program header comment always comes first.
Look at the class web page for the required
contents of our header comment.
L08IntroToC.ppt 9
Preprocessor Directives
Lines that begin with a # in column 1 are
called preprocessor directives
(commands).
Example: the #include <stdio.h> directive
causes the preprocessor to include a copy of
the standard input/output header file stdio.h
at this point in the code.
This header file was included because it
contains information about the printf ( )
function that is used in this program.
L08IntroToC.ppt 10
stdio.h
L08IntroToC.ppt 12
The Function Body
L08IntroToC.ppt 13
L08IntroToC.ppt 14
return 0 ;
Because function main() returns an integer value, there
must be a statement that indicates what this value is.
The statement
return 0 ;
L08IntroToC.ppt 15
L08IntroToC.ppt 16
Keywords
Sometimes called reserved words.
Are defined as a part of the C language.
Can not be used for anything else!
auto double int struct
break else long switch
case enum register typedef
char extern return union
const float short unsigned
continue for signed void
default goto sizeof volatile
do if static while
L08IntroToC.ppt 17
L08IntroToC.ppt 18
Data types in C
L08IntroToC.ppt 19
Data types in C
Keyword Variable Type Range
char Character -128 to 127
int Integer -32,768 to 32,767
short Short integer -32,768 to 32,767
short int Short integer -32,768 to 32,767
long Long integer -2,147,483,648 to
2,147,483,647
unsigned char Unsigned character 0 to 255
unsigned int Unsigned integer 0 to 65,535
unsigned short Unsigned short integer 0 to 65,535
unsigned long Unsigned long integer 0 to 4,294,967,295
float Single-precision +/-3.4E10^38 to +/-
3.4E10^38
double Double-precision +/-1.7E10^308 to +/-
L08IntroToC.ppt
1.7E10^308
20
Variables
L08IntroToC.ppt 21
Input
o scanf(%d,&a);
o Gets an integer value from the user and stores
it under the name a
Output
o printf(%d,a)
o Prints the value present in variable a on the
screen
L08IntroToC.ppt 23
The special character tells the program how to convert the data.
Conversion Specifier Description
%d Displays integer value
%f Displays floating-point numbers
%c Displays character
L08IntroToC.ppt 24
Type Conversion
1. Type conversion occurs when the expression has
data of mixed data types.
2. In type conversion, the data type is promoted from
lower to higher.
3. The hierarchy of data types: double, float, long, int,
short, char.
L08IntroToC.ppt 25
Tokens
L08IntroToC.ppt 26
Newline
In C, you can place a newline, also known
as a carriage return, inside a string literal
using:
\n
If a newline appears inside a string literal in
the source code, then when the string
literal is output, the newline causes the
output to move to a new line.
L08IntroToC.ppt 27
Newline Example
#include <stdio.h>
int main ()
{ /* main */
printf("Howdy do!\n");
printf("This string literal contains a newline in the\nmiddle ");
printf("but this string literal contains a newline at the end.\n");
printf("So there!\n");
} /* main */
L08IntroToC.ppt 28
Punctuation
L08IntroToC.ppt 29
Operators
L08IntroToC.ppt 30
Assignment operator
Assigning the value of an expression to a variable.
var = expression.
You can use other formats such as var += expression,
which means var = var + expression.
L08IntroToC.ppt 31
Arithmetic Operators
Operator Description Example
* Multiplication Result = Operand1 * Operand2;
/ Division Result = Operand1 / Operand2;
% Modulus (remainder) Remainder = Operand1 % Operand2;
+ Addition Result = Operand1 + Operand2;
- Subtraction Result = Operand1 -Operand2;
L08IntroToC.ppt 32
Increment/Decremental operator ++ --
Prefix: the value is incremented/decremented first and then applied.
Postfix: the value is applied and the value is
incremented/decremented.
#include<stdio.h>
main( )
{
int i = 3,j = 4,k;
k = i++ + --j;
printf("i = %d, j = %d, k = %d",i,j,k);
}
L08IntroToC.ppt 33
Relational operators
1. Relational operators are used in Boolean conditions or
expressions.
2. Boolean conditions or expressions return either true or false.
3. The relational operator returns zero values or nonzero values.
4. The zero value is taken as false while the nonzero value is taken
as true.
1. The relational operators are as follows: <, <=, >, >=, ==, !=.
2. The priority of the first four operators is higher than that of the later
two operators.
L08IntroToC.ppt 34
Boolean Operator in C
Character Set Boolean Operator
&& and
|| or
&& Operator
1. && operator: evaluate a Boolean expression from left to right.
2. Both sides of the operator must evaluate to true before the entire
expression becomes true.
|| Operator
1. || operator: evaluate from left to right.
2. If either side of the condition is true, the whole expression results
in true.
L08IntroToC.ppt 35
Conditional Statements
IF STATEMENT: To conditionally execute statements, you can use
the if or the if...else statement.
The general form of the if statement is
if(expr) {
....
}else{
...
}
expr is a Boolean expression that returns true (nonzero) or false
(zero).
L08IntroToC.ppt 36
Conditional Statements
SWITCH STATEMENT: To take one of a number of possible
actions.
switch is preferred over multiple if...else statements.
The general form of a switch statement is
switch(switch_expr)
{
case constant expr1 : S1; break;
case constant expr1 : S2; break;
.....
default : S5; break;
}
The clause 'default' is optional.
L08IntroToC.ppt 37
Loop Statement in C
Loops are basically means to do a task multiple
times, without actually coding all
statements over and over again. For example, loops
can be used for displaying a string
many times, for counting numbers and of course for
displaying menus. Loops in C are three types:
'for' loop
'while' loop
'do while' loop
L08IntroToC.ppt 38
For Loop
The for statement is typically used to count a number of items. At its regular structure,
it is divided in three parts. The first section specifies the starting point for the count.
The second section sets the counting limit. The last section determines the counting
frequency. The syntax of the for statement is:
for( Start; End; Frequency) {
Statement;
}
The Start expression is a variable assigned the starting value. This could be Count =
0; The End expression sets the criteria for ending the counting. An example would be
Count < 24; this means the counting would continue as long as the Count variable is
less than 24.
For example:
int count, num, total = 0;
for (count = 1; count <= 10; count++) {
cout << "Enter integer #" << count << ": ";
cin >> num;
total = total + num;
} //end for
Note: The "++" operator adds one to a number, so count++; is equivalent to count =
count + 1
L08IntroToC.ppt 39
While Loop
while (<stopping condition>) {
<one or more statements>
} end while
The while loop checks to see if the <stopping condition> is true (or not -). If so, the
statements inside the while loop are executed, then the <stopping condition> is checked
again, and so on. When the <stopping condition> is found to be false (or -), execution
continues with whatever statements follow at the end of the while loop.
For example:
#include<iostream>
void main(){
int i=0;
while(i<3){
i++;
cout<<ABC<<endl;
}}
L08IntroToC.ppt 40
Do-While
It is very similar to the 'while' loop shown above. The only difference
being, in a 'while',loop, the condition is checked beforehand, but in a
'do while' loop, the condition is checked after one execution of the
loop.Example code for the same problem using a 'do while' loop
would be :
void main(){
int i=0;
do{
i++; cout <<ABC<< endl;
}while(i<3)
}
L08IntroToC.ppt 41
What is a C Function?
A function receives zero or more parameters, performs
a specific task, and returns zero or one value.
1. A function is invoked by its name and parameters.
2. No two functions have the same name in your C program.
3. No two functions have the same name AND parameter types in
your C++ program.
4. The communication between the function and invoker is through
the parameters and the return value.
5. A function is independent:
6. It is completely self-contained.
7. It can be called at any places of your code and can be ported to
another program.
8. Functions make programs reusable and readable.
42
Standard function libraries
<stdio.h> printf(), scanf(),
printf(), scanf(), etc.
<string.h> strcmp(), etc.
strcmp(),
<ctype.c> isspace(), etc.
isspace(),
<math.h> sqrt(), etc.
sqrt(),
09/10/10 Stroustrup/Programming
43 43
Example
int max(int a, int b); int max(int a, int b){
return a>b?a:b;
int main(){ }
int x;
x = max(5,8);
x = max(x,7);
}
44
Syntax
Function Prototype:
return_type function_name (type1 name1, type2 name2,
..., typen namen);
Function Definition:
return_type function_name (type1 name1, type2 name2,
...,typen namen)
{
....statements...
}
The parameters
Function header
45
Some Examples
Function Prototype Examples
double squared (double number);
void print_report (int);
int get _menu_choice (void);
Function Definition Examples
void parameter list means
double squared (double number)
it takes no parameters
{
return (number * number);
}
Function call:
func1 (a, b, c);
Function header
int func1 (int x, int y, int z)
Each argument can be any valid C expression that has a value:
For example:
x = func1(x+1,func1(2,3,4),5);
Parameters x y z are initialized by the value of a b c
Type conversions may occur if types do not match.
47
return <expression>;
49
50
A Simple Example
#include <stdio.h>
int x=1; /* global variable - bad! */
void demo(void);
int main() {
int y=2; /* local variable to main */
printf ("\nBefore calling demo(), x = %d and y = %d.",x,y);
demo();
printf ("\nAfter calling demo(), x = %d and y = %d.\n",x,y);
return 0;
}
void demo () {
int x = 88, y =99; /* local variables to demo */
printf ("\nWithin demo(), x = %d and y = %d.",x,y);
}
51
Placement of Functions
For large programs mymath.h
int min(int x,int y);
#include the header file in the files int max(int x,int y);
that uses the functions.
mymath.c
For small programs, use the int min(int x,int y)
following order in the only
{
one file:
All prototypes return x>y?y:x;
main() function }
Other functions int max(int x,int y)
{
return x>y?x:y;
}
52
Recursion Functions
1. A recursive function is a function that calls itself.
2. The speed of a recursive program is slower because of
stack overheads.
3. In recursive function we need to specify recursive
conditions, terminating conditions, and recursive
expressions.
53
Recursion - An Example
unsigned int factorial(unsigned int a); unsigned int factorial (unsigned int a) {
if (a==1)
int main () {
unsigned int f,x; return 1;
printf("Enter value between 1 & 8: "); else {
scanf("%d", &x); a *= factorial(a-1);
if (x > 8 || x < 1)
return a;
printf (Illegal input!\n");
else { }
f = factorial(x); }
printf ("%u factorial equals %u\n",
x,f);
}
}
54
Arrays in C
55
Single-Dimensional Arrays
Generic declaration:
typename variablename[size]
typename is any type
variablename is any legal variable name
size is a number the compiler can figure out
For example
int a[10];
Defines an array of ints with subscripts ranging from 0 to 9
There are 10*sizeof(int) bytes of memory reserved for this array.
a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7] a[8] a[9]
57
Initializing Arrays
Initialization of arrays can be done by a comma separated
list following its definition.
For example:
int array [4] = { 100, 200, 300, 400 };
This is equivalent to:
int array [4];
array[0] = 100;
array[1] = 200;
array[2] = 300;
array[3] = 400;
You can also let the compiler figure out the array size for
you:
int array[] = { 100, 200, 300, 400};
58
A Simple Example
#include <stdio.h>
int main() {
float expenses[12]={10.3, 9, 7.5, 4.3, 10.5, 7.5, 7.5, 8, 9.9, 10.2,
11.5, 7.8};
int count,month;
float total;
for (month=0, total=0.0; month < 12; month++)
{
total+=expenses[month];
}
for (count=0; count < 12; count++)
printf ("Month %d = %.2f K$\n", count+1, expenses[count]);
printf("Total = %.2f K$, Average = %.2f K$\n", total, total/12);
return 0;
}
59
Multidimensional Arrays
Arrays in C can have virtually as many dimensions as
you want.
Definition is accomplished by adding additional
subscripts when it is defined.
For example:
int a [4] [3] ;
defines a two dimensional array
a is an array of int[3];
In memory:
a[0][0] a[0][1] a[0][2]
61
An Example
#include <stdio.h>
#include <stdlib.h>
int main () {
int random1[8][8];
int a, b;
for (a = 0; a < 8; a++)
for (b = 0; b < 8; b++)
random1[a][b] = rand()%2;
for (a = 0; a < 8; a++)
{
for (b = 0; b < 8; b++)
printf ("%c " , random1[a][b] ? 'x' : 'o');
printf("\n");
}
return 0;
62
}
The value of the array name
#include <stdio.h> for (i=0; i<3; i++) {
int main(){ printf( "a[%d] <- ",i);
int i; scanf( "%d", &a[i]);
int a[3] = { 1, 2, 3 }; }
printf( "a ? %d\n", a); printf( "a ? %d\n", a);
printf( "a[0] ? %d\na[1] ? %d\na[2] ? printf( "a[0] ? %d\na[1] ? %d\na[2]
%d\n", a[0], a[1], a[2]); ? %d\n", a[0], a[1], a[2]);
printf( "&a[0] ? %d\n&a[1] ? printf( "&a[0] ? %d\n&a[1] ?
%d\n&a[2] ? %d\n", &a[0], &a[1], %d\n&a[2] ? %d\n", &a[0],
&a[2]); &a[1], &a[2]);
}
printf( "\na[0] <- 4 \n");
a[0] = 4; When the array name is used alone,
printf( "a ? %d\n", a); its value is the address of the
printf( "a[0] ? %d\na[1] ? %d\na[2] ? array (a pointer to its address).
%d\n", a[0], a[1], a[2]);
&a has no meaning if used in this
printf( "&a[0] ? %d\n&a[1] ?
%d\n&a[2] ? %d\n\n", &a[0], &a[1], program.
&a[2]);
63
printf("\n");
return 0;
} 65
String Literals
String literals are given as a string quoted by
double quotes.
printf("Long long ago.");
Initializing char array ...
char s[10]="unix"; /* s[4] is '\0'; */
char s[ ]="unix"; /* s has five elements */
68
Printing with printf ( )
Example:
char str[ ] = "A message to display";
printf ("%s\n", str);
Example
char str[10]="unix and c";
printf("%s", str);
printf("\n");
str[6]='\0';
printf("%s", str);
printf("\n");
printf("\n");
printf(str);
printf("\n");
str[2]='%';
printf(str);
printf("\n");
70
Printing with puts( )
The puts function is a much simpler output function than
printf for string printing.
Prototype of puts is defined in stdio.h
int puts(const char * str)
This is more efficient than printf
Because your program doesn't need to analyze the format
string at run-time.
For example:
char sentence[] = "The quick brown fox\n";
puts(sentence);
Prints out:
The quick brown fox
71
72
Inputting Strings with scanf ( )
To read a string include:
%s scans up to but not including the next white space character
%ns scans the next n characters or up to the next white space
character, whichever comes first
Example:
scanf ("%s%s%s", s1, s2, s3);
scanf ("%2s%2s%2s", s1, s2, s3);
Note: No ampersand(&) when inputting strings into character arrays!
(Well explain why later
)
Difference between gets
gets( ) read a line
scanf("%s",
) read up to the next space
73
An Example
#include <stdio.h>
int main () {
char lname[81], fname[81];
int count, id_num;
puts ("Enter the last name, firstname, ID number
separated");
puts ("by spaces, then press Enter \n");
count = scanf ("%s%s%d", lname, fname,&id_num);
printf ("%d items entered: %s %s %d\n",
count,fname,lname,id_num);
return 0;
}
74
The C String Library
String functions are provided in an ANSI
standard string library.
Access this through the include file:
#include <string.h>
Includes functions such as:
Computing length of string
Copying strings
Concatenating strings
This library is guaranteed to be there in any ANSI
standard implementation of C.
75
strlen
strlen returns the length of a NULL terminated character
string:
size_t strlen (char * str) ;
Defined in string.h
size_t
A type defined in string.h that is equivalent to an unsigned int
char *str
Points to a series of characters or is a character array ending with
'\0'
The following code has a problem!
char a[5]={a, b, c, d, e};
strlen(a);
76
strcpy
Copying a string comes in the form:
char *strcpy (char * destination, char * source);
A copy of source is made at destination
source should be NULL terminated
destination should have enough room
(its length should be at least the size of source)
The return value also points at the destination.
77
strcat
Included in string.h and comes in the form:
char * strcat (char * str1, char * str2);
Appends a copy of str2 to the end of str1
A pointer equal to str1 is returned
Ensure that str1 has sufficient space for the
concatenated string!
Array index out of range will be the most popular bug
in your C programming career.
78
Example
#include <string.h>
#include <stdio.h>
int main() {
char str1[27] = "abc";
char str2[100];
printf("%d\n",strlen(str1));
strcpy(str2,str1);
puts(str2);
puts("\n");
strcat(str2,str1);
puts(str2);
}
79
Comparing Strings
C strings can be compared for equality or
inequality
If they are equal - they are ASCII identical
If they are unequal the comparison function will
return an int that is interpreted as:
< 0 : str1 is less than str2
0 : str1 is equal to str2
> 0 : str1 is greater than str2
80
strcmp
Four basic comparison functions:
int strcmp (char *str1, char *str2) ;
Does an ASCII comparison one char at a time until a
difference is found between two chars
Return value is as stated before
If both strings reach a '\0' at the same time, they are
considered equal.
int strncmp (char *str1, char * str2, size_t n);
Compares n chars of str1 and str2
Continues until n chars are compared or
The end of str1or str2 is encountered
Also have strcasecmp() and strncasecmp() which do the same as
above, but ignore case in letters.
81
Example
An Example - strncmp
int main() {
char str1[] = "The first string.";
char str2[] = "The second string.";
size_t n, x;
printf("%d\n", strncmp(str1,str2,4) );
printf("%d\n", strncmp(str1,str2,5) );
}
82
Searching Strings (1)
There are a number of searching functions:
char * strchr (char * str, int ch) ;
strchr search str until ch is found or NULL character
is found instead.
If found, a (non-NULL) pointer to ch is returned.
Otherwise, NULL is returned instead.
You can determine its location (index) in the string by:
Subtracting the value returned from the address of the
start of the string
More pointer arithmetic
more on this later!
83
Example
Example use of strchr:
#include<stdio.h>
#include<string.h>
int main() {
char ch='b', buf[80];
strcpy(buf, "The quick brown fox");
if (strchr(buf,ch) == NULL)
printf ("The character %c was not found.\n",ch);
else
printf ("The character %c was found at position %d\n", ch,
strchr(buf,ch)-buf+1);
}
84
Searching Strings (2)
Another string searching function:
char * strstr (char * str, char * query) ;
strstr searches str until query is found or a NULL
character is found instead.
If found, a (non-NULL) pointer to str is returned.
Otherwise, NULL is returned instead.
85
sprintf
#include <stdio.h>
int sprintf( char *s, const char *format,
);
Instead of printing to the stdin with printf(
),
sprintf prints to a string.
Very useful for formatting a string, or when one
needs to convert integers or floating point
numbers to strings.
There is also a sscanf for formatted input from a
string in the same way scanf works.
86
Example:
#include <stdio.h>
#include <string.h>
int main()
{
char result[100];
sprintf(result, "%f", (float)17/37 );
if (strstr(result, "45") != NULL)
printf("The digit sequence 45 is in 17
divided by 37. \n");
return 0;
} 87