0% found this document useful (0 votes)
15 views

1st unit c program notes

C programming language pdf

Uploaded by

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

1st unit c program notes

C programming language pdf

Uploaded by

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

C Programming

Unit 1
Basics of Programming

▪ Definition and Characteristics of Computer


▪ Block diagram of Computer
▪ Compiler, Interpreter
▪ Linker
▪ Loader
▪ Algorithm
▪ Flowchart
▪ Testing and Excmon Examples of flow charts and algorithms Largest of three number
▪ reversing the digits of an integer
▪ GCD of two integers
▪ generating prime numbers
▪ computing nth Fibonacci number
▪ finding Even and Odd numbers Programming

▪ Tokens: Keywords, Identifiers, Constants, Variables, Data types, defining symbolic commands, Simple Programs
C Programming
✓ Definition and Characteristics of Computer

Definition:
A computer is an electronic device that can perform various operations on data, such as input, processing, storage, and output, based on a
set of instructions provided by a program.

Characteristics of Computer
▪ Processing Power
▪ Storage
▪ Input Devices
▪ Output Devices
▪ Memory (RAM)
▪ Central Processing Unit (CPU)
▪ Operating System
▪ Connectivity
▪ Software
▪ Automation
▪ Versatility
C Programming

▪ Processing Power: Computers are capable of performing complex calculations and executing tasks at high speeds. The processing power of a computer is
often measured in terms of the number of instructions it can execute per second (IPS) or in gigahertz (GHz).

▪ Storage: Computers can store vast amounts of data in different types of storage devices, such as hard drives, solid-state drives, and memory (RAM). Storage
capacity is typically measured in gigabytes (GB) or terabytes (TB).

▪ Input Devices: Computers accept input from various devices, including keyboards, mice, touchscreens, and sensors. Input devices allow users to interact with
the computer by providing data and commands.

▪ Output Devices: Computers produce output in the form of text, graphics, audio, and video. Common output devices include monitors, printers, speakers,
and headphones.

▪ Memory (RAM): Random Access Memory (RAM) is a type of volatile memory that the computer uses to temporarily store data and actively running
programs. It allows for quick access to information but is cleared when the computer is powered off.

▪ Central Processing Unit (CPU): The CPU is often considered the "brain" of the computer. It executes instructions from programs, performs calculations, and
manages data flow between different components.

▪ Operating System: Computers use an operating system (OS) to manage hardware resources, run applications, and provide a user interface. Common
operating systems include Windows, macOS, and Linux.

▪ Connectivity: Computers can be connected to networks, enabling communication and data exchange between multiple devices. This connectivity is crucial
for tasks such as internet browsing, file sharing, and communication.
C Programming

▪ Software: Computers run software, which includes operating systems, applications, and utility programs. Software provides the instructions that the computer
follows to perform specific tasks.

▪ Automation: Computers are capable of automating repetitive tasks through programming and scripting. This characteristic enhances efficiency and reduces the
need for manual intervention in many processes.

▪ Versatility: Computers can be used for a wide range of applications, from word processing and gaming to scientific simulations and complex calculations.

✓ Block diagram of Computer


C Programming
There are basically three important components of a computer:
1.Input Unit
2.Central Processing Unit(CPU)
3.Output Unit

1. Input Unit:

The input unit consists of input devices that are attached to the computer. These devices take input and convert it into binary language that the
computer understands. Some of the common input devices are keyboard, mouse, joystick, scanner etc.

▪ The Input Unit is formed by attaching one or more input devices to a computer.
▪ A user input data and instructions through input devices such as a keyboard, mouse, etc.
▪ The input unit is used to provide data to the processor for further processing.

2. Central Processing Unit:

▪ Once the information is entered into the computer by the input device, the processor processes it.
▪ The CPU is called the brain of the computer because it is the control central of the computer.
▪ It first fetches instructions from memory and then interprets them so as to know what is to be done.
▪ If required, data is fetched from memory or input device.
▪ Thereafter CPU executes or performs the required computation, and then either stores the output or displays it on the output device.
▪ The CPU has three main components, which are responsible for different functions: Arithmetic Logic Unit (ALU), Control Unit (CU) and Memory registers
C Programming

