[go: up one dir, main page]

0% found this document useful (0 votes)
145 views48 pages

CSC 203 Week 3 B

The document discusses the C programming language. It provides: 1) A brief history of C, including its creation in 1972 and standardization in 1988. 2) An overview of why C is useful, noting its efficiency, flexibility, stability, and role in other languages like C++ and Java. 3) A high-level description of the basic components and phases of a C development environment, including editing, preprocessing, compiling, linking, loading, and executing code.

Uploaded by

segdavid03
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
145 views48 pages

CSC 203 Week 3 B

The document discusses the C programming language. It provides: 1) A brief history of C, including its creation in 1972 and standardization in 1988. 2) An overview of why C is useful, noting its efficiency, flexibility, stability, and role in other languages like C++ and Java. 3) A high-level description of the basic components and phases of a C development environment, including editing, preprocessing, compiling, linking, loading, and executing code.

Uploaded by

segdavid03
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 48

CSC 203

Falana O. J.
falanaoj@funaab.edu.ng
Introduction to C
Programming
language
HISTORY OF C
• In 1972 Dennis Ritchie at Bell Labs writes C and in 1978 the
publication of The C Programming Language by Kernighan
& Ritchie caused a revolution in the computing world

• In 1983, the American National Standards Institute (ANSI)


established a committee to provide a modern, comprehensive
definition of C. The resulting definition, the ANSI standard, or
"ANSI C", was completed late 1988.
Why IS C Useful?
C provides:
 Efficiency, high performance and high quality
 flexibility and power
 Stability and small size code
 Provide functionality through rich set of function
libraries
 Gateway for other professional languages like
C  C++  Java

C is used:
 system software Compilers, Editors, embedded systems
 data compression, graphics and computational geometry,
utility programs
 databases, operating systems, device drivers, system level
routines
 there are zillions of lines of C legacy code
 also used in application programs
Basics of C Environment
• C systems consist of 3 parts
– C development environment
– Language
– C Standard Library

• C Development environment has 6 phases


– Edit
– Pre-processor
– Compile
– Link
– Load
– Execute
C DEVELOPMENT Environment

Program edited in
Editor and stored
Phase 1 Editor Disk on disk

Preprocessor
program processes
Phase 2 Preprocessor Disk the code

Creates object code


and stores on disk
Phase 3 Compiler Disk

Links object code


with libraries and
Phase 4 Linker Disk stores on disk
C DEVELOPMENT Environment

Primary memory
Puts program in
memory
Phase 5 Loader

Primary memory
Takes each instruction
and executes it storing
Phase 6 CPU new data values
C Compilers, Linkers, Loaders
Few notes on C program…
C is a Structured programming language.

C is case-sensitive
 Word, word, WorD, WORD, WOrD, worD, etc are all different
variables / expressions

Eg. sum = 23 + 7
What is the value of Sum after this addition ?
The General Form of a Simple Program
• Simple C programs have the form
directives
int main ()
{
statements
}
• C uses { and } in much the same way that some other languages use words like begin
and end.
• Even the simplest C programs rely on three key language features:
– Directives
– Functions
– Statements
Directives
• Before a C program is compiled, it is first edited by a preprocessor.
• Commands intended for the preprocessor are called directives.
• Example:
#include <stdio.h>
• <stdio.h> is a header containing information about C’s standard I/O
library.
• Directives always begin with a # character.
• By default, directives are one line long; there’s no semicolon or other
special marker at the end.
• Two most common directives :
– #include
– #define
Functions
 Every C program consists of one or more modules called FUNCTIONS.
One of the functions must be called main where the execution begins
when the program is run.
 A function is a self-contained module of code that can accomplish some
