Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
99 views

C Programming

C programming language

Uploaded by

fdar928
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
99 views

C Programming

C programming language

Uploaded by

fdar928
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 55

Computer Programming (ESC-201)

Course Instructor: Dr. Auqib Hamid Lone

May , 2024
1. Introduction to
Programming
a. Introduction to Components
of a Computer System:
■ Memory
■ Processor
Contents ■ I/O Devices
■ Storage Devices
Chapter 1 b. Operating System
c. Assembler
d. Compiler
e. Interpreter
f. Loader
g. Linker
1. Introduction to
Programming
h. Representation of
Algorithm

Contents 1. Flowchart

2. Pseudocode

i. Basics of C Programming
+
● Computer: Computational device used to process the data
under the control of a program.

Input Data Output Data

Program

▪ Computer system functionality is program execution.

▪ Computer is made of separate pieces with specific function that all


work together
+ ● Program: is a sequence of instructions along with Data.
Instruction

Program

Data

Instruction: Binary sequence –Bind with- Operations

Data: Binary sequence –Bind with- Value


+ Computer System Components

The physical pieces of computer are called Hardware

The virtual pieces of computer are called Software


+ Computer System Components

■ CPU [Processing]

■ Memory [Storage]

■ Input-Output [external
communication]

A von Neumann architecture scheme


Source:https://en.wikipedia.org/wiki/Von_Neumann_architecture
✦ CPU – controls the operation of the
+ computer and performs its data
processing functions
There are four
main structural ✦ Main Memory – stores data
components ✦ I/O – moves data between the
of the computer: computer and its external
environment

✦ System Interconnection – some


mechanism that provides for
communication among CPU, main
memory, and I/O
Functions
+
● There are four basic functions that a computer can perform:
○ Data processing
■ Data may take a wide variety of forms and the range of processing requirements is
broad
○ Data storage
■ Short-term
■ Long-term
○ Data movement
■ Input-output (I/O) - when data are received from or delivered to a device (peripheral)
that is directly connected to the computer
■ Data communications – when data are moved over longer distances, to or from a
remote device
○ Control
■ A control unit manages the computer’s resources and orchestrates the performance
of its functional parts in response to instructions
Structure
+ System BUS
● Bus is a communication channel used to provide the communication
between different components.

● Characteristic of the bus is shared transmission media.

● The Bus which is used to provide the communication between the major
components of the system (CPU, Memory, IO ) is called a System Bus.

CPU Mem
System Bus
IO
● The CPU is often referred to as the brain of
+ CPU

the computer

Control Unit
○ Controls the operation of the CPU and
Major structural hence the computer
components: ○ Arithmetic and Logic Unit (ALU)
○ Performs the computer’s data processing
function

○ Registers
○ Provide storage internal to the CPU

○ CPU Interconnection
○ Some mechanism that provides for
communication among the control unit,
ALU, and registers
+ Input and Output
Devices ● Input devices allow users to provide
data and instructions to the computer
● Common input devices include
Major structural keyboards, mouse, touchscreens, and
components: microphones
● Output devices display information
processed by the computer
● monitors, printers, speakers, and
projectors are examples of output
devices
● Computer memory is used to store data
+ Memory
and instructions temporarily or
permanently.
Random Access Memory (RAM):
Major structural ● RAM is volatile memory
● store data and instructions that the
components: CPU needs to access quickly.
● faster but more expensive compared to
secondary storage.
Read-Only Memory (ROM):
● ROM is non-volatile memory
● stores instructions required to start the
computer.
● contains firmware that initializes the
computer’s hardware components
during the boot process
● Secondary Storage Devices

+Storage Devices Cont. ● Solid State Drives (SSDs)


○ SSDs use NAND flash memory.
○ No moving parts, making them faster and
more durable.
○ Commonly used in laptops, tablets, and
Major structural smartphones.
○ More expensive per gigabyte compared to
components: HDDs.

