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

C Programming Introduction-1

I need mayombya

Uploaded by

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

C Programming Introduction-1

I need mayombya

Uploaded by

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

St.

Joseph University In
Tanzania (SJUIT)
P. O. Box 11007 Dar es Salaam

Mr. Magere Benard M- BSC, MSc. CS.


PROGRAMMING LANGUAGES
INTRODUCTION TO COMPUTERS

Any programming language is implemented on a computer, all computer


system (irrespective of their shape & size) perform the following 5 basic
operations. It converts the raw input data into information, which is
useful to the users.
✓ Inputting: It is the process of entering data & instructions to the computer
system.
✓ Storing: The data & instructions are stored for either initial or additional
processing, as & when required.
✓ Processing: It requires performing arithmetic or logical operation on the
saved data to convert it into useful information.
✓ Outputting: It is the process of producing the output data to the end user.
✓ Controlling: The above operations have to be directed in a particular
sequence to be completed.
Input Unit: We need to first enter the data & instruction in the computer system, before any
computation begins. This task is accomplished by the input devices. (Eg: keyboard, mouse,
scanner, digital camera etc). This device is responsible for linking the system with the external
environment. The data accepted is in a human readable form. The input device converts it into
a computer readable form.

Storage Unit: The data & instruction that are entered have to be stored in the computer.
Similarly, the end results & the intermediate results also have to be stored somewhere before
being passed to the output unit. The storage unit provides solution to all these issues. This
storage unit is designed to save the initial data, the intermediate result & the final result. This
storage unit has 2 units: Primary storage & Secondary storage.

Central Processing Unit: Together the Control Unit & the Arithmetic Logic Unit are called as
the Central Processing Unit (CPU). The CPU is the brain of the computer. Like in humans, the
major decisions are taken by the brain itself & other body parts function as directed by the
brain. Similarly in a computer system, all the major calculations & comparisons are made
inside the CPU. The CPU is responsible for activating & controlling the operation of other
units of the computer system
Output Unit: The job of an output unit is just the opposite of an input unit. It accepts the
results produced by the computer in coded form. It converts these coded results to human
readable form. Finally, it displays the converted results to the outside world with the help of
output devices ( Eg :monitors, printers, projectors etc..).

Central Processing Unit: Together the Control Unit & the Arithmetic Logic Unit are called as
the Central Processing Unit (CPU). The CPU is the brain of the computer. Like in humans, the
major decisions are taken by the brain itself & other body parts function as directed by the
brain. Similarly in a computer system, all the major calculations & comparisons are made
inside the CPU. The CPU is responsible for activating & controlling the operation of other
units of the computer system

So when we talk about a computer, we actually mean two things:


Hardware- This hardware is responsible for all the physical work of the computer.
Software- This software commands the hardware what to do & how to do it.
This software is further classified as system software & application software

System Software- System software are a set of programs, responsible for running the
computer, controlling various operations of computer systems and management of computer
resources. They act as an interface between the hardware of the computer & the application
software. E.g.: Operating System

Application Software- Application software is a set of programs designed to solve a particular


problem for users. It allows the end user to do something besides simply running the
hardware. E.g.: Web Browser, Gaming Software, etc.
Classification of Computers
Three major categories Based on:
A. Size and capability
B. Working principle and data handling abilities
C. Purpose

A: Size and Capability


i. Supercomputers: Is the most powerful and high-performance type of computer,
designed to process extremely large amounts of data at incredibly high speeds.
Supercomputers consist of thousands (or even millions) of interconnected processors
that work together to solve highly complex computational problems. Working
Scenarios of a Supercomputer: Weather Forecasting and Climate Research, Scientific
Simulations, Nuclear Research, Artificial Intelligence and Machine Learning,
Astrophysics and Space Research.
Classification of Computers
A: Size and Capability

ii. Mainframe Computers: are powerful, large-scale machines designed to handle and
process massive amounts of data and transactions for large organizations. They are known
for their high reliability, scalability, and ability to support hundreds or thousands of users
simultaneously. Are particularly suited for mission-critical applications that require large-
scale data processing, such as in banking, insurance, government, and large enterprises.

