0% found this document useful (0 votes)
4 views36 pages

CSC 315 - System Programming With C Lecture Note

The document provides an overview of the C programming language, detailing its history, relevance, and basic syntax. It covers the setup of the programming environment, the structure of a C program, data types, variables, constants, operators, and decision-making structures. Additionally, it includes examples and exercises to help learners understand the concepts of C programming.

Uploaded by

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

CSC 315 - System Programming With C Lecture Note

The document provides an overview of the C programming language, detailing its history, relevance, and basic syntax. It covers the setup of the programming environment, the structure of a C program, data types, variables, constants, operators, and decision-making structures. Additionally, it includes examples and exercises to help learners understand the concepts of C programming.

Uploaded by

rebeccahard3
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

System Programming with C

Introduction to C
History of C (Dennis Ritchie, UNIX roots).
C is a general-purpose, high-level language that was originally developed by Dennis M. Ritchie
to develop the UNIX operating system at Bell Labs. C was originally first implemented on the
DEC PDP-11 computer in 1972. In 1978, Brian Kernighan and Dennis Ritchie produced the first
publicly available description of C, now known as the K&R standard. The UNIX operating
system, the C compiler, and essentially all UNIX application programs have been written in C. C
has now become a widely used professional language for various reasons:
 Easy to learn
 Structured language
 It produces efficient programs
 It can handle low-level activities
 It can be compiled on a variety of computer platforms.

Facts about C
 C was invented to write an operating system called UNIX.
 C is a successor of B language which was introduced around the early 1970s.
 The language was formalized in 1988 by the American National Standard Institute (ANSI).

Why C is still relevant (system programming, embedded, compilers)


 The UNIX OS was totally written in C.
 Today C is the most widely used and popular System Programming Language.
 Most of the state-of-the-art software have been implemented using C.
 Today's most popular Linux OS and RDBMS MySQL have been written in C.

Why Use C?
C was initially used for system development work, particularly the programs that make-up the
operating system. C was adopted as a system development language because it produces code
that runs nearly as fast as the code written in assembly language. Some examples of the use of C
are:
 Operating Systems, Language Compilers  Assemblers  Text Editors  Print Spoolers 
Network Drivers  Modern Programs  Databases  Language Interpreters  Utilities

1
ENVIORNMENT SETUP
You really do not need to set up your own environment to start learning C programming
language. Reason is very simple, we already have set up C Programming environment online, so
that you can compile and execute all the available examples online at the same time when you
are doing your theory work. This gives you confidence in what you are reading and to check the
result with different options. Feel free to modify any example and execute it online. Try
following example using online compiler option available at [Link]

Local Environment Setup


To set up your environment for C programming language, you need the following two software
tools available on your computer, (a) Text Editor and (b) The C Compiler.

Text Editor: This will be used to type your program. Examples of a few editors include
Windows Notepad, OS Edit command, Brief, Epsilon, EMACS, and vim or vi.
The name and version of text editors can vary on different operating systems. For example,
Notepad will be used on Windows, and vim or vi can be used on Windows as well as on Linux
or UNIX.
The files you create with your editor are called the source files and they contain the program
source codes. The source files for C programs are typically named with the extension ".c".

The C Compiler: The source code written in source file is the human readable source for
your program. It needs to be "compiled" into machine language so that your CPU can actually
execute the program as per the instructions given. The compiler compiles the source codes into
final executable programs. The most frequently used and free available compiler is the GNU
C/C++ compiler, otherwise you can have compilers either from HP or Solaris if you have the
respective operating systems.

 Structure of a C program.
A C program basically consists of the following parts:
 Preprocessor Commands
 Functions
 Variables
 Statements & Expressions
 Comments

2
 Compilation process (source → preprocessor → compiler → assembler → linker →
executable).
 First program: Hello World.
#include <stdio.h>
int main() {
printf("Hello, World!\n");
return 0;
}

Let us take a look at the various parts of the above program:


1. The first line of the program #include is a preprocessor command, which tells a C compiler to
include stdio.h file before going to actual compilation.
2. The next line int main() is the main function where the program execution begins.
3. The next line /*...*/ will be ignored by the compiler and it has been put to add additional
comments in the program. So such lines are called comments in the program.
4. The next line printf(...) is another function available in C which causes the message "Hello,
World!" to be displayed on the screen.
5. The next line return 0; terminates the main() function and returns the value 0.

Compile and Execute C Program


Let us see how to save the source code in a file, and how to compile and run it. Following are the
simple steps:
1. Open a text editor and add the above-mentioned code.
2. Save the file as hello.c
3. Open a command prompt and go to the directory where you have saved the file.
4. Type gcc hello.c and press enter to compile your code.
5. If there are no errors in your code, the command prompt will take you to the next line and
would generate [Link] executable file.
6. Now, type [Link] to execute your program.
7. You will see the output "Hello World" printed on the screen.

3
BASIC SYNTAX
Tokens in C
A C program consists of various tokens and a token is either a keyword, an identifier, a constant,
a string literal, or a symbol. For example, the following C statement consists of five tokens:
printf("Hello, World! \n");
The individual tokens are:
Printf
(
"Hello, World! \n"
)
;

Semicolons
0In a C program, the semicolon is a statement terminator. That is, each individual statement must
be ended with a semicolon. It indicates the end of one logical entity. Given below are two
different statements:
printf("Hello, World! \n");
return 0;

Comments
Comments are like helping text in your C program and they are ignored by the compiler. They
start with /* and terminate with the characters */ as shown below:
/* my first program in C */
NOTE: You cannot have comments within comments and they do not occur within a string or
character literals.

Identifiers
A C identifier is a name used to identify a variable, function, or any other user defined item. An
identifier starts with a letter A to Z, a to z, or an underscore ‘_’ followed by zero or more letters,
underscores, and digits (0 to 9). C does not allow punctuation characters such as @, $, and %

4
within identifiers. C is a case-sensitive programming language. Thus, Manpower and manpower
are two different identifiers in C. Here are some examples of acceptable identifiers:
Mohd, zara, abc, move_name, a_123, myname50 _temp, j, a23b9, retVal

Keywords
The following list shows the reserved words in C. These reserved words may not be used as
constants or variables or any other identifier names.

Whitespace in C
A line containing only whitespace, possibly with a comment, is known as a blank line, and a C
compiler totally ignores it. Whitespace is the term used in C to describe blanks, tabs, newline
characters and comments. Whitespace separates one part of a statement from another and enables
the compiler to identify where one element in a statement, such as int, ends and the next element
begins. Therefore, in the following statement:
int age;

5
there must be at least one whitespace character (usually a space) between int and age for the
compiler to be able to distinguish them. On the other hand, in the following statement:
fruit = apples + oranges; // get the total fruit
no whitespace characters are necessary between fruit and =, or between = and apples, although
you are free to include some if you wish to increase readability.

Data Types and Variables


Data types in C refer to 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. The types in C can be classified as follows:

The array types and structure types are referred collectively as the aggregate types. The type of a
function specifies the type of the function's return value. We will see the basic types in the
following section, whereas other types will be covered in the upcoming chapters.

6
Integer Types

7
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.
Given below is an example to get the size of int type on any machine:

8
When you compile and execute the above program, it produces the following result on Linux:
Storage size for int : 4

Floating-Point Types
The following table provides the details of standard floating-point types with storage sizes and
value ranges and their precision:

The header file float.h defines macros that allow you to use these values and other details about
the binary representation of real numbers in your programs. The following example prints the
storage space taken by a float type and its range values:

9
When you compile and execute the above program, it produces the following result on Linux:

The void Type: The void type specifies that no value is available.

 Variable declaration and initialization.


A variable is nothing but a name given to a storage area that our programs can manipulate. Each
variable in C has a specific type, which determines the size and layout of the variable's memory;
the range of values that can be stored within that memory; and the set of operations that can be
applied to the variable.

Variable Definition in C
A variable definition tells the compiler where and how much storage to create for the variable. A
variable definition specifies a data type and contains a list of one or more variables of that type
as follows:
type variable_list;