● Optical Drives:
● Optical drives (e.g., CD/DVD/Blu-ray) use laser
technology.
● Less common due to digital downloads and
streaming.
● Blu-ray discs offer higher storage capacity than
DVDs.
● Secondary Storage Devices
+Storage Devices Cont. ● Cloud Storage:
○ Remote storage on servers (e.g.,
Google Drive, Dropbox).
○ Accessible from any device with an
internet connection.
Major structural ○ Consider security and privacy
implications.
components: ● Network Attached Storage (NAS):
○ Specialized storage servers connected
to a network.
○ Provide centralized storage for multiple
users or devices.
○ Used for backups, media streaming,
and file sharing.
+

Fig: The Memory Hierarchy


Source:https://diveintosystems.org/book/C11-MemHierarchy/mem_hierarchy.html#FigMemoryHierarchy
+ Operating System
● What is an Operating System?
○ A program that acts as an intermediary
between a user of a computer and the
computer hardware.
● What is the purpose of an operating system?
○ To provide an environment in which a
user can execute programs.
● What are the goals of an Operating
System?
○ The primary goal of an Operating System is to
make the computer system convenient to use.
○ The secondary goal is to make the computer
system efficient to use.
.
+ Operating System Functions
● Process Management:
● Create, manage, and terminate processes
● Scheduling tasks to utilize CPU efficiently
● Memory Management:
● Allocate and deallocate memory
for processes
● Virtual memory management
● File System Management:
● Organize and manage files on
storage devices
● Provide file access and security
● I/O Management:
● Handle input and output operations
● Manage communication with peripherals
+ Operating System Components
● Kernel:
● Core component, manages system resources
● Provides essential services to other parts
of the operating system
● User Interface:
● CLI (Command Line Interface)
● GUI (Graphical User Interface)
● Device Drivers:
● Manage communication between
hardware devices and the OS
● Utilities:
● Tools for system management, file manipulation
and troubleshooting
+ Evolution Operating System
● Timeline showcasing major milestones:
● 1950s: Batch processing systems (e.g., IBM OS/360)
● 1960s: Time-sharing systems (e.g., CTSS, MULTICS)
● 1970s: Introduction of microcomputers and early personal computers
(e.g., CP/M, MS-DOS)
● 1980s: Graphical User Interfaces (e.g., Macintosh, Windows)
● 1990s-Present: Advancements in multi-tasking, multi-user, and real-time
operating systems (e.g., Linux, macOS, Android)
+ Operating System Types
● Single-User, Single-Tasking OS:
● Example: MS-DOS
● Single-User, Multi-Tasking OS:
● Example: Windows, macOS
● Multi-User OS:
● Example: Unix, Linux
● Real-Time OS:
● Example: VxWorks, QNX
● Embedded OS:
● Example: Android, iOS
+ Assembler
● An assembler is a program that translates assembly language code into machine code or
object code.
● It's the lowest level of programming language and directly corresponds to the instructions
of a specific machine architecture.
● Functions:
● Translation:
i. Converts mnemonic assembly instructions into binary machine language instructions.
● Symbol Resolution:
i. Resolves symbolic names and labels to their corresponding memory addresses.
● Code Generation:
i. Produces relocatable object code that can be executed by the computer's processor.
● Example:
● NASM (Netwide Assembler) for x86 architecture.
● GAS (GNU Assembler) for the GNU Compiler Collection (GCC).
+ Compiler
i. A compiler is a software tool that translates high-level programming languages into machine code or
intermediate code.
ii. It performs the translation in a single step, generating an executable file.
● Functions:
i. Lexical Analysis:
1. Breaks the source code into tokens such as keywords, identifiers, and operators.
ii. Syntax Analysis:
1. Checks the grammar and structure of the code based on the language's syntax rules.
iii. Semantic Analysis:
1. Ensures the correctness of expressions, types, and scope within the program.
iv. Code Optimization:
1. Improves the efficiency of the generated machine code by applying various optimization
techniques.
v. Code Generation:
1. Translates the optimized intermediate code into machine code specific to the target platform.
● Example:
i. GCC (GNU Compiler Collection) for C, C++, and other languages.
ii. javac for Java programming language.
+ Interpreter
● An interpreter is a program that directly executes source code without prior compilation.