Working Scenarios of Mainframe Computers:


Banking and Financial Transactions,
Government Systems and Tax Processing,
Retail and Inventory Management
Insurance Companies,
Airline Reservation Systems,
Classification of Computers
A: Size and Capability
iii. Minicomputers: Are multi-user systems that provide moderate processing power,
filling the gap between personal computers and mainframes. They were widely used in the
past for data processing, scientific research, business applications, and manufacturing
control. Although modern servers have largely replaced them,
Working Scenarios of Minicomputers:
Manufacturing Process Control,
Academic and Research Laboratories,

iv. Microcomputers : Also called Personal Computers, are versatile, single-user systems
designed for individual tasks. They range from desktop PCs and laptops to smartphones
and tablets,
Working Scenarios of Microcomputers:
Education and Learning,
Graphic Design and Video Editing, Gaming,
Scientific Experimentation and Prototyping
Classification of Computers
B. Working principle and data handling abilities
Analog Computers
Analog computers work with continuous data or physical quantities such as voltage,
temperature, speed, or pressure. They measure continuous changes and represent data
using a continuous range of values, rather than discrete steps, Examples: Thermostats,
Speedometers

Digital Computers
work with discrete data, processing information in binary format (0s and 1s). They are
highly accurate and perform tasks by handling discrete signals, performing arithmetic and
logical operations at high speed, Example, Personal Computers (PCs), Digital Watches.

Hybrid Computers
combine the features of both analog and digital computers. They process both continuous
(analog) and discrete (digital) data. These computers convert analog signals to digital form
and vice versa for processing, takes analog signals and transforms them into digital form
before processing them.
Classification of Computers
C. Purpose

General Purpose
General computers are designed to perform various everyday tasks such as;
Document preparation, Financial analysis, Printing documents, Basic Input/Output
functions, Creating databases, Data Saving on a smaller scale, Calculations with
accuracy and consistency.

Special Purpose
When a computer is outlined specifically to perform a certain function, such type of
computer is identified as a Special Purpose computer.
Examples of special-purpose computers

Automatic teller machines (ATM), Traffic-control computers, Surveillance equipment


Weather-forecasting simulators, ticket reservation systems, payroll systems etc
Data are representation inside the computer

Data representation in computer is about how a computer interprets and functions with
different types of information. Different information types require different representation
techniques. For instance, a video will be represented differently than a text document.

A breakdown of how different types of data are represented in a computer:


1. Binary Representation

➢ Bit (Binary Digit): The smallest unit of data in a computer, which can be either a 0 or a 1.
➢ Byte: A group of 8 bits. Commonly, a byte is used to represent a single character in text,
such as a letter or symbol.
➢ Word: A unit of data that typically consists of multiple bytes (e.g., 16-bit, 32-bit, or 64-bit
words). The word size depends on the architecture of the computer and affects how much
data the CPU can process at once.
Data are representation inside the computer
1. Binary Representation
➢ Here's a simplified representation of how bits are grouped:
1 bit = Binary Digit
8 bits = 1 byte
1024 bytes = 1 kilobyte (KB)
1024 KB = 1 megabyte (MB)
1024 MB = 1 gigabyte (GB)
1024 GB = 1 terabyte (TB)

2. Representation of Numbers
Computers represent numbers in binary form using bits. There are several ways to represent
numbers:
Unsigned Integers: Binary Decimal
0000 0
Signed Integers:
0001 1
Floating-point Numbers: 0010 2
0011 3
Data are representation inside the computer
3. Representation of Characters
Characters (letters, digits, symbols) are typically represented using character encoding standards,
where each character is assigned a unique binary code. Common standards is ASCII (American
Standard Code for Information Interchange): Represents 128 characters. For example:
The letter 'A' is represented as 01000001 in binary.
The letter 'a' is represented as 01100001

