0% found this document useful (0 votes)
15 views90 pages

Unit 1.1 C Notes by Prof. Shahid Masood

Uploaded by

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

Unit 1.1 C Notes by Prof. Shahid Masood

Uploaded by

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

CABSMJ1001 [2024-25]

CABSMJ-1001
Problem Solving Using C
Unit - I
CABSMJ1001 [2024-25]

Syllabus Consists of Four Units


I. Concept of Algorithms, Flow Charts, Overview of the Compiler,
Assembler, Linker and Loader, History of C, Features of C, Structure of
C program, Simple Hello World Program in C, Commonly Used Header
Files, Overview of Compilation, Linking and Execution Process, Pre-
processor Directive, C Character Set, Identifiers and Keywords,
Constants and Variables, C Data Types, Library Functions, Input/Output
Statements, Scope of Variables, const Keyword, C Operators: Arithmetic
Operators.
II. Relational Operators, Logical Operators, Assignment Operators,
Increment and Decrement Operators, Ternary Operator, Bitwise
Operators, Comma and sizeof Operators, Precedence of Operators,
Typecasting, Mathematical Library Functions, Decision Making and
Branching: if Statement, if - else Statement, if –else if ... else Statement,
Switch-case Statement, goto Statement and Label, Iteration/Loop
Statements: For Loop, While Loop, Do While Loop, Nested Loop,
Continue and Break Statements, typedef Statement and enum datatype.
CABSMJ1001 [2024-25]

III. Array and Structures: Declaration, Concept of One Dimensional and


Multi-Dimensional Arrays, 2-D Arrays used in Matrix Computation, Array
as Function Argument, Character Arrays and Strings, String
Declaration, 2D Character Arrays, Defining Structure, Declaration of
Structure Variable, Accessing Structure Members, Nesting of
Structures, Array of Structures, Defining Union, Declaration of Union
Variable, Functions: User Defined and Library Functions, Prototype of
Function, Call by Value, Call by Reference, Structure as Function
Argument, Functions Returning Structure, Pointers, Use of Pointers
with Arrays, Structures and Functions.
IV. Recursion, Command Line Arguments, Storage Classes – Auto, Extern,
Static, Register, Features of Storage Classes, Dynamic Memory
Allocation, Creating 1D and 2D Dynamic Arrays, Altering the size of an
Allocated Memory Block, File Handling: Library Functions for File
Handling, File Opening Modes, Declaring File Pointer, Creating, Reading
and Writing to Files, C Preprocessor: Macro Substitution Directives, File
Inclusion Directive, Compiler Control Directives.
CABSMJ1001 [2024-25]

Text Book

Title: Programming in ANSI C


Author: E. Balagurusamy
Publisher: McGraw Hill Education
Pvt. Ltd.
CABSMJ1001 [2024-25]

Concept of Algorithm
and
Flowchart
Algorithm toCABSMJ1001 [2024-25]
add two numbers
1. write "Enter two numbers"
Algorithm 2. read a, b
3. sum  a + b
4. write "Sum = ",sum
 is a finite sequence of instructions 5. end
for solving a problem or accomplishing a task.
 It transforms input into desired output.
 Examples:
1. Algorithm to add two numbers
2. Algorithm to find sum and average of n numbers
3. Algorithm to check whether a given integer is odd or even.

 Algorithm:
 is independent of any prog. language/machine/compiler
 can be translated into a computer program using any
programming language
 can be implemented on any machine.
CABSMJ1001 [2024-25]

Characteristics of Algorithm

Every algorithm must possess following characteristics:

1. Definiteness
2. Effectiveness
3. Finiteness
4. Input
5. Output
CABSMJ1001 [2024-25]

1. Definiteness
clear and accurate

 Each step of the algorithm must be precise and unambiguous

 Therefore, instructions like:

1. add 10 or 20 to total
X
2. divide 10 by 0

must not be used.


CABSMJ1001 [2024-25]

2. Effectiveness

 Each step – must be sufficiently basic and realizable such that:


 it can in principle be carried out exactly in a finite time
 by a person using paper & pencil.
CABSMJ1001 [2024-25]

3. Finiteness

 Algorithm must always terminate - after a finite number of


steps.

1. write "Enter a number"


2. read a
3. write a Infinite no. of
4. add 1 to a operations
5. go to step 3
6. end

Does above algorithm possess finiteness property? No


CABSMJ1001 [2024-25]

4. Input

 Algorithm accepts zero/more inputs (supplied externally)


which is transformed into desired output.

5. Output

 Algorithm must produce at least one result.


CABSMJ1001 [2024-25]

Algorithm
 Can be expressed in 3 ways:

1.Natural • Simple and easy way to express an algorithm