● It reads each line of code, translates it into machine code, and executes it immediately.

Functions:
1. Parsing:
Analyzes the syntax of the source code to identify the sequence of commands.
2. Execution:
Interprets and executes each command or statement directly.
3. Error Handling:
Detects and reports syntax errors and runtime errors as they occur.

Example:
○ Python Interpreter (CPython) for the Python programming language.
○ Ruby Interpreter (MRI) for the Ruby programming language.
+ Linker
■ A linker is a program that combines multiple object files and libraries into a single executable or
shared library.
■ It resolves external references, merges code and data sections, and generates the final
executable file.
○ Functions:
■ Symbol Resolution:
● Resolves references to symbols defined in other object files or libraries.
■ Code and Data Merging:
● Combines code and data sections from multiple object files into a single executable.
■ Relocation:
● Adjusts memory addresses and references to account for the final layout of the
executable in memory.
○ Example:
■ GNU ld (GNU Linker) for linking object files and libraries in the GNU Compiler Collection (GCC).
■ Microsoft Linker (link.exe) for linking object files on the Windows platform.

+ Loader
○ A loader is a program that loads executable files into memory for execution by the CPU.
○ It prepares the program for execution by resolving references, allocating memory, and initializing data
structures.
● Functions:
○ Loading:
■ Reads the executable file from storage into memory.
○ Address Resolution:
■ Resolves symbolic references and relocates addresses based on the program's memory layout.
○ Memory Allocation:
■ Allocates memory space for the program's code, data, and stack segments.
● Example:
○ Windows Loader for loading executable files on the Windows operating system.
○ ELF Loader for loading executable files on Unix-like operating systems.

+ Putting it Altogether

Source:https://www.techtarget.com/searchdatacenter/definition/assembler
+ Introduction to Algorithms
❖ Algorithms are step-by-step procedures or methods used for solving
problems
❖ An algorithm is a finite sequence of well-defined instructions used to solve a
problem or perform a computation

Characteristics
➢ Input: Data provided to the algorithm.
➢ Output: Result produced by the algorithm.
➢ Definiteness: Each step of the algorithm must be precisely defined.
➢ Correctness: The algorithm must produce the correct output for all
valid inputs.
➢ Finiteness: The algorithm must terminate after a finite number of steps.
➢ Effectiveness: Each step must be executable using basic operations.
Representation of Algorithm
+ Flowchart Representation
● Flowcharts are graphical representations of algorithms, consisting of
various symbols connected by arrows to indicate the flow of control.
● Common flowchart symbols include:
● Start/End: Indicates the beginning
or end of the algorithm.
● Process: Represents a computational
step or operation.
● Decision: Represents a conditional
statement or branching.
● Input/Output: Represents data input or output.
+ Representation of Algorithm
Pseudocode Representation
● Pseudocode is a high-level description of algorithms using structured
English-like syntax, allowing for easy understanding and translation into
programming languages.
● Advantages of pseudocode include language independence, readability,
and aiding in algorithm design.
+ Problem Solving

Algorithm: Addition of two numbers


SStart
1. Start Nnum1,num2,
sum
2. Input: num1, num2,
sum Sum=num1+num2
3. Sum = num1+num2
4. Output: sum sum

5. Stop
Stop
+ Problem Solving
Algorithm: Finding Largest of two numbers SStart
1. Start Nnum1,
num2
2. Input: num1, num2,
3. If num1 > num2
then: num1 > num2

output (num1 is bigger)


else:
output (num2 is bigger) num2 num1

4. Stop Stop
+ Problem Solving
Algorithm: Print first 10 natural numbers
Algorithm: Checking whether number is even or odd
Algorithm: Checking whether number is a Prime Number
Algorithm: Calculate sum of digits of a number
Algorithm: Checking whether number is palindrome
Algorithm: Steps involved in C program development
+ History of C

● Developed in the early 1970s by Dennis Ritchie at


Bell Labs.
● Originated as a systems programming language for
Unix.
● Influenced by earlier languages like B and BCPL.
● Became popular due to the growth of Unix.
● Continues to be widely used in operating systems,
system programming, and embedded systems.
+ Features of C