4. Representation of Images
Images are represented as a collection of pixels, where each pixel has a specific color value. Color
values are typically represented using the RGB (Red, Green, Blue) model, with 8 bits for each
color channel, giving 24 bits per pixel (16.7 million possible colors).
For example:
A white pixel is represented as 11111111 11111111 11111111 (all color channels at full intensity).
A black pixel is represented as 00000000 00000000 00000000 (no intensity).
Images are stored in various formats such as JPEG, PNG, and BMP, which may involve
compression techniques to reduce file size.
Data are representation inside the computer
5. Representation of Sound
Sound is represented as a series of digital samples taken from an analog sound wave. These
samples are converted into binary form, representing the amplitude of the sound at a given
moment.
Common formats include:
WAV(Waveform Audio File Format): Uncompressed audio data.
MP3(MPEG Audio Layer 3): Compressed audio using lossy compression to reduce file size.
A sound sample might be represented as a sequence of 16-bit binary values corresponding to the
amplitude at each point in time.

6. Representation of Video
Video is essentially a sequence of images (frames) displayed in rapid succession, along with
synchronized audio. Each frame is represented as a collection of pixels, just like images, and the
video file may include compressed versions of both image and audio data.
Common video formats include MP4(MP4 stands MPEG-4 part 14), AVI (Audio Video
Interleave)
Data are representation inside the computer
Representation of Instructions
Machine Language: The binary representation of instructions that the CPU can execute directly.
For example, an instruction like "ADD" (to add two numbers) might be represented as a binary
code like 1010 0001 1100.

Assembly Language: A human-readable version of machine language, using mnemonics like


MOV, ADD, and SUB. Assembly language is converted into machine language for execution by
the CPU.

Summary
Numbers: Represented as binary integers or floating-point values.
Characters: Represented using encoding standards like ASCII or Unicode.
Images: Represented as pixel grids, with color information stored in binary.
Sound: Represented as digital samples of sound waves.
Video: Represented as sequences of image frames along with audio.
Instructions: Represented in binary as machine code for the CPU to execute.
INTRODUCTION TO PROGRAMMING

A language that is acceptable to a computer system is called a computer language or


programming language and the process of creating a sequence of instructions in such a language
is called programming or coding.
A program is a set of instructions, written to perform a specific task by the computer. A set of
large program is called software. To develop software, one must have knowledge of a
programming language

Languages are a means of communication. Normally people interact with each other through a
language. On the same pattern, communication with computers is carried out through a language.
This language is understood both by the user and the machine. Just as every language like
Swahili, English has its own grammatical rules; every computer language is also bounded by rules
known as syntax of that language. The user is bound by that syntax while communicating with the
computer system
INTRODUCTION TO PROGRAMMING

Classifications of computer languages:


Low Level Language: The term low level highlights the fact that it is closer to a language which
the machine understands

The low level languages are classified as:

• Machine Language: This is the language (in the form of 0’s and 1’s, called binary numbers)
understood directly by the computer. It is machine dependent. It is difficult to learn and even
more difficult to write programs.
• Assembly Language: This is the language where the machine codes comprising of 0’sand 1’s
are substituted by symbolic codes (called mnemonics) to improve their understanding. It is the
first step to improve programming structure. Assembly language programming is simpler and
less time consuming than machine level programming, it is easier to locate and correct errors in
assembly language than in machine language programs.
INTRODUCTION TO PROGRAMMING

Classifications of computer languages:


High Level Language: Low level language requires extensive knowledge of the hardware since it
is machine dependent. To overcome this limitation, high level language has been evolved which
uses normal English, which is easy to understand to solve any problem. High level languages are
computer independent and programming becomes quite easy and simple. Various high level
languages are given below:

• Procedural Languages: Focus on a sequence of instructions. Examples: C, Fortran, Pascal.


Object-Oriented Languages: Organize code into objects, making it modular and reusable.
Examples: Java, C++, Python.
• Scripting Languages: Often used for automating tasks and building web applications.
Examples: JavaScript, Python, PHP.
• Functional Languages: These focus on mathematical functions. Examples: Haskell, Lisp
Popular Programming Languages:
✓ C: A foundational language known for its performance and close interaction with hardware.
✓ Java: Object-oriented, widely used for cross-platform applications and Android development.
✓ Python: Known for simplicity and readability, widely used in web development, AI, and
scientific computing.
✓ JavaScript: Dominates web development for both client-side and server-side applications.
✓ C++: An extension of C that supports object-oriented programming, used in system/software
development, and games.