A. Arithmetic and Logic Unit (ALU):


The ALU, as its name suggests performs mathematical calculations and takes logical decisions. Arithmetic calculations include addition, subtraction,
multiplication and division. Logical decisions involve the comparison of two data items to see which one is larger or smaller or equal.

▪ Arithmetic Logical Unit is the main component of the CPU


▪ It is the fundamental building block of the CPU.
▪ Arithmetic and Logical Unit is a digital circuit that is used to perform arithmetic and logical operations.

B. Control Unit:
The Control unit coordinates and controls the data flow in and out of the CPU, and also controls all the operations of ALU, memory registers and also
input/output units. It is also responsible for carrying out all the instructions stored in the program. It decodes the fetched instruction, interprets it and sends
control signals to input/output devices until the required operation is done properly by ALU and memory.

▪ The Control Unit is a component of the central processing unit of a computer that directs the operation of the processor.
▪ It instructs the computer’s memory, arithmetic and logic unit, and input and output devices on how to respond to the processor’s instructions.
▪ In order to execute the instructions, the components of a computer receive signals from the control unit.
▪ It is also called the central nervous system or brain of the computer.
C Programming
C. Memory Registers:

A register is a temporary unit of memory in the CPU. These are used to store the data, which is directly used by the processor. Registers can be
of different sizes(16 bit, 32 bit, 64 bit and so on) and each register inside the CPU has a specific function, like storing data, storing an instruction, storing
address of a location in memory etc. The user registers can be used by an assembly language programmer for storing operands, intermediate results etc.
Accumulator (ACC) is the main register in the ALU and contains one of the operands of an operation to be performed in the ALU.
Memory attached to the CPU is used for the storage of data and instructions, and is called internal memory The internal memory is divided into
many storage locations, each of which can store data or instructions. Each memory location is of the same size and has an address. With the help of the
address, the computer can read any memory location easily without having to search the entire memory. When a program is executed, its data is copied to the
internal memory and stored in the memory till the end of the execution. The internal memory is also called the Primary memory or Main memory. This
memory is also called RAM, i.e., Random Access Memory. The time of access of data is independent of its location in memory, therefore, this memory is also
called Random Access memory (RAM).

▪ Memory Unit is the primary storage of the computer.


▪ It stores both data and instructions.
▪ Data and instructions are stored permanently in this unit so that they are available whenever required.

3. Output Unit :

The output unit consists of output devices that are attached to the computer. It converts the binary data coming from the CPU to human
understandable form. The common output devices are monitor, printer, plotter, etc.

▪ The output unit displays or prints the processed data in a user-friendly format.
▪ The output unit is formed by attaching the output devices of a computer.
▪ The output unit accepts the information from the CPU and displays it in a user-readable form.
C Programming
✓ Compiler, interpreter
The Compiler and Interpreter, both have similar works to perform. Interpreters and Compilers convert the Source Code (HLL) to Machine
Code (understandable by Computer). In general, computer programs exist in High-Level Language that a human being can easily understand. But
computers cannot understand the same high-level language, so for computers, we have to convert them into machine language and make them readable
for computers. In this article, we are going to see the differences between them.

Compiler

The Compiler is a translator which takes input i.e., High-Level Language, and produces an output of low-level language i.e. machine or assembly
language. The work of a Compiler is to transform the codes written in the programming language into machine code (format of 0s and 1s) so that
computers can understand.

▪ A compiler is more intelligent than an assembler it checks all kinds of limits, ranges, errors, etc.
▪ But its program run time is more and occupies a larger part of memory. It has a slow speed because a compiler goes through the entire program and
then translates the entire program into machine codes.

Role of a Compiler

For Converting the code written in a high-level language into machine-level language so that computers can easily understand, we use a compiler.
Converts basically convert high-level language to intermediate assembly language by a compiler and then assembled into machine code by an
assembler.
C Programming

Advantages of Compiler

▪ Compiled code runs faster in comparison to Interpreted code.


▪ Compilers help in improving the security of Applications.
▪ As Compilers give Debugging tools, which help in fixing errors easily.