● Simple and efficient language.


● Close-to-the-machine approach.
● Powerful set of operators.
● Rich library of functions.
● Portability across different platforms.
● Flexibility for low-level and high-level programming.
● Strong influence on other languages like C++, Java, and
Python.
Standard I/O in C
+ ● C provides standard input and output facilities for reading and writing
data.
● Standard I/O is handled by the stdio.h library.
● Key functions include printf() for output and scanf() for input.
● printf() is used to display output on the console.
● Format specifier %d is used for integers, %f for floats, %c for characters,
%s for strings, etc.

Example: printf("The value of x is %d\n", x);

● scanf() is used to read input from the console.


● Requires format specifiers to match the data type being read.

Example: scanf("%d", &x); (reads an integer into variable x).


+ Components of C Language
● C language is comprised of several key components that work together to
create functional programs.
● Understanding these components is essential for mastering C programming.
a. Keywords
b. Identifiers
c. Constants
d. Variables
e. Data Types
f. Operators
g. Control Structures
h. Functions
i. Arrays
j. Pointers
Components of C Language
+ Keywords in C
❖ Keywords are reserved words in C with predefined meanings.
❖ They cannot be used as identifiers.
❖ Each keyword serves a specific purpose in the C language.
❖ Common Keywords:
● auto: Specifies automatic storage duration for variables.
● break: Terminates the current loop or switch statement.
● case: Marks a branch in a switch statement.
● char: Declares a character data type.
● const: Declares constants that cannot be modified.
● continue: Skips the rest of the loop and starts the next iteration.
● default: Specifies the default case in a switch statement.
● do: Starts a do-while loop.
● double: Declares a double-precision floating-point data type.
● else: Marks the alternative statement in an if-else statement.
+ Components of C Language
Common Keywords in C

● enum: Declares an enumeration data type.


● extern: Declares variables and functions that are defined in other files.
● float: Declares a single-precision floating-point data type.
● for: Starts a for loop.
● goto: Transfers control to a labeled statement.
● if: Starts an if statement.
● int: Declares an integer data type.
● long: Declares a long integer data type.
● register: Suggests that a variable be stored in a register.
● return: Exits a function and returns a value.
+ Components of C Language
Common Keywords in C

● short: Declares a short integer data type.


● signed: Declares a signed data type.
● sizeof: Returns the size of a variable or data type.
● static: Specifies static storage duration for variables.
● struct: Declares a structure data type.
● switch: Starts a switch statement.
● typedef: Defines a new data type with an alias.
● union: Declares a union data type.
● unsigned: Declares an unsigned data type.
● void: Specifies an empty data type.
● volatile: Indicates that a variable may be modified externally.
● while: Starts a while loop.
+ Components of C Language
Identifiers in C
Identifiers are user-defined names used to identify variables, functions, arrays, etc. in a
C program.

● They provide a means of giving a unique name to different program elements.


● Identifiers must follow certain rules to be valid in C.

Rules for Identifiers:

1. Must begin with a letter (a-z, A-Z) or underscore (_) character.


2. Can be followed by letters, digits (0-9), or underscore (_) characters.
3. Cannot contain spaces or special characters (except underscore).
4. Cannot be a C keyword.
+ Components of C Language
Identifiers in C
Examples of Valid Identifiers:

● num
● total_amount
● _value
● counter1
● myFunction

Examples of Invalid Identifiers:

● 123num (starts with a digit)


● @value (contains a special character)
● for (is a keyword)
● my variable (contains a space)
● my-variable (contains a hyphen)
+ Components of C Language
Constants in C

1. Constants are fixed values that do not change during program


execution.
2. They are used to represent values that are known and fixed at
compile time.
3. Constants can be of various types, including integer constants,
floating-point constants, character constants, and string
literals.
+ Components of C Language
Constants in C
Types of Constants:

1. Integer Constants: Whole numbers without any fractional part.


● Example: 123, -456, 0, 255
2. Floating-Point Constants: Numbers with a fractional part or in exponential form.
● Example: 3.14, -0.007, 1.23e-5
3. Character Constants: Single characters enclosed in single quotes ('').
● Example: 'A', 'x', '7'
4. String Literals: Sequences of characters enclosed in double quotes ("").
● Example: "Hello, World!", "C programming"