Key Concepts in Programming


➢ Syntax: The set of rules that defines how programs are written in a language. Incorrect syntax
leads to errors.
➢ Semantics: The meaning of the syntax—what the instructions do when executed.
➢ Variables: Named storage locations that hold data, which can be changed during program
execution.
➢ Control Structures: Constructs like loops (for, while) and conditionals (if, switch) that control
the flow of the program.
➢ Functions/Methods: Reusable blocks of code that perform a specific task.
Programming Language Translators:
Assembler: The software that reads a program written in assembly
language and translates it into an equivalent program in machine
language is called as assembler
Compiler: The software that reads a program written in high level
language and translates it into an equivalent program in machine
language is called as compiler. The program written by the programmer
in high level language is called source program and the program
generated by the compiler after translation is called as object program
Interpreter: These are executed line-by-line.
Linker: A linker or link editor is a computer program that takes one or
more object files generated by a compiler and combines them into a
single executable file, library file, or another object file
Programming Language Translators:
Assembler: The software that reads a program written in assembly
language and translates it into an equivalent program in machine
language is called as assembler
Compiler: The software that reads a program written in high level
language and translates it into an equivalent program in machine
language is called as compiler. The program written by the programmer
in high level language is called source program and the program
generated by the compiler after translation is called as object program
Interpreter: These are executed line-by-line.
Linker: A linker or link editor is a computer program that takes one or
more object files generated by a compiler and combines them into a
single executable file, library file, or another object file
Problem-Solving
What is problem-solving?
Is a process of understanding the problem, finding solution for the
problem, and finally implementing the solution to it.

A successful problem-solving process depends on the following factors:

I. Understanding the problem.


II. Designing proper algorithms and flowcharts.
III. Implementing the algorithm.
Program Algorithm & Flow Chart

A typical programming task can be divided into two phases:

1. Problem solving phase. Produce an ordered sequence of steps that


describe solution of problem
2. Implementation phase. Implement the program in some programming
language
Program Algorithm & Flow Chart

What is Algorithm?

An algorithm is a procedure or set of rules that defines how a program is to be executed. Or a


step-by-step procedure or a set of rules for solving a problem in a finite number of steps. It is a
blueprint for writing a program. The algorithm outlines how the data will be processed to achieve
the desired result.

Algorithm has the following characteristics :

Input: An algorithm may or may not require input


Output: Each algorithm is expected to produce at least one result
Definiteness: Each instruction must be clear and unambiguous.
Finiteness: If the instructions of an algorithm are executed, the algorithm should terminate after
finite number of steps
Program Algorithm & flow chart

How to write algorithms


1. Define your algorithms input: Many algorithms take in data to be processed, e.g. to calculate
the area of rectangle input may be the rectangle height and rectangle width.
2. Define the variables: Algorithm's variables allow you to use it for more than one place. We
can define two variables for rectangle height and rectangle width as HEIGHT and WIDTH (or
H & W). We should use meaningful variable name e.g. instead of using H & W use HEIGHT
and WIDTH as variable name.
3. Outline the algorithm's operations: Use input variable for computation purpose, e.g. to find
area of rectangle multiply the HEIGHT and WIDTH variable and store the value in new
variable (say) AREA. An algorithm's operations can take the form of multiple steps and even
branch, depending on the value of the input variables.
4. Output the results of your algorithm's operations: In case of area of rectangle output will be
the value stored in variable AREA. if the input variables described a rectangle with a
HEIGHT of 2 and a WIDTH of 3, the algorithm would output the value of 6.
Flow chart
Meaning:
• Is a graphical representation of steps of processes in chronological
order. It is basically a diagrammatic representation of an algorithm.
• By seeing a flow chart one can know the operations performed and the
sequence of these operations in a system.
Flow chart
Flow chart
Example:
1. Write an algorithm and draw a flowchart that will read the two sides of a rectangle and
calculate its area.
2. Flowchart to find the greatest from 2 numbers.
Introduction & History of C
• The C programming language is one of the most influential and widely used programming
languages in computer science and software engineering. Developed in the early 1970s by
Dennis Ritchie at Bell Labs (AT&T)
• Is a general-purpose language that has been a cornerstone in the world of computer science and
software development.
• History
i. Origins (1969-1973): C was created as an enhancement to the B language, which itself
was influenced by BCPL. Dennis Ritchie wanted to develop a language that could be used
to write the Unix operating system, providing low-level access to memory and system
resources.
ii. Standardization (1980s): The American National Standards Institute (ANSI) established
a standard for C in 1989, known as ANSI C. This version ensured consistency across
different platforms and compilers.
iii. Legacy and Impact: C's syntax and concepts have influenced many other languages,
including C++, Java, and C#. Its efficiency and control over system resources have made it
the go-to language for operating systems, embedded systems, and performance-critical
applications.
Introduction & History of C

