COSC 206 Lecture 1 and 2
COSC 206 Lecture 1 and 2
Introduction to C programming
Lecture 1: Introduction
What is C Programming?
Brief History of C Programming
Features of C Programming
Structure of C program
First C Example
C compilation Process
C Syntax
C Tokens
What is C Programming?
C Programming is a high-level, general-purpose programming language that was developed in the 1970s
by Dennis Ritchie at Bell Labs. It is a compiled language that allows developers to create efficient, low-
level programs while also providing high-level abstractions that make it easy to write complex programs.
C is a popular language for system programming, including operating systems, device drivers, embedded
systems, and other low-level applications. It is also widely used in application programming, including
business applications, scientific applications, and games.
Overall, the C language has had a significant impact on the field of computer science and programming,
and it remains a popular choice for developers today due to its power, efficiency, and flexibility
C programming language was created by Dennis Ritchie at Bell Laboratories in 1972. However, its
development began in 1969 as an internal project at Bell Labs, with Ken Thompson as the lead developer.
The development of C language was initially intended to create a language for developing the Unix
operating system. It was designed to be a low-level language that provided direct access to the system
hardware, making it suitable for system programming.
C programming language was developed as a successor to the B programming language. B was developed
by Ken Thompson at Bell Labs in 1970, which was derived from the BCPL programming language
developed by Martin Richards.
B was an interpreted language, and its performance was poor. Ritchie then developed C programming
language, which was faster and more efficient than B.
1
The early versions of C were developed on the DEC PDP-11 computer using the Unix operating system. C
programming language became popular with the release of Unix Version 6 operating system in 1975. As
Unix became more popular, so did C programming language.
In 1978, the first edition of "The C Programming Language" book, also known as the K&R C book, was
published by Brian Kernighan and Dennis Ritchie. The book became very popular and played a significant
role in the widespread adoption of C programming language.
C programming language was standardized by the American National Standards Institute (ANSI) in 1989.
The ANSI C standard, also known as C89 or C90, provided a common specification for C programming
language, which helped in portability and interoperability of C programs.
In 1999, the ISO (International Organization for Standardization) released the C99 standard, which added
several new features to the language, such as inline functions, variable-length arrays, and support for IEEE
floating-point arithmetic.
Since then, there have been several revisions to the C programming language, including C11 and C18. The
latest version of the C standard, C2x, is currently under development and is expected to be released in the
coming years.
Despite being over 50 years old, C programming language is still widely used today for system
programming, embedded systems, and high-performance computing applications. It has influenced the
development of many other programming languages, including C++, Java, and Python, and has left a
significant impact on the field of computer science.
C programming language has several features that make it a popular choice for developing a wide range of
applications. Some of the key features of C programming language are:
Simple and Easy to Learn: C programming language is a simple language with a small number of
keywords and constructs, making it easy to learn for beginners. At the same time, it provides
powerful features for low-level programming, such as direct access to memory, efficient use of
resources, and precise control over program flow.
Portable: C programs can be written and compiled on different platforms, including Windows, Mac,
and Linux, making it a portable language. This is due to the use of a standard set of libraries and
compilers, such as the GNU Compiler Collection (GCC), which are available on many platforms.
2
Efficient Memory Management: C programming language provides manual memory management,
allowing developers to control the allocation and de-allocation of memory, resulting in efficient
memory utilization.
Rich Library Support: C programming language has a rich set of libraries that provide access to a
wide range of functions, making it easy to implement complex functionality.
Low-level Language Features: C programming language provides low-level language features like
direct access to memory and pointers, making it possible to implement low-level functionality.
Overall, the combination of simplicity, portability, efficiency, and rich functionality makes C
programming language a powerful tool for developing a wide range of applications.
• “Mid-level” Language
• It is everywhere! (portable)
• Mother language
3
Structure of C Program
2. Link section: The link section provides instructions to the compiler to link functions from the
system library such as using the #include directive.
3. Definition section: The definition section defines all symbolic constants such using the #define
directive.
4. Global declaration section: There are some variables that are used in more than one function.
Such variables are called global variables and are declared in the global declaration section that is
outside of all the functions. This section also declares all the user-defined functions.
5. main () function section: Every C program must have one main function section. This section
contains two parts; declaration part and executable part.
4
a. Declaration part: The declaration part declares all the variables used in the executable part.
b. Executable part: There is at least one statement in the executable part.
These two parts must appear between the opening and closing braces. The program execution
begins at the opening brace and ends at the closing brace. The closing brace of the main function
is the logical end of the program. All statements in the declaration and executable part end with a
semicolon.
6. Subprogram section: If the program is a multi-function program then the subprogram section
contains all the user-defined functions that are called in the main () function. User-defined functions
are generally placed immediately after the main () function, although they may appear in any order.
Although not all c programs will include all of the above sections, you may find them in a real
world C program. Hence, the need to understand the various sections. The figure below shows a
simple program that demonstrates the usage of the various sections of C program explained above.
5
Structure of C Program: An Example
6
Example 1: A program that welcome you to the course
The table below gives a description of the above program explaining the various part of the
program
int main() main is the first function that is executed in the program.
7
Example 2: A simple C program that adds two integers
Description and explanation of the various part of the above program is given in the table below
main is the first function that is executed in the program. The int main is used in
order to return an integer value
int main()
Prompt the user to enter some input by printing the string “Enter two numbers
printf() to be added”
Reads data from standard input streams and writes the results into the specified
scanf variables
Sum = a + b Sum the content of a and b and store the result in the sum variable for output
8
return 0 Exit the main function, returning 0 to the caller
In the above examples, we have used the printf and scanf functions for printing formatted output and input
respectively, even though we don’t know how they really work. In this section, we will have a closer look
at both functions.
The printf() and scanf() functions are used for output and input in C language, repectively. Both
functions are inbuilt library functions, defined in stdio.h (header file). Each time we use the statement
#include<stdio.h> in the beginning of our program, we are informing the C preprocessor that it should
include those functions. Without including them, we won’t be able to read input or print output.
printf() function
The printf() function is used for output. It prints the given statement to the console.
printf("format string",argument_list);
The function takes two arguments:
a. Format string: A string that specifies the format of the output to be printed. This string can
contain conversion specifiers that tell printf() what type of output to print and how to print it.
The format string can be %d (integer, as we have seen in the examples above), %c (character),
%s (string), %f (float) etc.
b. A variable-length argument list that contains the memory addresses of variables whose value
will be printed.
scanf() function
The scanf() function is used for input. It reads the input data from the console.
scanf("format string",argument_list);
9
The function takes two arguments:
a. format: A string that specifies the format of the input to be read. This string can contain
conversion specifiers that tell scanf() what type of input to expect and how to read it.
The format string can be %d (integer, as we have seen in the examples above), %c (character),
%s (string), %f (float) etc.
b. A variable-length argument list that contains the memory addresses of variables where the input
values will be stored. These memory addresses must be passed as pointers.
1. #include<stdio.h>
2. int main(){
3. int number;
4. printf("enter a number:");
5. scanf("%d",&number);
6. printf("cube of number is:%d ",number*number*number);
7. return 0;
8. }
The program above used both printf and scanf for output and input respectively.
In line 5, scanf is used to enter an integer specified by %d and the value is store in the variable number
In line 6, the printf is used to print the cube of the number in the specified format
enter a number:5
cube of number is:125
10
C Compilation Process
1. The Preprocessor
The Preprocessor accepts source code as input and is responsible for:
• removing comments
• Interpreting special preprocessor directives denoted by #. For example
• #include -- includes contents of a named file. Files usually called header files.
e.g #include -- standard library maths file.
#include -- standard library I/O file
• #define -- defines a symbolic name or constant.
#define MAX_ARRAY_SIZE 100
2. C Compiler
Once the C preprocessor has stripped the source code of the comments and expanded the preprocessor
directives given by the lines that begin with #, the compiler translates the C code into assembly language,
which is a machine level code that contains instructions that manipulate the memory and processor directly,
in a layer beneath the operating system
3. Assembler
The assembly code is converted into object code by using an assembler. The name of the object file
generated by the assembler is the same as the source file. The extension of the object file in DOS is '.obj,'
11
and in UNIX, the extension is 'o'. If the name of the source file is 'hello.c', then the name of the object file
would be 'hello.obj'.
4. Link Editor
Mainly, all the programs written in C use library functions. These library functions are pre-compiled, and
the object code of these library files is stored with '.lib' (or '.a') extension. The main task of the linker is to
combine the object code of library files with the object code of our program. Sometimes the situation arises
when our program refers to the functions defined in other files; then linker plays a very important role in
this. It links the object code of these files to our program. Therefore, we conclude that the job of the linker
is to link the object code of our program with the object code of the library files and other files. The output
of the linker is the executable file.
Syntax of C language
The syntax of the C programming language is characterized by a set of rules that dictate how C programs
should be written. It specify which tokens are valid and indicate the expected order of token. Some key
elements of C syntax include:
1. Case Sensitivity:
• C is case-sensitive, meaning that uppercase and lowercase letters are treated as distinct.
2. Comments:
• Comments in C are written using /* */ for multiline comments and // for single-line
comments.
3. Semicolons:
• Statements in C are terminated by semicolons (;). Each executable statement must end
with a semicolon.
4. Variables:
• Variables must be declared before use, specifying their data type. For example, int x;
declares an integer variable named "x."
C Tokens
Tokens are the smallest individual unit of a C program.
They are the basic building blocks in C language which are constructed together to write a
program.
C Consist of the following types of tokens:
i. Identifier: x, y, …
ii. Keywords: printf, int, scanf, …
iii. Constants: 5, 5.0, …
iv. Strings: “Hello”
v. Special Symbols: { } ; < > # /* */ ….
12
vi. Operators: +, -, …
i. Identifiers
Identifiers are Names used for data and objects in C. It is used as a general terminology for the
names of variables, functions, and arrays. Identifiers allow us to name data and other objects
in the program. Each identified object in the computer is stored at a unique address.
Rules for identifiers in C:
a. first character must be alphabetic [a-z,A-Z] character or underscore (_)
b. must consist of only alphabetic, digit, underscore characters
c. first 31/63 characters are significant
d. Must not duplicate a reserved word
e. case (upper/lower) matters
13
The table below gives a list of C keywords
auto break case char const
continue default do double else
enum extern float for goto
if int long register return
short signed sizeof static struct
switch typedef union unsigned void
volatile while
iii. C Constant
A constant refers to the data items that do not change their value during the program execution.
C support the following types of constants:
Integer Constants
Integer constants are whole numbers without any fractional part. It must have at least one digit
and may contain either + or – sign. A number with no sign is assumed to be positive.
There are three types of integer constants:
Decimal Integer Constants
Integer constants consisting of a set of digits, 0 through 9, preceded by an optional – or + sign.
Example of valid decimal integer constants: 341, -341, 0,8972
Octal Integer Constants
Integer constants consisting of sequence of digits from the set 0 through 7 starting with 0 is said
to be octal integer constants. Example of valid octal integer constants: 010, 0424, 0,0540
Hexadecimal Integer Constants
Hexadecimal integer constants are integer constants having sequence of digits preceded by 0x or
0X. They may also include alphabets from A to F representing numbers 10 to 15.
Example of valid hexadecimal integer constants: 0xD, 0X8d, 0X, 0xbD
It should be noted that, octal and hexadecimal integer constants are rarely used in programming.
Real Constants
The numbers having fractional parts are called real or floating point constants. These may be
represented in one of the two forms called fractional form or the exponent form and may also
have either + or – sign preceding it.
Example of valid real constants in fractional form or decimal notation
0.05, -0.905, 562.05, 0.015
Character constant:
A character constant is either a single alphabet, a single digit, or a single special symbol enclosed
within single quotes, e.g., 'x', and can be stored in a simple variable of char type. The value of a
14
character constant is stored within single quotes and has a maximum length of 1. For example, 'x'
is a valid character constant, but 'xy' is not a valid character constant.
String constant
A string constant is a sequence of characters enclosed in double quotes; the characters may be
letters, numbers, special characters, and blank space, etc. Examples of string constants include:
1. "COSC 206"
2. "Ali"
3. "+123"
4. "1-/a"
5. "good" // string constant
6. "" // null string constant
7. " " // string constant of six white spaces
8. "x" // string constant having a single character
9. "Earth is round\n" // prints a string with a newline
The following special symbols are used in C, each having a specific meaning, and therefore,
cannot be repurposed for other uses: [] () {} , ; : * … = #
Braces {}: These opening and ending curly braces mark the start and end of a block of code
containing more than one executable statement.
Parentheses (): These special symbols are employed to indicate function calls and function
parameters.
Brackets []: Opening and closing brackets are utilized as array element references. They indicate
single and multidimensional subscripts.
15
Lecture 1: Review Exercise
1. Briefly explain what C programming is and its primary applications.
2. Describe the origin of the C programming language, including key figures and milestones.
3. List at least five key features of C programming and explain how each contributes to its popularity.
7. Examine the provided example program that prints "Welcome to C Programming" and identify
each component, such as comments, preprocessor directives, and function calls.
8. Describe the purpose of printf() and scanf() functions in C, including the syntax and how they work
with format specifiers.
9. Outline the stages of C program compilation, including the roles of the preprocessor, compiler,
assembler, and linker.
11. Provide examples of each token type, including identifiers, keywords, constants, and operators.
16
COSC 206
Introduction to C Programming
Variable declaration
Variable initialization
C data types
Symbolic Constant
Variables in C
A variable is a named memory location in which data of a certain type can be stored. The contents of a
variable can change, thus the name. User defined variables must be declared before they can be used in a
program. It is during the declaration phase that the actual memory for the variable is reserved. All
variables in C must be declared before use.
Rules for naming variable in C
i. Variable naming rules in C include the following:
ii. Variable names can consist of letters, digits, and underscores (_).
iii. Variable names must commence with letters.
iv. Keywords, such as 'for' and 'while,' cannot be utilized as variable names.
v. Variable names are case-sensitive; for instance, 'int x;' and 'int X;' declare two distinct variables.
Examples of valid and invalid variable names are given below:
int money$owed; (incorrect: cannot contain $)
int total_count (correct)
int score2 (correct)
int 2ndscore (incorrect: must start with a letter)
int long (incorrect: cannot use keyword)
Variable Declaration in C
In C, variables have to be declared before they are used. Variable declaration is the process of
explicitly informing the compiler of the characteristics of the variable. It typically involves naming
a variable, specifying its data type and optionally assigning a value to the variable .
17
data_type variable name;
Where
• data_type: Represents the type of data that the variable will hold (e.g., int, float, char).
• variable_name: Is the name given to the variable, allowing you to reference it in your program.
For example, in C, you might declare an integer variable named age as follows:
int age ;
This tells the compiler to set aside memory to store an integer value under the name age. After declaring a
variable, you can then assign a value to it, like:
age = 37; // stores the value 37 in the variable
Variable declaration only reserves some memory space for the variable, but doesn’t put any value in the
variable. Values get into the memory location of the variable through initialization or assignment.
C also allow the declaration of more one variable in a single statements. C uses the following syntax for
declaring more than one variable in a single statement.
18
value of sum is 33
value of money is 44.119999
value of letter is E
value of pressure is 2.010000
C Data Types
An extensive system used for declaring variables or functions of different types. The type of a variable
determines how much space it occupies in storage and how the bit pattern stored is interpreted or how it
can be manipulated in a program.
C has the following 4 types of data types
char: can be used to store a single character, such as the letter ‘a’, the digit character ‘6’, or a
semicolon ‘;’. The keyword used to define character variables in C is: char.
An example of declaring a character variable called letter is:
char letter;
Example 2: Using basic data types
#include <stdio.h>
int main (void)
{
19
// declaration and initialization
int integerVar = 100;
float floatingVar = 331.79;
double doubleVar = 8.44e+11;
char charVar = 'W';
// printing the variables values
printf ("integerVar = %d\n , ",integerVar);
printf ("floatingVar = %f\n", floatingVar);
printf ("doubleVar = %e\n", doubleVar);
printf ("doubleVar = %g\n", doubleVar);
printf ("charVar = %c\n" , charVar);
return 0;
}
Data types Sizes and ranges
Every type has a size and range of values that its supports. This range is determined by the amount
of storage that is allocated to store a value belonging to that type of data. In general, that amount
of storage is not defined in the language. It typically depends on the computer you’re running, and
is, therefore, called implementation- or machine-dependent.
For example, an integer might take up 32 bits on your computer, or it might be stored in 64. You
should never write programs that make any assumptions about the size of your data types. The
language standards only guarantees that a minimum amount of storage will be set aside for each
basic data type. For example, it’s guaranteed that an integer value will be stored in a minimum of
32 bits of storage, which is the size of a “word” on many computers.
To get the exact size of a type or a variable on a particular platform, you can use
the sizeof operator. The expressions sizeof(type) yields the storage size of the object or type in
bytes. The following is an example to get the size of int type on any machine:
Example 3: Determining the size of int data type on any machine
#include <stdio.h>
#include <limits.h>
int main()
{
printf("Storage size for int : %d \n", sizeof(int));
return 0;
}
20
When you compile and run the above program, it produces the following output
Program Sample output
size of int = 4
Example 4: Determining the size, range and precision of float data type on any machine
#include <stdio.h>
#include <float.h>
int main()
{
printf("Storage size for float : %d \n", sizeof(float));
printf("Minimum float positive value: %E\n", FLT_MIN );
printf("Maximum float positive value: %E\n", FLT_MAX );
printf("Precision value: %d\n", FLT_DIG );
return 0;
}
When you compile and run the above program, it produces the following output
Program sample output
size of float = 4
float min = 1.175494E-38
float max = 3.402823E+38
float precision = 6
The following table gives you details about the basic types with their storage sizes and
value ranges:
21
unsigned long int 4 0 to 4294967295
float 4 -3.4E-38 to 3.4E+38
double 8 1.7E-308 to 1.7E+308
Long double 10 3.4E-4932 to 1.1E+4932
#define MAX 10
#define CH ‘b’
#define HELLO “Hello World \n”
Wherever a symbolic constant appears in the code, it is equivalent to direct text-replacement with the
constant it defines. For example,
printf(HELLO);
prints the string Hello World. The reason for using symbolic constants rather than constant values directly,
is that it prevents the proliferation of “magic numbers”—numerical constants scattered throughout the code.
This is very important as magic numbers are error-prone and are the source of major difficulty when
attempting to make code-changes. Symbolic constants keep constants together in one place so that making
changes is easy and safe.
Example 5: Use of Symbolic Constant
#include <stdio.h>
#define LENGTH 10
#define WIDTH 5
#define NEWLINE ‘\n’
int main()
{
int area;
area = LENGTH * WIDTH;
printf("value of area : %d", area);
printf("%c", NEWLINE);
return 0;
}
value of area : 50
22
Two ways to define constant in C
There are two methods for defining constants in C programming:
1. Using the C #define preprocessor, as illustrated above.
2. Utilizing the C const keyword.
When employing the C const keyword, constants in C programming can be defined by using the
const prefix along with a specific type in the following manner:
const type identifier = value;
For instance:
const float PI = 3.14;
the value of PI variable will remain the same throughout the program.
Example 6: demonstrates constant definition using the const keyword
#include <stdio.h>
int main()
{
const int LENGTH = 10;
const int WIDTH = 5;
const char NEWLINE = '\n';
int area;
area = LENGTH * WIDTH;
printf("value of area : %d", area);
printf("%c", NEWLINE);
return 0;
}
23
Lecture 2: Review Exercise
1. Define a variable in C programming and explain the rules for naming variables.
2. Provide examples of valid and invalid variable names and explain why some names are
not allowed
3. Describe the syntax for declaring a variable in C and explain the difference between
declaration and initialization.
4. Write a code snippet to declare and initialize three different types of variables.
6. Explain the significance of data type size and range and how they vary across different
systems.
7. Review the provided examples of data types (integer, float, double, char).
8. Write a short program using each basic data type to print values to the console.
9. Explain the purpose of constants in C and the two ways to define them.
10. Provide examples of defining constants using both #define and const.
11. Describe symbolic constants and discuss why they are preferable to using "magic
numbers" in code.
12. Write a program that uses symbolic constants for calculating and printing the area of a
rectangle.
13. Write a program that declares and initializes variables for a user's name, age, and height,
then prints these details in a formatted message.
24