language • Popular choice – can convey the steps to a wide
such as audience
English • Tends to be verbose and ambiguous
2.Pseudo
code
• Graphical representation of an algorithm
• Uses a collection of connected geometric
3.Flowchart
shapes and arrows to show flow of operations
• Avoids most issues of ambiguity
CABSMJ1001 [2024-25]

1. Algorithm (in Natural Language)

Algorithm For Adding Two Numbers Algorithm

1. write "Enter two numbers" Program


2. read first number in a and second number in b
3. add a with b and store the result in sum Compile
4. write "Sum of two given numbers = ",sum
5. end Run
CABSMJ1001 [2024-25]

2. Pseudocode
 is a structured way of describing algorithms – using a
combination of:
 programming language constructs and
 informal English sentences.

 It closely resembles the structure of a program code because


it allows to include control structures ( if-then-else, switch-
case, while, do-while, for loop etc.).

 But it doesn’t use the syntax of a specific prog. language.

 It is preferred notation for describing algorithms because:


 it can be better read & understood and
 it is easier to translate into program code.
CABSMJ1001 [2024-25]

Algorithm in Pseudocode Form


Algorithm to read 3 numbers and find their sum and average:

Algorithm Note:
1. write "Enter three numbers" 1. Each step has a
2. read a, b, c sequence number.
Comments
3. compute sum and average 2. Comments can be
4. sum  a + b + c included
5. avg  sum/3.0 compute average 3. Operations:
6. output result +, -, *, /, ^, %
7. write "Sum=",sum, " Average=",avg
<, >, =, <=, >=, !=
8. end
and, or, not
4. No particular agreement
on the syntax used
CABSMJ1001 [2024-25]

Constants and Variables


Constants
 are fixed values that cannot be changed during the program
execution. Constants Variable

 Example: area  2 * 3.14 * radius

Different types of Constants


Integer constants Whole numbers e.g. -350, 0, 2023
Real (Floating point) Values with a decimal point Scientific notation
constants e.g. 1846.75, -256.8, 1.49E-1, 8.495E+3
represent a single character enclosed in ' '
Character constants
e.g. 'A' , '9', '$'
a collection of characters enclosed in " "
String constants
e.g. "INDIA", "Jan 26, 2024", "9"
CABSMJ1001 [2024-25]
m1 m2
Variable 60 70

 is a name given to a memory location that is used to hold a


value.
 Value of the variable can be changed during the execution of
the program.
 It has a data type and a unique name, e.g.
int m1=60, m2=70; m1 m2
m2 = (m1+m2)/2; /*value of m2 changed */ 60 65

 Variable names used in algorithms:


 may consist of letters, digits and underscore (_) character.
 must begin with a letter or underscore (_) character.
CABSMJ1001 [2024-25]

Algorithm in Pseudocode Form


Algorithm to print numbers from 1 to 10:
Takes no input
Algorithm Output
1. n  1 1
2. if n <= 10 then 2
3. write n 3
4. n  n + 1 4
5. go to 2 5
6. end if denotes end of if structure 6
7
7. end
8
9
10
CABSMJ1001 [2024-25]

Algorithm in Pseudocode form


Algorithm to read 5 numbers and print their sum:

Algorithm Output
1. sum  0 Enter number-1
2. count  1 10
3. if count <= 5 then Enter number-2
4. write "Enter number-",count 20
5. read n Enter number-3
6. sum  sum + n 30
7. count  count + 1 Enter number-4
8. go to 3 40
9. end if Enter number-5
10. write "Sum of 5 numbers = ",sum 50
11. end Sum of 5 numbers = 150
CABSMJ1001 [2024-25]

3. Flowchart

 is a graphical (diagrammatical)
representation of an algorithm.

 It shows the steps as boxes of various kinds, and their


execution order by connecting the boxes with arrows.

 Different geometric shapes (symbols) are used - to represent


different operations.

 Since a flowchart is a pictorial representation of an


algorithm, it makes it easier to interpret and understand the
algorithm.
CABSMJ1001 [2024-25]

Flowchart Shapes (Symbols)


Symbol Operation

start Start or Stop

Input or Output

Assignment or Processing

F T Decision
Cond?

Direction of flow
CABSMJ1001 [2024-25]

Flowcharting Shapes (Symbols)


On page connector (connects parts of the flowchart
A
continued on the same page. Flow continues where a
matching symbol is found)

P2 Off page connector (connects parts of the flowchart


continued to other pages)

Document or Report

Beginning of For Loop, e.g. for i  1 to n

Invoking/calling a pre-defined process, e.g. fn1()

comment
Dotted line should extend to the symbol it
references
CABSMJ1001 [2024-25]

How to
use
on-page
connector

Both parts of the Flowchart


are on the same page
CABSMJ1001 [2024-25]

Advantages of Flowchart

1. Makes it easier to understand the logic of a program