Why C programming?

✓ It is one of the most popular programming languages in the world,

✓ If you know C, you will have no problem learning other popular programming languages
such as Java, Python, C++, C#, etc, as the syntax is similar,

✓ C is very fast, compared to other programming languages, like Java and Python,

✓ C is very versatile; it can be used in both applications and technologies


Features and structure of C program

1. Simplicity: C is a straightforward language with clean syntax. It doesn't have a lot of built-in
features, which makes it easy to learn.
2. Portability: C programs can be run on different machines with little to no modification,
making it highly portable.
3. Efficiency: C is known for its efficiency, allowing developers to write programs that execute
quickly.
4. Rich Library: The standard C library provides numerous built-in functions for performing
common tasks.
5. Extensibility: You can add your own functions to the C library to extend the capabilities of the
language.
6. Structured Language: C supports structured programming with its clean structure and
modularity.
7. Memory Management: C provides dynamic memory allocation, allowing programs to handle
memory efficiently.
8. Fast Execution: Since C is a compiled language and provides low-level access to system
resources, C programs are generally fast and efficient in terms of execution speed.
Features and structure of C program

9. Procedure-Oriented: C follows a procedural programming approach, where the focus is on


functions and the sequence of actions to be performed rather than data. This approach makes
C ideal for writing system software and applications.

10. Extendable: C can be extended by creating libraries and linking them to other C programs.
This feature allows developers to build upon the existing codebase, adding new functionalities
without starting from scratch.
Structure of a C Program

A typical C program consists of the following sections:


1. Preprocessor Directives: Preprocessor directives are commands given to the
C preprocessor, a tool that processes the source code before it is compiled.
For example, #include <stdio.h> includes the standard input-output library,
enabling the use of functions like printf(). #define is used to define macros or
constants, which can be used throughout the program.
2. Global Variable Declarations: Variables declared outside any function are
global variables, accessible from any function within the program. They are
used when data needs to be shared across multiple functions.
3. Main Function: The execution of a C program starts with the main function.
This is the starting point of every C program. It contains the code to be
executed when the program runs.
4. Local Variable Declarations: Variables declared within a function are local
to that function and cannot be accessed outside of it. They are created when
the function is called and destroyed when it exits
Structure of a C Program

5. Executable Expressions & Statements: These are the lines of code that
perform the operations of the program. Statements are the executable
instructions in a C program, such as assignments, conditional statements,
loops, and function calls. Expressions perform computations, evaluations, and
logical operations, often involving operators like +, -, *, /, and &&.

6. Comments: Comments are added to improve code readability and explain