Disadvantages of Compiler

▪ The compiler can catch only syntax errors and some semantic errors.
▪ Compilation can take more time in the case of bulky code.

Interpreter:
An Interpreter is a program that translates a programming language into a comprehensible language. The interpreter converts high-level language
to an intermediate language. It contains pre-compiled code, source code, etc.

▪ It translates only one statement of the program at a time.


▪ Interpreters, more often than not are smaller than compilers.

Role of an Interpreter

The simple role of an interpreter is to translate the material into a target language. An Interpreter works line by line on a code. It also converts high-level
language to machine language.
C Programming

Advantages of Interpreter

▪ Programs written in an Interpreted language are easier to debug.


▪ Interpreters allow the management of memory automatically, which reduces memory error risks.
▪ Interpreted Language is more flexible than a Compiled language.

Disadvantages of Interpreter

▪ The interpreter can run only the corresponding Interpreted program.


▪ Interpreted code runs slower in comparison to Compiled code.
C Programming

Difference Between Compiler and Interpreter


Compiler Interpreter

Steps of Programming:
▪ Program Creation. Steps of Programming:
▪ Analysis of language by the compiler and throws errors in case of any incorrect statement. ▪ Program Creation.
▪ In case of no error, the Compiler converts the source code to Machine Code. ▪ Linking of files or generation of Machine Code is not required by Interpreter.
▪ Linking of various code files into a runnable program. ▪ Execution of source statements one by one.
▪ Finally runs a Program.

The compiler saves the Machine Language in form of Machine Code on disks. The Interpreter does not save the Machine Language.

Compiled codes run faster than Interpreter. Interpreted codes run slower than Compiler.

Linking-Loading Model is the basic working model of the Compiler. The Interpretation Model is the basic working model of the Interpreter.

The compiler generates an output in the form of (.exe). The interpreter does not generate any output.

Any change in the source program during the translation does not require retranslation of the
Any change in the source program after the compilation requires recompiling the entire code.
entire code.

Errors are displayed in Compiler after Compiling together at the current time. Errors are displayed in every single line.

It does not require source code for later execution. It requires source code for later execution.

Execution of the program takes place only after the whole program is compiled. Execution of the program happens after every line is checked or evaluated.

Compilers more often take a large amount of time for analyzing the source code. In comparison, Interpreters take less time for analyzing the source code.

CPU utilization is more in the case of a Compiler. CPU utilization is less in the case of a Interpreter.

The use of Compilers mostly happens in Production Environment. The use of Interpreters is mostly in Programming and Development Environments.

Object code is permanently saved for future use. No object code is saved for future use.

C, C++, C#, etc are programming languages that are compiler-based. Python, Ruby, Perl, SNOBOL, MATLAB, etc are programming languages that are interpreter-based.
C Programming

✓ Linker
▪ Linker is a program in a system which helps to link object modules of a program into a single object file.
▪ It performs the process of linking. Linkers are also called as link editors.
▪ Linking is a process of collecting and maintaining piece of code and data into a single file.
▪ Linker also links a particular module into system library.
▪ It takes object modules from assembler as input and forms an executable file as output for the loader.
▪ Linking is performed at both compile time, when the source code is translated into machine code and load time, when the program is loaded into
memory by the loader.
▪ Linking is performed at the last step in compiling a program.
C Programming

Linking is of two types:

1. Static Linking
2. Dynamic linking

1. Static Linking :
It is performed during the compilation of source program. Linking is performed before execution in static linking. It takes collection of
relocatable object file and command-line arguments and generates a fully linked object file that can be loaded and run.

2. Dynamic linking :
Dynamic linking is performed during the run time. This linking is accomplished by placing the name of a shareable library in the executable
image. There are more chances of errors and failures. It require less memory space as multiple programs can share a single copy of the library.

Advantages of Linker

1) Code Reuse
2) Smaller Executable Files
3) Reduced Memory Footprint
4) Reduced Disk Space
5) Improved Security
6) Easier to Update Libraries
7) Portability
C Programming

Disadvantages of Linker

1) Complexity
2) Symbol resolution
3) Compatibility issues
4) Performance
5) Security
6) Dependency management