2. Helpful in explaining the logic to others (users of program)

3. Enables easier, faster and error-free program coding

4. Helpful in debugging

5. Helpful in program modification


CABSMJ1001 [2024-25]

Flowchart to read 3 numbers and find their sum and average:

start

write "Enter 3 numbers"


read a, b, c
Output
Enter 3 numbers
sum = a+b+c 10 20 30
avg = sum/3.0
Sum=60 Average=20.0

write "Sum=",sum," Average=",avg

stop
CABSMJ1001 [2024-25]

Flowchart to print numbers from 1 to 10:

start

n=1 Output
1
F 2
is n<=10 ?
3
4
T
5
write n
6
7
n=n+1 8
9
10
stop
CABSMJ1001 [2024-25]

Flowchart to read 5 numbers and print their sum:


start Output
Enter number-1
10
sum = 0
Enter number-2
count = 1
20
Enter number-3
is F 30
COUNT<=5 ? Enter number-4
40
T Enter number-5
write "Enter number-",count 50
read n Sum of 5 numbers = 150
sum = sum + n
count = count + 1 write "Sum of 5
numbers = ",sum

stop
CABSMJ1001 [2024-25]

Computer Program,
System S/w and
Application S/w ?
CABSMJ1001 [2024-25]

Computer Program (or Program)


 It is a sequence of instructions written using a programming
language to perform a specified task by the computer.
 For example, C program to find biggest among n numbers, Java
program to find sum of n numbers etc.
 Whatever a computer does, is done by executing a program.
 Program instructions (written using a prog. lang.):
 are first translated into machine code
 which can be understood & executed by the CPU.

 Computer program instructions are also called program source


code and
 Computer programming is also called program coding.
CABSMJ1001 [2024-25]

System Software
 It is a set of programs that is designed:
 to control & manage the operations of a computer's
hardware, and
 to provide a platform for running other softwares.

 It is commonly developed by the computer manufacturers.


 Examples are:
 Operating systems (DOS, MS Windows, Linux, Apple’s MacOS)
 Device drivers (controls a specific h/w device attached to computer)
 Computer language translators (Assemblers, Compilers,
Interpreters etc.)
 Antivirus softwares (to detect, remove and prevent viruses)
 Utility programs (Disk formatting tool, File management tool,
Disk clean up tool etc.)
CABSMJ1001 [2024-25]

Application Software
 It is a set of programs used to accomplish specific tasks for
which they are designed for.
 It simplifies an operation and helps users get their tasks done
effortlessly.
 Examples:
 Word-processing software (create and print documents)
 Spreadsheet software (numeric data-analysis tool)
 Real-time online communication s/w (Skype, Google Meet, Zoom)
 Database s/w (manage a collection of related data, e.g. MS Access, Oracle)
 Graphics s/w (create drawings, edit pictures e.g. MS Paint, Photoshop)
 Multimedia s/w (like VLC Media player, Windows Media Player etc).

 It is installed according to the user’s requirement.


CABSMJ1001 [2024-25]

Difference between System s/w and Application s/w


Enables the computer Usage Enables users to perform some
to function properly specific task efficiently, such as
letters, presentations, accounting etc.
Compulsory – Each Need Optional – depends on usage and
computer must have a needs. Without an application s/w,
system s/w to function the computer is still able to function.
Provides the Function Provides the environment to enable
environment for the users to accomplish specific tasks
application s/w to run e.g. using word to create documents
Each computer needs Number Each computer can have more than
only one system s/w (OS) of s/w one application s/w
Independent – system Depen- Dependent – application s/w can’t
s/w functions without dency work without system s/w
an application s/w
CABSMJ1001 [2024-25]

Programming
Languages
CABSMJ1001 [2024-25]

Programming Language

 A programming language:
 is a computer language used to write programs to be
executed by the computer to perform a specified task.
 has a set of rules (syntax) and structure for writing the
code (program instructions) in that prog. language.

 Three types of programming languages:


1. Machine language Low-level
Programming languages
2. Assembly language (close to hardware)
3. High-level language
CABSMJ1001 [2024-25]

1. Machine Language

 Native language (made up of binary digits) of the computer.


 It is directly understood & executed by the computer.
 Both data and instructions are represented as binary numbers
(strings of 1’s and 0’s).
 Each computer has its own set of machine lang. instructions
which are based on its architecture.
 It is machine dependent, precise knowledge of architecture of
the computer is required to write the programs.
 Typical machine language instruction format is given in the fig:
 Opcode: specifies operation to be performed. in
 Operand: specifies where to find/store data in memory. binary
CABSMJ1001 [2024-25]