10
The line int i, j, k; declares and defines the variables i, j and k; which instruct the compiler to
create variables named i, j, and k of type int.
Variables can be initialized (assigned an initial value) in their declaration. The initializer consists
of an equal sign followed by a constant expression as follows:
type variable_name = value;

For definition without an initializer: variables with static storage duration are implicitly
initialized with NULL (all bytes have the value 0); the initial value of all other variables are
undefined.

extern keyword
You will use the keyword extern to declare a variable at any place. Though you can declare a
variable multiple times in your C program, it can be defined only once in a file, a function, or a
block of code.
Example
Try the following example, where variables have been declared at the top, but they have been
defined and initialized inside the main function:

11
When the above code is compiled and executed, it produces the following result:

12
Lvalues and Rvalues in C There are two kinds of expressions in C:
 lvalue : Expressions that refer to a memory location are called "lvalue" expressions. An lvalue
may appear as either the left-hand or right-hand side of an assignment.
 rvalue : The term rvalue refers to a data value that is stored at some address in memory. An
rvalue is an expression that cannot have a value assigned to it which means an rvalue may appear
on the right-hand side but not on the left-hand side of an assignment.
Variables are lvalues and so they may appear on the left-hand side of an assignment. Numeric
literals are rvalues and so they may not be assigned and cannot appear on the left-hand side. Take
a look at the following valid and invalid statements:

Exercise:
Write a program that prints your name, matric number, and department.
Write a program that converts temperature from Celsius to Fahrenheit.
Write a program that prints the multiplication table of a number.

CONSTANTS AND LITERALS

Constants refer to fixed values that the program may not alter during its execution. These fixed
values are also called literals. Constants can be of any of the basic data types like an integer
constant, a floating constant, a character constant, or a string literal. There are enumeration
constants as well. Constants are treated just like regular variables except that their values cannot
be modified after their definition.

Integer Literals
An integer literal can be a decimal, octal, or hexadecimal constant. A prefix specifies the base or
radix: 0x or 0X for hexadecimal, 0 for octal, and nothing for decimal. An integer literal can also
have a suffix that is a combination of U and L, for unsigned and long, respectively. The suffix
can be uppercase or lowercase and can be in any order.

Here are some examples of integer literals:

13
Following are other examples of various types of integer literals:

Floating-point Literals
A floating-point literal has an integer part, a decimal point, a fractional part, and an exponent
part. You can represent floating point literals either in decimal form or exponential form.
While representing decimal form, you must include the decimal point, the exponent, or both; and
while representing exponential form, you must include the integer part, the fractional part, or
both. The signed exponent is introduced by e or E.

Here are some examples of floating-point literals:

14
Character literals
Character literals are enclosed in single quotes, e.g., 'x' can be stored in a simple variable of char
type.
A character literal can be a plain character (e.g., 'x'), an escape sequence (e.g., '\t'), or a universal
character (e.g., '\u02C0').
There are certain characters in C that represent special meaning when preceded by a backslash,
for example, newline (\n) or tab (\t). Here, you have a list of such escape sequence codes:

15
Following is the example to show a few escape sequence characters:

16
When the above code is compiled and executed, it produces the following result:

String Literals
String literals or constants are enclosed in double quotes "". A string contains characters that are
similar to character literals: plain characters, escape sequences, and universal characters.
You can break a long line into multiple lines using string literals and separating them using
whitespaces. Here are some examples of string literals. All the three forms are identical strings.

17
Defining Constants
There are two simple ways in C to define constants:
 Using #define preprocessor
 Using const keyword
The #define Preprocessor
Given below is the form to use #define preprocessor to define a constant:

The following example explains it in detail:

18
When the above code is compiled and executed, it produces the
following result:

The const Keyword


You can use const prefix to declare constants with a specific type as follows:

The following example explains it in detail:

When the above code is compiled and executed, it produces the following result:

Note that it is a good programming practice to define constants in CAPITALS.