Applications of Linker

1) Combining object files


2) Resolving symbol references
3) Dynamic linking
4) Library management
5) Modularity

✓ Loader Algorithm

The loader is the program of the operating system which loads the executable from the disk into the primary memory(RAM) for execution. It
allocates the memory space to the executable module in the main memory and then transfers control to the beginning instruction of the program.

The loader is an important part of the system, as it loads the program, places them in the memory, and prepares them for the final execution.
Loading a program includes reading the content of the executable file that has program instructions from the memory, then it performs some other preparatory
task to execute the task.
C Programming

✓ Algorithm

The word Algorithm means “ A set of finite rules or instructions to be followed in calculations or other problem-solving operations ”
Or
A procedure for solving a mathematical problem in a finite number of steps that frequently involves recursive operations.

Use of the Algorithms:

Algorithms play a crucial role in various fields and have many applications. Some of the key areas where algorithms are used include:

▪ Computer Science
▪ Mathematics
▪ Operations Research
▪ Artificial Intelligence
▪ Data Science
C Programming
What is the need for algorithms?

1. Algorithms are necessary for solving complex problems efficiently and effectively.
2. They help to automate processes and make them more reliable, faster, and easier to perform.
3. Algorithms also enable computers to perform tasks that would be difficult or impossible for humans to do manually.
4. They are used in various fields such as mathematics, computer science, engineering, finance, and many others to optimize processes, analyze data,
make predictions, and provide solutions to problems.

What are the Characteristics of an Algorithm?


C Programming

✓ Flowchart
Flowchart is a graphical representation of an algorithm. Programmers often use it as a program-planning tool to solve a problem. It makes
use of symbols which are connected among them to indicate the flow of information and processing.
The process of drawing a flowchart for an algorithm is known as “flowcharting”.

Basic Symbols used in Flowchart Designs

1.Terminal:
The oval symbol indicates Start, Stop and Halt in a program’s logic flow. A pause/halt is generally used in a program logic under some error
conditions. Terminal is the first and last symbols in the flowchart.

2.Input/Output:
A parallelogram denotes any function of input/output type. Program instructions that take input from input devices and display output on
output devices are indicated with parallelogram in a flowchart.
C Programming
3. Processing:
A box represents arithmetic instructions. All arithmetic processes such as adding, subtracting, multiplication and division are indicated by action or
process symbol.

4. Decision Diamond symbol represents a decision point. Decision based operations such as yes/no question or true/false are indicated by diamond in flowchart.

5. Connectors:
Whenever flowchart becomes complex or it spreads over more than one page, it is useful to use connectors to avoid any confusions. It is
represented by a circle.

6.Flow lines:
Flow lines indicate the exact sequence in which instructions are executed. Arrows represent the direction of flow of control and relationship
among different symbols of flowchart.
C Programming

Rules For Creating Flowchart :

A flowchart is a graphical representation of an algorithm.it should follow some rules while creating a flowchart
Rule 1: Flowchart opening statement must be ‘start’ keyword.
Rule 2: Flowchart ending statement must be ‘end’ keyword.
Rule 3: All symbols in the flowchart must be connected with an arrow line.
Rule 4: The decision symbol in the flowchart is associated with the arrow line.

Advantages of Flowchart:
Disadvantages of Flowchart:
▪ Flowcharts are a better way of communicating the logic of the system.
▪ Flowcharts act as a guide for blueprint during program designed. ▪ It is difficult to draw flowcharts for large and complex programs.
▪ Flowcharts help in debugging process. ▪ There is no standard to determine the amount of detail.
▪ With the help of flowcharts programs can be easily analyzed. ▪ Difficult to reproduce the flowcharts.
▪ It provides better documentation. ▪ It is very difficult to modify the Flowchart.
▪ Flowcharts serve as a good proper documentation. ▪ Making a flowchart is costly.
▪ Easy to trace errors in the software. ▪ Some developer thinks that it is waste of time.
▪ Easy to understand. ▪ It makes software processes low.
▪ It helps to provide correct logic. ▪ If changes are done in software, then the flowchart must be redrawn
C Programming