parts of the code. They are ignored by the compiler and can be single-line
comments (//) or multi-line comments (/* ... */).

7. Return Statement: Indicates the end of the main function. In the main()
function, a return statement is used to indicate the program’s exit status.
Typically, return 0; indicates that the program has executed successfully.
Structure of a C Program
Example C Program.
#include <stdio.h> // Preprocessor Command
int main() // Main Function
{
int num1, num2, sum; // Variable Declarations
// Executable Statements
printf("Enter two integers: ");
scanf("%d %d", &num1, &num2);
sum = num1 + num2;
printf("Sum: %d\n", sum);
return 0; // Return Statement
}
This program takes two integers as input, calculates their sum, and provide the
result
Diagrammatic representation of C program execution process
The execution process of a C program involves several stages, from writing the
code to running the executable.

Source Code This is the initial file written by the programmer, typically saved with a .c
(.c file) extension. It contains the program's code in C language syntax.
The compiler translates the preprocessed code into assembly language,
Compilation generating an assembly file.(It checks for syntax errors and converts
high-level C code into a lower-level language.)
Preprocessor The preprocessor takes the source code and handles directives, like
(Expanded #include and #define, expanding macros and including the contents of any
source code) header files.
The compiler translates the preprocessed code into assembly language,
Compilation generating an assembly file.(It checks for syntax errors and converts
high-level C code into a lower-level language.)
Compiler
(Assembly
Code)
Diagrammatic representation of C program execution process
Compiler
(Assembly
Code)

Assembly

Assembler The assembler takes the assembly code and converts it into machine code,
(Object producing an object file (.o or .obj file).(This object file contains machine-
Code) readable code but may not be executable yet)

Linking

Linker The linker combines all object files, as well as libraries and external
(Executable functions, into a single executable file.(It resolves function calls and
File) variable references, connecting any necessary code from libraries.)
Diagrammatic representation of C program execution process

Linker
(Executable
File)

The operating system loads the executable file into memory for execution
Loading (This is where the operating system allocates memory and sets up the
runtime environment)

Execution
The CPU executes the instructions in the executable file, starting from the
(Program is main function.
Run)
C Programming Language Concepts
Character Set
C uses a set of characters for writing programs:
1. Letters: A-Z and a-z
2. Digits: 0-9
3. Special Characters: + - * / = % & ^ ! ~ | . , ; ' " : ? # _
4. Whitespace Characters: space, tab, newline, etc.

Tokens

Tokens are the smallest elements of a program that are meaningful to the compiler.
They include:
1. Keywords: Reserved words with special meanings (e.g., int, return, if).
2. Identifiers: Names given to variables, functions, arrays, etc. (e.g., age,
calculateSum).
3. Constants: Fixed values that do not change during program execution (e.g., 10,
3.14, 'A’).
4. Operators: Symbols representing operations (e.g., +, -, *, &&).
5. Punctuators (Separators): Characters that separate statements (e.g., {}, [], ;, ,).
C Programming Language Concepts
Constants

Constants are values that do not change during the execution of a program.
Types of constants include::
1. Integer Constants: Whole numbers without decimal points (e.g., 10, -25)

2. Floating-Point Constants: Numbers with decimal points (e.g., 3.14, -0.75,


2.5e3 for scientific notation).Character Constants: A single character
enclosed in single quotes (e.g., 'A', '9', '%’).

3. String Constants: A sequence of characters enclosed in double quotes


(e.g., "Hello World!").

4. Enumeration Constants: Defined using the enum keyword, they represent


integral constants.
C Programming Language Concepts
Keywords
Keywords are reserved words in C that have special meanings and cannot be used
as identifiers
Examples: int, return, if, else, while, for, char, void, etc.
Variables and
Identifiers
Variables: Named storage locations in memory that hold data values which can be
modified during program execution. Variable names are identifiers.
Identifiers: are names given to various program elements such as variables,
functions, and arrays Or Names used to identify variables, functions, arrays, etc.
Identifiers in C must have the following rules:
✓ Names can contain letters, digits and underscores
✓ Names must begin with a letter or an underscore (_)
✓ Names are case-sensitive (firstNum and firstnum are different identifies)
✓ Names cannot contain whitespaces or special characters like !, #, %, etc.
✓ Reserved words (such as int, float, while) cannot be used as names.
C Programming Language Concepts
Variables and
Identifiers
Syntax and declaration of a variable:
datatype variable_list;
Before using a variable, you need to declare it. The declaration specifies the data
type of the variable and its name.
For example:
int age; // Declaration of an integer variable named 'age'
float height; // Declaration of a floating-point variable named 'height'
char grade; // Declaration of a character variable named 'grade'
Initialization of a variable:
Initialization means assigning an initial value to the variable. After declaration, you
can optionally initialize a variable with a specific value.
For example:
int age = 18; // Initialization of 'age' with the value 18
float height = 7.5; // Initialization of 'height' with the value 7.5
char grade = 'B'; // Initialization of 'grade' with the character 'B'
C Programming Language Concepts
Data Types &
Storage
• Data Types define the type and size of data that can be stored in
variables.
• Whenever we define a variable or use any data in the C programming, we
have to specify the type of the data, so that the compiler knows what type
of data to expect.

Types Data Types


Basic Data Type int, char, float, double

Derived Data Type array, pointer, structure, union

Enumeration Data Type Enum

Void Data Type Void


C Programming Language Concepts
Data Types &
Storage
Basic Data Types:

A. Integer Data Type: Integer data type is used to store whole


numbers (positive or negative).
Range : -2,147,483,648 to 2,147,483,647
Size : 4 bytes
Format Specifier : %d

Syntax of Integer
We use int keyword to declare the integer variable: int var_name;

Example
int number;
C Programming Language Concepts
Data Types &
Storage
B. Double Data Type:
Double-precision floating-point data type is used for larger decimal
numbers and provides more precision than float.
Range : 1.7E-308 to 1.7E+308
Size : 8 bytes
Format Specifier : %lf

Syntax of Double
The variable can be declared as double precision floating point using the
double keyword:

double var_name;
Example
double bigSize = 123456.79;
C Programming Language Concepts
Data Types &
Storage
C. Character Data Type:
Character data type is used to store a single character.
Range : (-128 to 127) or (0 to 255)
Size : 1 byte
Format Specifier : %c

Syntax of char
The char keyword is used to declare the variable of character type:

char var_name;
Example
char grade = 'A';
C Programming Language Concepts
Data Types &
Storage
E. Bool:
Boolean data type is used to represent true or false values (0 or 1).

Example:
bool a = true;
C Programming Language Concepts
Data Types &
Storage
Derived Data Type

❖ These data types give programmers the ability to handle heterogeneous


data, directly modify memory, and build complicated data structures.
❖ C also supports derived data types, including arrays, pointers, structures,
and unions.

1) Arrays: Arrays allow you to store multiple values of the same data type
in a contiguous memory block.

Example
int numbers[5] = {1, 2, 3, 4, 5};
C Programming Language Concepts
Data Types &
Storage
Derived Data Type
2) Pointers:
Pointers store the memory address of a variable.
They allow dynamic memory allocation and manipulation.

Example:
int *ptr = &number;
3) Structures:
Structures allow you to group variables of different data types under
a single name.
Example
struct Person {
char name[20]; int age;
};
C Programming Language Concepts
Data Types &
Storage
Derived Data Type
4) Unions: Unions are similar to structures, but they share the same
memory location for all their members.