Machine Language
It is extremely difficult for programmers to
understand machine language instructions.
Example of machine language instructions:
To add the two numbers stored at memory
locations 1471 and 2041, and storing the result at 3456:
Machine language instructions
( opcode + operand ) Operation to be performed
Clear & store into Accumulator
001000000000001100111001 register - the number stored at 1471
Add to the contents of Accumulator
001100000000010000100001 - the number stored at 2041
Store the contents of Accumulator
011000000000011100101110 - at memory location 3456
CABSMJ1001 [2024-25]
Symbolic name Memory location
2. Assembly Language FRST 0000001100111001
SCND 0000010000100001
RSLT 0000011100101110
 Since machine lang. uses binary numbers which are extremely
difficult for humans to decipher, hence assembly language is
developed to make programming a bit easier for humans.
 In assembly language programming:
 Mnemonic codes are used to specify opcodes (operations
to be performed). Opcodes usually consist of three letters
e.g. ADD, SUB, MUL, DIV, MOV, END etc.
 Symbolic names are used to specify operands (memory
locations) e.g. FRST, SCND, RSLT, A, B, C etc.
 Mnemonic codes & symbolic names are easier to remember &
use in writing programs.
 It is machine dependent, so precise knowledge of architecture
of the computer is required to write the programs.
CABSMJ1001 [2024-25]

Assembly Language
Example:
Assembly language instructions to add two
numbers FRST and SCND stored in the memory
and store the result in RSLT.
Assembly
language Operation Equivalent machine code
instruction
Clear & store FRST into
CLA FRST Accumulator 001000000000001100111001
Add SCND to the
ADD SCND contents of Accumulator 001100000000010000100001
Store the contents of
STA RSLT Accumulator in RSLT 011000000000011100101110

An Assembler is required to translate an A.L.code into machine code.


CABSMJ1001 [2024-25]

Assembler

 Since an assembly language program:


 cannot be directly interpreted & executed by the CPU,
 hence first it is translated into machine language code
using a language translator, called assembler.

 An assembler is a system s/w and a language translator that:


 reads & interprets an assembly language program, and
 converts it into machine language code that can be
directly understood & executed by the CPU.
CABSMJ1001 [2024-25]

3. High-Level Languages
 are designed to overcome the following limitations of low-
level prog. languages:
 machine dependent
 knowledge of hardware of the machine is required
 difficult to program.

 are independent of the computer's hardware architecture.

 enable to write programs that are almost independent of a


particular type of computer.

 are closer to English language. So, they are easier to


understand and easier to program.
CABSMJ1001 [2024-25]

High-Level Languages

 Program statements are written using:


 English words and
 mathematical symbols and expressions.

 HLLs are machine independent, easier to learn & program.

 HLLs also offer development tools, such as libraries containing


built-in functions (sqrt(), pow(), ceil(), floor(), abs() sin(), cos() etc.)

 Examples: FORTRAN, COBOL, C, C++, C#, Java, Python, PHP etc.

A compiler or interpreter is required to translate a high-level


language code into machine code.
CABSMJ1001 [2024-25]

Compiler and Its


Working

 A compiler is a system s/w and a language translator that:


 reads & interprets a high-level language program and
 translates it into machine language code that can be
directly understood & executed by the CPU.
 If any errors are encountered in the program, then the
errors are reported.

HLLs like FORTRAN, COBOL, C, C++, C#, Java etc. use compilers.
CABSMJ1001 [2024-25]

Interpreter

 Like a compiler, an interpreter is also a language translator


that translates a HLL program into machine code.

 However, there are differences in how they work.


Compiler Interpreter
It reads the entire program It translates the program
and converts it as a whole one statement at a time and
into machine code. executes it.
An executable file is Executable file is not
generated. generated.
Progname.exe (Windows)
Progname.out (Unix)
CABSMJ1001 [2024-25]

Working of
Interpreter

 An interpreter:
 reads a statement from the source code, converts it into
machine code and executes it,
 then it takes the next statement in sequence and repeats
the above process until an error is encountered or all the
statements are executed.
 If an error occurs, the interpreter stops execution and reports
the error.

High-level languages like JavaScript, Python, PHP, Perl, Ruby


etc. use interpreters.
CABSMJ1001 [2024-25]

Overview
Of C
Programming
language
CABSMJ1001 [2024-25]
broadly applicable across a
C Programming Language variety of application domains

 C is a powerful, general-purpose, high-level programming


language.
 It was developed by Dennis Ritchie at AT & T Bell Labs, USA
in 1972 and it is still very popular.
 The main features of C language include bit-level memory
access, dynamic memory management, a simple set of 32
keywords, and a clean style.
 These features make it suitable for developing softwares like:
 Operating systems System s/w
 Compilers & Interpreters (Unix OS, C compiler, Python interpreter
 Device drivers are mostly written in C)
Application s/w
 Databases, Web Browsers & Applications (C is also used in
developing MySQL, Google Chrome
along with some other languages)
CABSMJ1001 [2024-25]