Examples of flow charts and algorithms Largest of three number


flow charts
Algorithms

Step 1: Start
Step 2: Ask the user to enter three integer values.
Step 3: Read the three integer values in num1, num2, and num3 (integer variables).
Step 4: Check if num1 is greater than num2.
Step 5: if true, then check if num1 is greater than num3.
If true, then print ‘num1’ as the greatest number.
If false, then print ‘num3’ as the greatest number.
Step 6: If false, then check if num2 is greater than num3.
If true, then print ‘num2’ as the greatest number.
If false, then print ‘num3’ as the greatest number.
Step 7: Stop
C Programming
✓ reversing the digits of an integer

Algorithms

Step 1: Start
Step 2: Initialize rev_num = 0
Step 3: Loop while num > 0
Step 4: Multiply rev_num by 10 and add remainder of num
Step 5: divide by 10 to rev_num rev_num = rev_num*10 + num%10;
Step 6: Divide num by 10
Step 7: Return rev_num
C Programming

✓ GCD of two integers Start

Algorithms Declare variable n1, flow charts


n2, gcd=1, i=1
Step 1: Start
Step 2: Declare variable n1, n2, gcd=1, i=1
Step 3: Input n1 and n2
Input n1 and n2
Step 4: Repeat until i<=n1 and i<=n2
If n1%i==0 && n2%i==0:
gcd = i true
If n1%i==0 &&
false
Step 5: Print gcd i<=n1 and i<=n2
n2%i==0:
Step 6: Stop
true

false gcd = i

i= i +1

Print gcd

Stop
C Programming

✓ generating prime numbers

Algorithms

step 1: start
step 2: Accept a number] read n
step 3: set 1-2
step 4: Repeat steps Sand 6 until i < n
step 5: check whether n is divisible or not] if no than Goto step?
Goto stop6
step 6: set i=i+1
step 7: if in then Print "number is prime"
Print "number is not prime"
step 8: stop
C Programming
✓ computing nth Fibonacci number

Algorithms flow charts

Step 1: START
Step 2: Declare variable n1, n2, sum, n, i
Step 2: Initialize variables: n1 = 0, n2 = 1, i = 2
Step 3: Read n
Step 4: Repeat this step until i <= n:
sum = n1 + n2
print sum
n1 = n2
n2 = sum
i=i+1
Step 5: STOP
C Programming

✓ Finding Even and Odd numbers Programming

Algorithms flow charts


flow charts

Step 1: Start
Step 2: [ Take Input ] Read: Number
Step 3: Check: If Number%2 == 0 Then
Print : N is an Even Number.
Else
Print : N is an Odd Number.
Step 4: Exit
C Programming

✓ Tokens: Keywords, Identifiers, Constants, Variables, Data types, defining symbolic commands, Simple Programs

The tokens of C language can be classified into six types based on the functions they are used to perform. The types of C tokens are as follows:

1) Keywords
2) Identifiers
3) Constants
4) Strings
5) Special Symbols
6) Operators
C Programming

Keywords :

▪ The keywords are pre-defined or reserved words in a programming language.


▪ Each keyword is meant to perform a specific function in a program.
▪ Since keywords are referred names for a compiler, they can’t be used as variable names because by doing so, we are trying to assign a new
meaning to the keyword which is not allowed.
▪ You cannot redefine keywords.
▪ However, you can specify the text to be substituted for keywords before compilation by using C preprocessor directives.
▪ C language supports 32 keywords which are given below:

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
C Programming

Identifiers :

▪ Identifiers are used as the general terminology for the naming of variables, functions, and arrays.
▪ These are user-defined names consisting of an arbitrarily long sequence of letters and digits with either a letter or the underscore(_) as a first character.
▪ Identifier names must differ in spelling and case from any keywords.
▪ You cannot use keywords as identifiers; they are reserved for special use.
▪ Once declared, you can use the identifier in later program statements to refer to the associated value.
▪ A special identifier called a statement label can be used in goto statements.

Rules for Naming Identifiers :

Certain rules should be followed while naming c identifiers which are as follows:

▪ They must begin with a letter or underscore(_).