19
Expression and Assignment Statement
An expression is any combination of variables, values (constants), and operators that
evaluates to a single value. An assignment statement is a specific kind of expression
statement where a value is assigned to a variable.

OPERATORS

An operator is a symbol that tells the compiler to perform specific mathematical or logical functions. C
language is rich in built-in operators and provides the following types of operators:

 Arithmetic Operators
 Relational Operators
 Logical Operators
 Bitwise Operators
 Assignment Operators
We will, look into the way each operator works.

Arithmetic Operators
The following table shows all the arithmetic operators supported by the C language. Assume variable A
holds 10 and variable B holds 20, then:

20
Example Try the following example to understand all the arithmetic operators available in C:

When you compile and execute the above program, it produces the following result:

21
Relational Operators
The following table shows all the relational operators supported by C. Assume variable A holds 10 and variable
B holds 20, then:

22
Logical Operators
Following table shows all the logical operators supported by C language. Assume variable A holds 1 and
variable B holds 0, then:

Example
Try the following example to understand all the logical operators available in C:

23
24
When you compile and execute the above program
m, it produces the following result:

Assignment Operators
The following tables lists the assignment operators supported by the C language:

25
DECISION MAKING: Conditional and Iterative Control Structure
Decision-making structures require that the programmer specifies one or more conditions to be
evaluated or tested by the program, along with a statement or statements to be executed if the
condition is determined to be true, and optionally, other statements to be executed if the
condition is determined to be false.

C programming language provides the following types of decision-making statements.

if Statement
The syntax of an ‘if’ statement in C programming language is:

If the Boolean expression evaluates to true, then the block of code inside the ‘if’ statement will be
executed. If the Boolean expression evaluates to false, then the first set of code after the end of the ‘if’
statement (after the closing curly brace) will be executed.

26
Example

When the above code is compiled and executed, it produces the following result:

if…else Statement
An if statement can be followed by an optional else statement, which executes when the Boolean
expression is false.
The syntax of an if...else statement

27
If the Boolean expression evaluates to true, then the if block will be executed, otherwise, the else block
will be executed.

28
When the above code is compiled and executed, it produces the following result:

if...else if...else Statement


An if statement can be followed by an optional else if...else statement, which is very useful to test various
conditions using single if...else if statement.
When using if…else if…else statements, there are few points to keep in mind:

 An if can have zero or one else's and it must come after any else if's.
 An if can have zero to many else if's and they must come before the else.
 Once an else if succeeds, none of the remaining else if's or else's will be tested.

The syntax of an if...else if...else statement

29
Example

30
When the above code is compiled and executed, it produces the following result:

Nested if Statements
It is always legal in C programming to nest if-else statements, which means you can use one if or else
if statement inside another if or else if statement(s).

Syntax
The syntax for a nested if statement is as follows:

You can nest else if...else in the similar way as you have nested if statements.

Example

31
When the above code is compiled and executed, it produces the following result:

32
LOOPS
A loop statement allows us to execute a statement or group of statements multiple times.

while Loop
A while loop in C programming repeatedly executes a target statement as long as a given condition is
true.

The syntax of a while loop

The loop iterates while the condition is true. When the condition becomes false, the program control
passes to the line immediately following the loop.

33
When the above code is compiled and executed, it produces the following result:

for Loop
A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a
specific number of times.
The syntax of a for loop:

34
Here is the flow of control in a ‘for’ loop:

1. The init step is executed first, and only once. This step allows you to declare and initialize any loop
control variables. You are not required to put a statement here, as long as a semicolon appears.
2. Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is false, the body
of the loop does not execute and the flow of control jumps to the next statement just after the ‘for’
loop.
3. After the body of the ‘for’ loop executes, the flow of control jumps back up to the increment
statement. This statement allows you to update any loop control variables. This statement can be left
blank, as long as a semicolon appears after the condition.
4. The condition is now evaluated again. If it is true, the loop executes and the process repeats itself
(body of loop, then increment step, and then again condition). After the condition becomes false, the
‘for’ loop terminates.

Example

When the above code is compiled and executed, it produces the following result:

35
36

You might also like