Important Features of C
Feature Description
Structured  C language allows to break a large code
programming into different parts using functions and it
language allows the use of control statements like if-
else, switch-case, while, do-while, for loop.
 Above features make the program easier to
understand and also make debugging,
testing and maintenance of the program easier.
Free-form language  C programming language allows:
 to begin writing the statements
anywhere on a line.
 to have any number of blank spaces
between symbols.
 We also don't need to start a statement on
a new line.
CABSMJ1001 [2024-25]

C Program
 A C program is a sequence of instructions:
 written using the syntax of C prog. language
 to perform a specified task by the computer.

 It consists of one or more functions. Each function performs a


specific task.
 Every C program contains a main() function:
 which is a special type of function
 that defines the starting point of the program where the
execution begins.

Note: C program must be saved with .c file extension, such as


progname.c
CABSMJ1001 [2024-25]

Structure of a C Program: A C program may have 6 sections:


/* Short info about this program */ Documentation section
#include<stdio.h> Link/File inclusion section
#include<math.h>
#define PI 3.14 */ symbolic constant */ Definition section
int add(int,int); */ function prototype */ Global declaration
int x=100; */ global variable */
section
main() Start of program
{ int a=10,b=20; main() function section
printf("%d",add(a,b));
... End of program
}
int add(int p,int q)
{ return p+q; Subprogram section
}
....
CABSMJ1001 [2024-25]

Simple Hello World Program In C


A simple C program:

/* A simple program for printing a message */


/* helloworld.c */
#include<stdio.h>
main()
{
printf("Hello World!"); /* every C statement is terminated by ; */
}
File extension of all
c programs is .c
Note: Save the program as helloworld.c
CABSMJ1001 [2024-25]
/* A simple program for printing a message */
/* helloworld.c */
Description #include<stdio.h>
main()
The first & second line {
/* A simple program for… */ printf("Hello World!");
}
/* helloworld.c */
 These are the comment lines.

 Comments are used in a program to enhance its readability and


understanding.
 Comments are optional. They are generally written at the
beginning of a line or at the end of a C statement.
 Comments are non-executable statements and therefore
anything enclosed between /* and */ is ignored by the compiler.
 Comments do not affect the execution speed and the size of a
compiled program.
CABSMJ1001 [2024-25]
/* A simple program for printing a message */
/* helloworld.c */
Description #include<stdio.h>
main()
{
The third line printf("Hello World!");
}
#include<stdio.h>
 It is a preprocessor directive.

 While compiling the program, #include tells the preprocessor to


read the stdio.h (standard input output header file) and include
its contents at this point in the program file (before compilation).
 stdio.h file contains the info about input & output functions.

 So, to use input & output functions in our program, stdio.h


header file must be included.
 Similarly, to use library functions like - sqrt(), pow(), abs(), exp()
etc., math.h must be included.
/* A simple program for CABSMJ1001 [2024-25]
printing a message */
/* helloworld.c */
Description #include<stdio.h>
main()
The fourth line {
main() printf("Welcome to C");
}
 main() is a special function.
 It tells the computer that execution of the program begins at this line.
 Every C program must have exactly one main() function.
 Different forms of main statement:
 main() When void appears in a function’s parameter list,
 main(void) it indicates that the function takes no parameters.
 void main() When void is used as function’s return type, it
 void main(void) indicates that the function doesn’t return any value.
The fifth line
{
 Left brace indicates the beginning of the main() function.
CABSMJ1001 [2024-25]
/* A simple program for printing a message */
/* helloworld.c */
Description #include<stdio.h> Output
main() Hello World!
{
The sixth line printf("Hello World!");
printf("Welcome to C"); }
 It is predefined standard C library function for printing output.
 It is a prewritten function which gets linked with our program at
the time of linking.
 It will print everything enclosed between the quotation marks on
the stdout (standard output) stream (i.e. computer screen).

The seventh line


}
 It represents the end of the main() function (end of the program).
 Set of statements enclosed within { and } form the function body.
CABSMJ1001 [2024-25]

What are the C Library Functions?


 C Library functions are built-in functions that are grouped
together and placed in a common location called library.
 All library functions are created at the time of designing the
C compiler. These library functions are declared in
respective header files.
 Each library function performs a specific operation e.g.
scanf(), printf(), getchar(), sqrt() functions.
 To use library functions in our program, we need to include
the respective header file(s) in our C program by using
#include<filename.h> directive.
 When the program is compiled, the contents of header files
are included in the C program (by the preprocessor).
CABSMJ1001 [2024-25]

Commonly Used Header Files and the Type of Library


Functions they Contain:
1. <stdio.h> : It is standard I/O header file in which various
Input/output functions are declared.
It is used to perform I/O operations using functions like:

scanf() Reads formatted input from stdin (keyboard).


printf() Sends formatted output to stdout (computer screen).
getchar() Gets a character from stdin. You need to press <Enter> key.
getc() No need to press <Enter> key, char is not displayed.
getche() No need to press <Enter> key, char is displayed.
putchar() Writes the passed character to stdout.
gets() Reads a line from stdin.
puts() Writes a line to stdout.
CABSMJ1001 [2024-25]

Commonly Used Header Files and the Type of Library


Functions they Contain:
2. <ctype.h> : It contains function declarations to test and
manipulate character data:
isalnum(x) Checks whether the character x is alphanumeric.
isalpha(x) Checks whether the character x is alphabetic.
isdigit(x) Checks whether the character x is a digit.
islower(x) Checks whether the character x is a lowercase letter.
isupper(x) Checks whether the character x is an uppercase
letter.
isspace(x) Checks whether passed character x is white-space.
isprint(x) Checks whether the character x is printable.
CABSMJ1001 [2024-25]

Commonly Used Header Files and the Type of Library


Functions they Contain:
3. <string.h> : It is used to perform various operations related
to string manipulation like:

strcpy(s1,s2) Copies string s2 into s1


strcat(s1,s2) Appends string s2 to the end of s1
strcmp(s1,s2) Compares string s1 with s2
strlen(s) Gives no. of characters in the string (excluding \0 char)
strchr(s,c) Searches for the first occurrence of a given
character c in a given string s and returns a pointer.
strncmp(s1,s2,n) Compares first n characters of string s1 with s2.
strncpy(s1,s2,n) Copies first n characters from s1 to s2.
CABSMJ1001 [2024-25]

Commonly Used Header Files and the Type of Library


Functions they Contain:
4. <math.h> : It contains mathematical functions like:
pow(x,y) Computes and returns x raised to the power of y.
sqrt(x) Returns the square root of x.
ceil(x) Returns the smallest integer value  x.
floor(x) Returns the largest integer value  x.
round(x) Returns the nearest integer value to the number x.
x can be int/float/double/long double.
log(x) Returns the natural logarithm (base-e logarithm)
of x.
log10(x) Returns the common logarithm (base-10 logarithm)
of x.
sin(x) Returns the sine of a given radian angle x.
CABSMJ1001 [2024-25]

Commonly Used Header Files and the Type of Library


Functions they Contain:
5. <stdlib.h> : It contains functions for memory allocation,
process control, conversions like:
strtod() Converts a given string to a double type number.
strtoi() Converts a given string to an integer type number.
strtol() Converts a given string to a long integer type
number.
malloc(), Allocates the requested amount of memory at
calloc() runtime and returns a pointer to it.
free() Deallocates the memory previously allocated by a
malloc, calloc or realloc.
exit() Causes the program to terminate normally.
CABSMJ1001 [2024-25]

Saving and
Executing
a C program
CABSMJ1001 [2024-25]

Saving and Executing a C Program


 Windows system doesn’t come with a pre-installed C
compiler or "C IDE" (Integrated Development Environment).
 We need to install a "C IDE" which enables to write, edit,
compile, link and run C programs.
 Here, we are using "Dev-C++ IDE" (to develop C and C++ programs):
CABSMJ1001 [2024-25]

Saving and Executing a C Program

To enter and save a program:


 Click on File -> New -> Source File

 Enter the program


CABSMJ1001 [2024-25]

 Click on File -> Save As (to save the program).


CABSMJ1001 [2024-25]

 In Save As dialog box: Enter the Filename


 In Save as type: Select C source files (*.c)
 Click on Save.
CABSMJ1001 [2024-25]

To execute the program:


 Click on Execute -> Compile & Run.
CABSMJ1001 [2024-25]

Overview of
Compilation & Linking
Process
and
Execution Process of C
Program
CABSMJ1001 [2024-25]

Compilation and Linking Process of C Program


 is performed by the C Compilation System.

 C Compilation System:
 converts the source code into executable code
 that can be directly executed by the system.

 C Compilation System:
 consists of 4 components: a preprocessor, a compiler, an
assembler, a linker and
 performs following 4 steps (to convert C source code into
executable code):
1. Preprocessing,
2. Compiling,
3. Assembling and
4. Linking.
CABSMJ1001 [2024-25]

Compilation and Linking Process of C Program


Source Expanded Object Executable
Preprocessor Compiler Linker
code code code code
hello.c hello.obj hello.exe
Assembly code
Object codes of
Assembler other Library modules
as needed
1. Preprocessor
 C preprocessor component processes the C source code before