▪ They must consist of only letters, digits, or underscore. No other special character is allowed.
▪ It should not be a keyword.
▪ It must not contain white space.
▪ It should be up to 31 characters long as only the first 31 characters are significant.

Note: Identifiers are case-sensitive so names like variable and Variable will be treated as different.
For example,

▪ main: method name.


▪ a: variable name.
C Programming

Constants :

▪ The constants refer to the variables with fixed values.


▪ They are like normal variables but with the difference that their values can not be modified in the program once they are defined.
▪ Constants may belong to any of the data types.

Examples of Constants in C

const int c_var = 20; const int* const ptr = &c_var;

Strings :

▪ Strings are nothing but an array of characters ended with a null character (‘\0’).
▪ This null character indicates the end of the string.
▪ Strings are always enclosed in double quotes.
▪ Whereas, a character is enclosed in single quotes in C and C++.

Examples of String

char string[20] = {‘b’, ’c’, ‘a’, ‘e’, ‘x’, ‘p’, ‘e’, ‘r’, ‘t’, ‘\0’};
char string[20] = “bcaexpert”;
char string [] = “bcaexpert”;
C Programming
Special Symbols:

The following special symbols are used in C having some special meaning and thus, cannot be used for some other purpose. Some of these are listed below:

▪ Brackets[] : Opening and closing brackets are used as array element references. These indicate single and multidimensional subscripts.

▪ Parentheses() : These special symbols are used to indicate function calls and function parameters.

▪ Braces{} : These opening and ending curly braces mark the start and end of a block of code containing more than one executable statement.

▪ Comma (, ) : It is used to separate more than one statement like for separating parameters in function calls.

▪ Colon(:) : It is an operator that essentially invokes something called an initialization list.

▪ Semicolon(;) : It is known as a statement terminator. It indicates the end of one logical entity. That’s why each individual statement must be ended
with a semicolon.

▪ Asterisk (*) : It is used to create a pointer variable and for the multiplication of variables.

▪ Assignment operator(=) : It is used to assign values and for logical operation validation.

▪ Pre-processor (#) : The preprocessor is a macro processor that is used automatically by the compiler to transform your program before actual compilation.

▪ Period (.) : Used to access members of a structure or union.

▪ Tilde(~) : Used as a destructor to free some space from memory.


C Programming

Operators :

▪ Operators are symbols that trigger an action when applied to C variables and other objects. The data items on which operators act are called operands.
▪ Depending on the number of operands that an operator can act upon, operators can be classified as follows:

• Unary Operators: Those operators that require only a single operand to act upon are known as unary operators.
For Example increment and decrement operators

• Binary Operators: Those operators that require two operands to act upon are called binary operators. Binary operators can further are classified into:
• Arithmetic operators
• Relational Operators
• Logical Operators
• Assignment Operators
• Bitwise Operator

• Ternary Operator: The operator that requires three operands to act upon is called the ternary operator.
Conditional Operator(?) is also called the ternary operator.
C Programming

✓ Data Types in C

▪ Each variable in C has an associated data type. It specifies the type of data that the variable can store like integer, character, floating, double, etc.
▪ Each data type requires different amounts of memory and has some specific operations which can be performed over it.
▪ The data type is a collection of data with values having fixed values, meaning as well as its characteristics.

The data types in C can be classified as follows:

Types Description

Primitive data types are the most basic data types that are used for
Primitive Data Types
representing simple values such as integers, float, characters, etc.

User Defined Data Types The user-defined data types are defined by the user himself.

The data types that are derived from the primitive or built-in datatypes are
Derived Types
referred to as Derived Data Types.
C Programming

Primitive Data Types

Data Type Size Description


Format Specifier

int 2 or 4 bytes %d or %i Stores whole numbers, without decimals

Stores fractional numbers, containing one or more decimals. Sufficient


float 4 bytes %f
for storing 6-7 decimal digits

Stores fractional numbers, containing one or more decimals. Sufficient


double 8 bytes %lf
for storing 15 decimal digits

char 1 bytes %c Stores a single character/letter/number, or ASCII values


C Programming

Thank you !

You might also like