Defining Constants:

● Constants can be defined using the const keyword to declare variables with fixed values.
● Example: const int MAX_VALUE = 100;
+ Components of C Language
Variables in C
● Variables are named memory locations used to store data
during program execution.
● They provide a way to manipulate and process data in a
program.
● Before using a variable, it must be declared with a specific
data type.

Declaration of Variables:

● Syntax: data_type variable_name;


● Example: int age;, float temperature;, char grade;
+ Components of C Language
Variables in C
Initializing Variables:

● Variables can be initialized (assigned an initial value) at the time of


declaration.
● Syntax: data_type variable_name = initial_value;
● Example: int count = 0;, float pi = 3.14;, char letter = 'A';
+ Components of C Language
Data Types in C
● Data types specify the type of data that variables can store.
● C supports various data types, including fundamental types like integers,
floating-point numbers, characters, and derived types like arrays, structures,
and pointers.

Fundamental Data Types:

1. int: Integer data type used to store whole numbers.


2. float: Floating-point data type used to store decimal numbers.
3. double: Double-precision floating-point data type with greater precision than
float.
4. char: Character data type used to store single characters.
5. void: Void data type represents the absence of a type.
+ Components of C Language
Data Types in C
Derived Data Types:

1. Arrays: Collection of elements of the same data type stored in


contiguous memory locations.
2. Structures: User-defined data type that groups together variables
of different data types under one name.
3. Pointers: Variables that store memory addresses of other
variables.
+ Components of C Language
Data Types in C
Size and Range of Data Types:

● The size of each data type depends on the compiler and the
system architecture.
● For example:
● int: Typically 4 bytes on most systems, range from
-2,147,483,648 to 2,147,483,647.
● float: Typically 4 bytes, range from approximately
1.2e-38 to 3.4e38 with 6 decimal places of precision.
● char: Typically 1 byte, representing ASCII characters.
Integrated Development Environment (IDE)
+
❖ provides comprehensive facilities to programmers for software
development
❖ consists of several components such as a source code editor,
build automation tools, and a debugger, all integrated into a
single user interface
❖ Code::Blocks: Code::Blocks is a free, open-source IDE specifically designed for C,
C++, and Fortran development. It is customizable, lightweight, and supports multiple
compilers, making it suitable for beginners and advanced users alike.
❖ Visual Studio Code (VS Code): extensions like C/C++ and C/C++ IntelliSense
❖ Dev-C++: Dev-C++ is a free, open-source IDE for Windows that is tailored for C and
C++ development. It offers a simple interface, integrated debugging, and support for
multiple compilers.
Storage Classes in C
+
❖ Storage classes define the scope, lifetime, and visibility of variables in C
programs.
❖ They play a crucial role in memory management and program optimization

1. auto Storage Class:

● Default storage class for local variables declared inside functions.


● Variables declared as auto are created when the function is called and destroyed when
the function exits.
● Scope is limited to the block in which it is defined.

void function() {

auto int x = 10;

printf("Value of x: %d\n", x);}


Storage Classes in C
+2. extern Storage Class:
● Indicates that a variable or function is defined in another file.
● Allows the use of variables across multiple files in a program.
● Variables declared as extern are not initialized.

// File1.c

int count = 10;

// File2.c

extern int count;


Storage Classes in C
+
3. static Storage Class:

● Preserves the value of a variable between function calls.


● Variables declared as static retain their value even after the function
exits.
● Can also be used to limit the scope of a variable to a particular block.

void function() {

static int num_calls = 0;

num_calls++;

printf("Number of function calls: %d\n", num_calls);

}
Storage Classes in C
+
4. register Storage Class:

● Requests the compiler to store the variable in a CPU register for faster
access.
● Variables declared as register are accessed more quickly than those stored in
memory.
● The use of register is optional, and the compiler may ignore the request.
register int i;
for (i = 0; i < 10; i++) {
// Loop body
}

You might also like