Example
union Value {
int intValue;
float floatValue;
};
C Programming Language Concepts
Data Types &
Storage
Derived Data Type
5) Enumeration Data Type
✓ A set of named constants or enumerators that represent a collection of
connected values
✓ Enumeration allows you to define a set of named integer constants.
✓ It’s declared using enum keyword
✓ Example
enum Days {Monday, Tuesday, Wednesday, Thursday, Friday, Saturday,
Sunday};

6) Void Data Type


The void data type is used to indicate that a function does not return any
value.
C Programming Language Concepts
Data Type Qualifiers
in C Programming
• Data type qualifiers are keywords in C that are used to modify the
behavior of data types.
• They provide additional information about how the compiler should treat
the variable or data being declared.
• These qualifiers gives you more control over variable declarations and their
behavior.
Types of Data Type Qualifiers
1. const (Constant)
2. Volatile
3. Restrict
4. Type Size Qualifiers (signed, unsigned, short, and long)
const (Constant) C Programming Language Concepts
• The const qualifier is used to declare variables whose values cannot be
changed after initialization.
• Once a const variable is assigned a value, it becomes read-only.
• (Use case) Prevent accidental modification of critical values like
mathematical constants (PI) or configuration parameters.
• Example
const int max = 100; // max is a constant and cannot be modified.
Volatile
•The volatile qualifier tells the compiler that a variable's value may be
changed unexpectedly by external factors such as hardware
•This prevents the compiler from optimizing the code in a way that assumes
the variable's value will not change unexpectedly.
•(Use case) Variables shared between an interrupt service routine (ISR) and
main code.
•Example
volatile int sensorValue;// sensorValue might be updated by hardware.
C Programming Language Concepts
Restrict
• The restrict qualifier is used with pointers to indicate that the object
pointed to by the pointer is accessed only through that pointer (or a copy of
it) during the lifetime of the pointer.
• Tells the compiler to distinct memory, non-overlapping memory regions.
• (Use case) Optimizing performance in functions where pointers do not
overlap.
• Example
void process(int *restrict a, int *restrict b) {
*a = *a + 10;
*b = *b + 20;
}
C Programming Language Concepts
Type Size Qualifiers
• Signed:
By default, integer types in C are signed, meaning they can represent
both positive and negative values. The signed keyword explicitly declares
that an integer type can store negative values.
Example:
signed int a = -17; // Can store negative, zero, and positive values