it is passed to the compiler.
 It:
 removes all the comments from the source code,
 processes the preprocessor directives (like #define, #include,
#if, #elif, #else, #endif etc.) and takes appropriate actions,
such as macro substitution, inclusion of files, conditional
code compilation etc.
CABSMJ1001 [2024-25]

Compilation and Linking Process of a C Program


Source Expanded Object Executable
Preprocessor Compiler Linker
code code code code
hello.c hello.obj hello.exe
Assembly code
Object codes of
Assembler other Library modules
as needed

 For example, if #include<stdio.h> directive:


 is present in the program,
 then preprocessor replaces this directive with the
contents of the "stdio.h" header file.
 This expanded code (generated by the preprocessor) is passed
to the compiler.
CABSMJ1001 [2024-25]

Compilation and Linking Process of a C Program


Source Expanded Object Executable
Preprocessor Compiler Linker
code code code code
hello.c hello.obj hello.exe
Assembly code
Object codes of
Assembler other Library modules
as needed

2. Compiler
 Compiler:
 translates the expanded code (preprocessed source code)
 into assembly language code.

 This assembly language code is passed to the assembler.


CABSMJ1001 [2024-25]

Compilation and Linking Process of a C Program


Source Expanded Object Executable
Preprocessor Compiler Linker
code code code code
hello.c hello.obj hello.exe
Assembly code
Object codes of
Assembler other Library modules
as needed

3. Assembler
 It translates the assembly language code into object code
(machine language code) and generates an object code file.
 Name of the object code file is similar to that of the source
file, i.e. if source file name is "hello.c":
 then object code file would be "hello.obj" in Windows and
 "hello.o" in Unix.
CABSMJ1001 [2024-25]

Compilation and Linking Process of a C Program


Source Expanded Object Executable
Preprocessor Compiler Linker
code code code code
hello.c hello.obj hello.exe
Assembly code
Object codes of
Assembler other Library modules
as needed
4. Linker
 Linker combines the object code of the program with the
object codes of the library functions used in the program and
creates the executable code file.
 Library functions:
 are used in all the C programs
 are pre-compiled, and their object codes are stored as
library files with ".lib" (or ".a") extension.
CABSMJ1001 [2024-25]

Compilation and Linking Process of a C Program


Source Expanded Object Executable
Preprocessor Compiler Linker
code code code code
hello.c hello.obj hello.exe
Assembly code
Object codes of
Assembler other Library modules
as needed

 For example, if our program contains printf() and scanf() library


functions, then the linker adds the object codes of these
functions in the executable code of our program.
 The output of the linker is the executable code file which can
be directly executed by the CPU.
 If the source file name is "hello.c", then the executable code file
name would be "hello.exe" in Windows and "hello.out" in Unix.
CABSMJ1001 [2024-25]

Executable Executed
Execution Process of code Loader
by the CPU
a C Program hello.exe

 Whenever we give the command to execute a particular


program, the loader:
 loads the executable file in the main memory and
 informs the CPU the starting point of the program in the
memory (i.e. the memory address where this program is
loaded in the memory).
 The CPU then executes the program.

Loader ?
 Loader is a system program (component of OS) which loads
the executable file from the disk into the primary memory
(RAM) for execution.
CABSMJ1001 [2024-25]

C Program to Add Two Numbers

/* Program to add two numbers*/


/* add.c */
#include<stdio.h>
main()
{ int number1 = 30; /*every statement must end with ; */
int number2 = 20;
int sum = number1 + number2;
printf("Sum = %d",sum);
} Output
Sum = 50
CABSMJ1001 [2024-25]

C Character Set
and
C Tokens
CABSMJ1001 [2024-25]

C Character Set

 In C programming language, the character set:


 refers to a set of all the valid characters
 that we can use in the source program for forming words,
expressions, and numbers.

 The C character set contains all the characters that we can use
for the source program text.
CABSMJ1001 [2024-25]

C Character Set
Following characters can be used to form words, numbers and
expressions in C programs:

Letters: Uppercase: A,B,C,D,……..Z


Lowercase: a,b,c,d,…….…z
Digits: 0,1,2,3,4,5,6,7,8,9
Special ,.;:?'"!|/\~_$%&^*-+=<>()[]{}#@
characters: White spaces:
Blank space
Horizontal tab
Vertical tab
New line
Carriage return
Form feed
CABSMJ1001 [2024-25]
Meaning of C Special Characters
Character Meaning Character Meaning
, Comma & Ampersand
. Period ^ Carat
; Semicolon * Asterisk
: Colon - Minus
? Question mark + Plus sign
' Apostrophe < Less than sign
" Quotation mark > Greater than sign
! Exclamation mark ( Left parenthesis
| Vertical bar ) Right parenthesis
/ Slash [ Left bracket
\ Backslash ] Right bracket
~ Tilde { Left brace
_ Underscore } Right brace
$ Dollar sign # Number sign (Hash)
% Percent sign @ At the rate sign
CABSMJ1001 [2024-25]

C Tokens
 In a C program, an atomic unit (smallest indivisible unit) is
known as a C token.
 They are the most basic elements in a program recognized by
the C compiler. It may be a single character or a group of
characters.
 The compiler cannot breakdown the token any further.
 Examples: main
{
(
float
int
sum
"Computer Science"
CABSMJ1001 [2024-25]

Types of C Tokens
 C programs are written using C tokens and the syntax of the
language.
 C has six types of tokens:
Types of C tokens Examples
1. Keywords float, int, double, while, for, switch, case
2. Identifiers rollno, name, age, amount, sum, total
3. Constants 3.14, 2024
4. Strings "New Delhi", "Monday"
5. Special symbols [, ], {, }, (, )
6. Operators +, -, *, /, %
CABSMJ1001 [2024-25]

1. C Keywords
 C Keywords are predefined tokens, also called reserved words.
 They have special meaning to the C compiler.
 They can be used for their intended action only; can’t be used
for any other purpose.
 There are 32 keywords in C:
auto double int struct break
else long switch case enum
register typedef char extern return
union const float short unsigned
continue for signed void default
goto sizeof volatile do if
static while
CABSMJ1001 [2024-25]

2. Identifiers
 refer to the names given to entities, such as variables, pointers
arrays, structures, unions, functions etc.
 are user-defined names consisting of a sequence of letters
(lowercase & uppercase), digits and underscore ( _ ) character.
Rules for identifiers
Must consist of only letters, digits or underscore.
 Must begin with an alphabet or underscore.
 Only first 31 characters are significant.
 Must not contain a white space. Some valid identifiers are:
 It can’t be a keyword. Average, average
 Are case sensitive. height1,
total_height
Note: Uppercase & lowercase letters class_strength
are treated as different characters.
CABSMJ1001 [2024-25]

3. C Constants (or Literals)


 are fixed values that cannot be changed during program
execution.
 C supports several types of constants:
1. Integer are whole numbers.
constants Three types:
Decimal constants: consist of digits 0 through 9,
e.g. 123, -350, 0, 2021
Octal: consist of digits 0 - 7 (with a leading 0),
e.g. 07, 010, 00, 0435
Hexadecimal: consist of digits 0 - 9, alphabets A - F
(preceded by 0X or 0x),
e.g. 0xA, 0x9B, 0x, 0xcbd
CABSMJ1001 [2024-25]

C Constants 1492.4 (in


decimal notation)

2. Floating point are values with a decimal point, e.g.


constants 1846.75, -256.0, .72, 1.4924E+3
or
Real constants
3. Character a single character enclosed within single
constants quote marks, e.g.
'A', '9', '$', ' '
4. String a sequence of characters enclosed inside
constants double quotes, e.g.
"Hello World", "Jan 26, 2023", "9"

Contd...
CABSMJ1001 [2024-25]
5. Backslash  These constants are used in output functions,
character e.g. '\n' stands for newline character.
constants
 Each constant represents a single character
(or Escape (although they consist of two characters):
sequences)
'\a' audible alert (beep sound)
'\b' backspace
'\f' form feed
'\n' new line
'\r' carriage return
'\t' horizontal tab
'\v' vertical tab
'\'' apostrophe (single quote)
'\"' double quote
'\\' backslash
'\?' question mark
'\0' null
CABSMJ1001 [2024-25]

Example: To illustrate the Use of Escape Sequences


 To put quotes within quotes - use the escape sequence \"
 For example, to print "Hello":
 C statement would be: printf("\"Hello\""); /* output: "Hello" */
 and not: printf(""Hello""); /* Error */
/* escseq1.c */
#include<stdio.h>
main()
{ printf("He came to me");
printf("\n");
printf("and said \"Hello!\" to me.");
printf("\a"); /* produces a beep sound */
}
CABSMJ1001 [2024-25]
marks1
Variables in C 60
RAM
 A variable is a unique name assigned to a data value in memory.
 Values of variables can be changed during program execution.
 Variable name should be chosen in a meaningful way so as to
reflect its function.
Variable name is an identifier. So rules for variable
Rules for variable name name are same as that of rules for identifier.
 Must consist of only letters, digits or underscore ( _ ).
 Must begin with an alphabet or underscore.
 Only first 31 characters are significant.
 Must not contain a white space. Some valid variable names:
 It can’t be a keyword. Average, average
 Are case sensitive. height1
total_height
class_strength
CABSMJ1001 [2024-25]

Variables in C
 Which of the following variable names are valid and which are
invalid?
Variable name Valid/invalid
first_tag Valid
char Invalid
price$ Invalid
group one Invalid
avg_number1 Valid
int_type Valid
(area) Invalid
25th Invalid

You might also like