task.
 A function is a sub-unit of a program that performs a specific task.

 Each function must contain:


 a function heading
 a list of argument declarations (arguments are also referred to as parameters.
 a block of statements, which is enclosed within a pair of braces { }
 The braces may contain one or more elementary statements or other block of statements.
i.e {
{
}
}
Functions
The program will always begin by executing the main function, which
may access other functions. Every function must return a value.
THE MAIN FUNCTION
• The main function is mandatory.
• main is special: it gets called automatically when the program is
executed.
• main returns a status code; the value 0 indicates normal program
termination.
• If there’s no return statement at the end of the main function,
many compilers will produce a warning message.
Statements
A statement is a command to be executed when the program
runs.
Asking a function to perform its assigned task is known as
calling the function.
 Each statement in C needs to be terminated with semicolon (;)

Statement has two parts :


 Declaration
The part of the 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
Few notes on C program…
Comments
 are inserted into the code using /* to start and */ to end a comment
 Some compiler support comments starting with //
 Such comments are useful in explaining the underlying logic of various
program features
 They may appear anywhere within a program, as long as they placed within
delimiters /* and */ or //

 Provides supplementary information but is ignored by the preprocessor and


compiler
/* Program to calculate the area of a circle*/
// This program was written by Iyabo Moshood
C Syntax
#include inserts another file. “.h” files are called
“header” files.
What do the < >
mean? This is a comment. The compiler ignores
this.

#include <stdio.h>
The main() function is
/* The simplest C Program */ always where your program
int main(int argc, char **argv) starts running.
{
Blocks of code (“lexical
printf(“Hello World\n”); scopes”) are marked by { … }
return 0;
}

Returning a value from Print out a message. ‘\n’ means “new


the function line”.
A Quick Digression About the
Compiler
#include <stdio.h>
/* The simplest C Program */ Compilation occurs in two steps:
int main(int argc, char **argv)
Preprocess
{
printf(“Hello World\n”);
“Preprocessing” and “Compiling”
return 0;
}

__extension__ typedef unsigned long long int __dev_t; In Preprocessing, source code is “expanded” into
__extension__ typedef
__extension__ typedef
unsigned int
unsigned int
__uid_t;
__gid_t; a larger form that is simpler for the compiler to
__extension__ typedef
__extension__ typedef
unsigned long int
unsigned long long int
__ino_t;
__ino64_t; understand. Any line that starts with ‘#’ is a
__extension__ typedef
__extension__ typedef
unsigned int
long int
__nlink_t;
__off_t; line that is interpreted by the Preprocessor.
__extension__ typedef long long int __off64_t;
extern void flockfile (FILE *__stream) ;
extern int ftrylockfile (FILE *__stream)
extern void funlockfile (FILE *__stream)
;
; • Include files are “pasted in” (#include)
int main(int argc, char **argv)
{ • Macros are “expanded” (#define)
printf(“Hello World\n”);
return 0; • Comments are stripped out ( /* */ , // )
}
• Continued lines are joined ( \ )

my_program The compiler then converts the resulting text


Compile
into binary code the CPU can run directly.
FunctionS
A Function is a series of instructions to run. You
pass Arguments to a function and it returns a
Value.
“main()” is a Function. It’s only special because it
always gets called first when you run your
program.
Return type, or
void
Function
#include <stdio.h> Arguments
/* The simplest C Program */
int main(int argc, char **argv)
Calling a Function: “printf()” is just
{ another function, like main(). It’s
printf(“Hello World\n”); defined for you in a “library”, a
return 0;
collection of functions you can call from
your program.
} Returning a
value
Simple C Program
/* A first C Program*/

#include <stdio.h>

void main()

{
printf("Hello World \n");

}
Simple C Program
• Line 1: #include <stdio.h>
• As part of compilation, the C compiler runs a program called the
C preprocessor. The preprocessor is able to add and remove code
from your source file.
• In this case, the directive #include tells the preprocessor to
include code from the file stdio.h.
• This file contains declarations for functions that the program
needs to use. A declaration for the printf function is in this file.
Line 2: void main()
• This statement declares the main function.
• The "void" specifies the return type of main. In this case, nothing
Simple C Program
Line 3: {
This opening bracket denotes the start of the program.

Line 4: printf("Hello World \n");


Printf is a function from a standard C library that is used to print
strings to the standard output, normally your screen.
The compiler links code from these standard libraries to the
code you have written to produce the final executable.
The "\n" is a special format modifier that tells the printf to
put a line feed at the end of the line.

Line 5: }
This closing bracket denotes the end of the program.
C Program Structure
• Another example of simple program in C

#include <stdio.h>

int main()
{
printf(“I love programming\n”);
printf(“You will love it too once
”);
printf(“you know the trick\n”);
return 0;
}
The output
• The previous program will produce the
following output on your screen

I love programming
You will love it too once you know the trick
Input/Output Functions
• A few functions that are pre-defined in the header file
<stdio.h> such as :
– printf()
– scanf()
– getchar() & putchar()
1. The printf function
• Used to send data to the standard output (usually the monitor) to be printed
according to specific format.
• General format:
1.printf(“string literal”);
• A sequence of any number of characters surrounded by double quotation
marks.
• E.g printf(“Thank you\n”); Thank you
The printf function cont…
2.printf(“format string”, variables);
• Format string is a combination of text, format specifier and escape
sequence.
• E.g printf (“Total sum is: %d\n”, sum);

Total sum is: 50


Assuming that the
value of sum is 50

• %d is a placeholder (format specifier)


– marks the display position for a type integer variable
– a common format identifier used in printf function.

• \n is an escape sequence
– moves the cursor to the new line
Placeholder / FORMAT Specifier
No Format Specifier Output Type Output Example
1 %d Signed decimal integer 76
2 %i Signed decimal integer 76
3 %o Unsigned octal integer 134
4 %u Unsigned decimal integer 76
5 %x Unsigned hexadecimal (small letter) 9c
6 %X Unsigned hexadecimal (capital letter) 9C
7 %f Integer including decimal point 76.0000
8 %e Signed floating point (using e notation) 7.6000e+01
9 %E Signed floating point (using E notation) 7.6000E+01
10 %g The shorter between %f and %e 76
11 %G The shorter between %f and %E 76
12 %c Character ‘7’
13 %s String ‘76'
2. The scanf function
Reads data from the standard input device
(usually keyboard) and stores it in a variable.
General format:
 scanf(“format string”, &variable);
E.g scanf (“%d” , &a);

Ampersand (&) operator :


 it passes the address of the variable
 tells the scanf() where to find the variable to store the new value

 Format string is a combination of format specifier and


escape sequence (if any).
The scanf function cont…
• Common Format Identifier used in printf and
scanf functions.
printf scanf
int %d %d
float %f %f
double %f %lf
char %c %c
string %s %s
• Example :
int age;
printf(“Enter your age:”);
scanf(“%d”, &age);
The scanf function cont…
• If you want the user to enter more than one value,
you serialise the inputs.

• Example:

float height, weight;

printf(“Please enter your height and weight:”);


scanf(“%f%f”, &height, &weight);
getchar() and putchar()
• getchar() - read a character from standard
input
• putchar() - write a character to standard
output #include <stdio.h>
int main
• Example: {
char my_char;
printf(“Please type a character:”);
my_char = getchar();
printf(“\nYou have typed this character:
”);
putchar(my_char);
return 0;
} Please type a character: h
You have typed this character: h
30
getchar() and putchar() cont
• Alternatively, you can write the previous code using
normal printf / scanf and %c placeholder.
Example
#include <stdio.h>
int main
{
char my_char;
printf(“Please type a character: ”);
scanf(“%c”,&my_char);
printf(“\nYou have typed this character: %c”, my_char);
return 0;
}
Please type a character: h
You have typed this character: h
A Simple C Program
1 /* A first program in C */
2 #include <stdio.h>
3
4int main()
5 {
6 printf( "Welcome to C!\n" );
7
8 return 0;
9 }
Welcome to C!

Comments
 Text surrounded by /* and */ is ignored by computer
 Used to describe program
#include <stdio.h>
 Preprocessor directive
Tells computer to load contents of a certain file
 <stdio.h> allows standard input/output operations
int main()
 Parenthesis used to indicate a function
 int means that main "returns" an integer value
 Braces ({ and }) indicate a block
The bodies of all functions must be contained in braces

printf( "Welcome to C!\n" );


 Instructs computer to perform an action
Specifically, prints the string of characters within quotes (“ ”)
 Entire line called a statement
All statements must end with a semicolon (;)
 Escape character (\)
Indicates that printf should do something out of the ordinary
\n is the newline character

return 0;
 A way to exit a function
 return 0, in this case, means that the program terminated normally

Right brace }
 Indicates end of main has been reached
A Simple C Program

1 /* Addition program */
2 #include <stdio.h>
3
4 int main()
5 {
6 int integer1, integer2, sum; /* declaration */
7
8 printf( "Enter first integer\n" ); /* prompt */
9 scanf( "%d", &integer1 ); /* read an integer */
10 printf( "Enter second integer\n" ); /* prompt */
11 scanf( "%d", &integer2 ); /* read an integer */
12 sum = integer1 + integer2; /* assignment of sum */
13 printf( "Sum is %d\n", sum ); /* print sum */
14
15 return 0; /* indicate that program ended successfully */
16 }
OUTPUT

• Enter first integer


• 45
• Enter second integer
• 72
• Sum is 117
1 /* Using if statements, relational
2 operators, and equality operators */
3 #include <stdio.h>
4
5 int main()
6 {
7 int num1, num2;
10
11 printf( "Enter two integers, and I will tell you\n" );
12 printf( "the relationships they satisfy: " );
13 scanf( "%d%d", &num1, &num2 ); /* read two integers */
14
15 if ( num1 == num2 )
16 printf( "%d is equal to %d\n", num1, num2 );
17
18 if ( num1 != num2 )
19 printf( "%d is not equal to %d\n", num1, num2 );
20
21 if ( num1 < num2 )
22 printf( "%d is less than %d\n", num1, num2 );
23
24 if ( num1 > num2 )
25 printf( "%d is greater than %d\n", num1, num2 );
26
27 if ( num1 <= num2 )
28 printf( "%d is less than or equal to %d\n",
29 num1, num2 );
30
31 if ( num1 >= num2 )
32 printf( "%d is greater than or equal to %d\n",
33 num1, num2 );
34
35 return 0; /* indicates program ended successfully */
36}

Enter two integers, and I will tell you


the relationships they satisfy: 3 7
3 is not equal to 7
3 is less than 7
3 is less than or equal to 7

Enter two integers, and I will tell you


the relationships they satisfy: 22 12
22 is not equal to 12
22 is greater than 12
22 is greater than or equal to 12
MORE ExampleS
#include <stdio.h>
// program prints a number of type int
int main()
{
int number = 4;
printf (“Number is %d”, number);
return 0;
}

Output: Number is 4
MORE ExampleS
#include <stdio.h>
// program reads and prints the same thing
int main()
{
int number ;
printf (“ Enter a Number: ”);
scanf (“%d”, &number);
printf (“Number is %d\n”, number);
return 0;
}

Output : Enter a number: 4


Number is 4
C Token
 Tokens are a series of continuous characters
that compilers treat as separate entities.

 Tokens can be classified into:


1. Reserved words (also known as keywords)
2. Identifiers
3. Constants
4. String Literal
5. Punctuators
6. Operators
Reserved Words
• Keywords that identify language entities
such as statements, data types, language
attributes, etc.
• Have special meaning to the compiler,
cannot be used as identifiers (variable,
function name) in our program.
• Should be typed in lowercase.
• Example: const, double, int, main, void,
printf, while, for, else (etc..)
Identifiers
• Words used to represent certain program
entities (variables, function names, etc).
• Example:
– int my_name;
• my_name is an identifier used as a program
variable
– void CalculateTotal
• CalculateTotal is an identifier used as a function
name
Rules for naming identifiers
Rules Example
Can contain a mix of characters and numbers. H2o
However it cannot start with a number

First character must be a letter or underscore Number1;


_area

Can be of mixed cases including underscore XsquAre


character my_num
Cannot contain any arithmetic operators R*S+T
… or any other punctuation marks… #@x%!!

Cannot be a C keyword/reserved word struct; printf;


Cannot contain a space My height
… identifiers are case sensitive Tax != tax
Constant example – volume of a cone
#include <stdio.h>

int main ()
{
const double pi = 3.412;
double height, radius, base, volume;

printf(“Enter the height and radius of the cone:”);


scanf(“%f %f”, &height, &radius);

base = pi * radius * radius;


volume = (1.0/3.0) * base * height;

printf(“\nThe volume of a cone is %f ”, volume);


return 0;
}
#define
• You may also associate constant using #define preprocessor directive

#include <stdio.h>
#define pi 3.142

int main ()
{
double height, radius, base, volume;

printf(“Enter the height and radius of the cone:”);


scanf(“%f %f”, &height, &radius);

base = pi * radius * radius;


volume = (1.0/3.0) * base * height;

printf(“\nThe volume of a cone is %f ”, volume);


return 0;
}
String Literal
• A sequence of any number of characters surrounded by double
quotation marks “ ”.
• Example of usage in C program:
printf(“What a beautiful day.\n”);

What a beautiful day.

• To have double quotation marks as part of the sentence,


precede the quote with backslash
printf(“He shouted \“stop!\” to the thief.\n”);

He shouted “stop!” to the thief.


Punctuators (separators)
• Symbols used to separate different parts of the C
program.
• These punctuators include:
[ ] ( ) { } , ; “: * #
#include <stdio.h>
• Example:
int main ()
{
int num = 10;
printf(“%d”,num);
return 0;
}

You might also like