• Unsigned:
The unsigned keyword modifies an integer type to only represent non-
negative values (0 and positive numbers). This effectively doubles the
range of positive values it can represent compared to its signed
counterpart.
Example:
unsigned int b = 10; // Can only store zero and positive values
C Programming Language Concepts
Type Size Qualifiers
• Short:
The short keyword specifies a shorter version of an integer, which
typically uses less storage and has a smaller range compared to the
standard int type.
Example:
short int c = 32123; // Range is typically -32,768 to 32,767

• Long:
The long keyword specifies a longer version of an integer, which typically
uses more storage and has a larger range compared to the standard int
type.
Example:
long int d = 1000000L;
Larger range of integer
C Programming Language Concepts
Type Size Qualifiers
(Summary)

Type Typical Range

signed int -2,147,483,648 to 2,147,483,647

unsigned int 0 to 4,294,967,295

short int -32,768 to 32,767

long int -2,147,483,648 to 2,147,483,647 (or larger)


C Operators
• Operators are symbols that perform operations on variables and values.
• Types of Operators in C:
1) Arithmetic operators
2) Assignment operators
3) Comparison operators
4) Logical operators
5) Bitwise operators
6) Conditional (Ternary) Operator
Arithmetic operators are used to perform common mathematical
Arithmetic Operators operations
Operator Description Example Result
+ Addition a+b Sum of a and b
- Subtraction a-b Difference of a and b
* Multiplication a*b Product of a and b
/ Division a/b Quotient of a divided by b
% Modulus (Remainder) a%b Remainder when a is divided by b
++ Increment a++ Increases the value of a variable by 1
-- Decrement a-- Decreases the value of a variable by 1
C Operators
Example: Basic Arithmetic Operators
#include <stdio.h>
int main() {
int a = 17, b = 3, result;
// addition
result = a+b;
printf("Addition of a & b = %d \n",result);
// subtraction
result = a-b;
printf("Subtraction of a & b = %d \n",result);
// multiplication
result = a*b;
printf("Multiplication of a & b = %d \n",result);
// division
result = a/b;
printf("Division of a & b = %d \n",result);
// Using Modulus operator
result = a%b;
printf("result = %d",result);
return 0;
}
C Operators
These operators assign values to variables, often combining other
Assignment operators operations with the assignment.

Operator Description Example Equivalent To

= Assignment a=b Assigns b to a

+= Add and assign a += b a=a+b

-= Subtract and assign a -= b a=a-b

*= Multiply and assign a *= b a=a*b

/= Divide and assign a /= b a=a/b

%= Modulus and assign a %= b a=a%b


C Operators
• Operators are symbols that perform operations on variables and values.
• Types of Operators in C:
1) Arithmetic operators
2) Assignment operators
3) Comparison operators
4) Logical operators
5) Bitwise operators
6) Conditional (Ternary) Operator
Arithmetic operators are used to perform common mathematical
Assignment operators operations
Operator Description Example Result
+ Addition a+b Sum of a and b
- Subtraction a-b Difference of a and b
* Multiplication a*b Product of a and b
/ Division a/b Quotient of a divided by b
% Modulus (Remainder) a%b Remainder when a is divided by b
THANK YOU
Welcome to SJUIT
Where Your Dreams Are Nurtured
Mr. Magere Benard M.

You might also like