0% found this document useful (0 votes)
13 views20 pages

BCP Basic Notes

Bcp

Uploaded by

jitendra626331
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)
13 views20 pages

BCP Basic Notes

Bcp

Uploaded by

jitendra626331
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/ 20

BASIC COMPUTER PROGRAMMING - ANUBHAV CHOUBEY

MODULE-I COMPUTER HARDWARE

BLOCK DIAGRAM OF COMPUTER:

HARDWARE,SOFTWARES,FIRMWARES:
Hardware is a collective term used to describe any of the physical components of an analog or digital
computer. The term hardware distinguishes the tangible aspects of a computing device from software,
which consists of written, machine-readable instructions or programs that tell physical components what
to do and when to execute the instructions.
EX: Internal Hardwares: CPU,Motherboard, Heat sink,etc.
External Hardware: Monitor,Mouse,Keyboard,etc.

Software is a set of instructions, data or programs used to operate computers and execute specific
tasks. It is the opposite of hardware, which describes the physical aspects of a computer. Software is a
generic term used to refer to applications, scripts and programs that run on a device. It can be thought of
as the variable part of a computer, while hardware is the invariable part.

Firmware is a specific class of computer software that provides the low-level control for a device's
specific hardware. Firmware, such as the BIOS of a personal computer, may contain basic functions of a
device, and may provide hardware abstraction services to higher-level software such as operating
systems. For less complex devices, firmware may act as the device's complete operating system,
performing all control, monitoring and data manipulation functions. Typical examples of devices
containing firmware are embedded systems (running embedded software), home and personal-use
appliances, computers, and computer peripherals.

TYPES OF SOFTWARE:
Application software. The most common type of software, application software, is a computer software
package that performs a specific function for a user, or in some cases, for another application. An
application can be self-contained, or it can be a group of programs that run the application for the user.
Examples of modern applications include office suites, graphics software, databases and database
management programs, web browsers, word processors, software development tools, image editors and
communication platforms.

System software. These software programs are designed to run a computer's application programs and
hardware. System software coordinates the activities and functions of the hardware and software. In
addition, it controls the operations of the computer hardware and provides an environment or platform for
all the other types of software to work in. The OS is the best example of system software; it manages all
the other computer programs. Other examples of system software include the firmware, computer
language translators and system utilities.

Driver software. Also known as device drivers, this software is often considered a type of system
software. Device drivers control the devices and peripherals connected to a computer, enabling them to
perform their specific tasks. Every device that is connected to a computer needs at least one device
driver to function. Examples include software that comes with any nonstandard hardware, including
special game controllers, as well as the software that enables standard hardware, such as USB storage
devices, keyboards, headphones and printers

Middleware. The term middleware describes software that mediates between application and system
software or between two different kinds of application software. For example, middleware enables
Microsoft Windows to talk to Excel and Word. It is also used to send a remote work request from an
application in a computer that has one kind of OS, to an application in a computer with a different OS. It
also enables newer applications to work with legacy ones.

Programming software. Computer programmers use programming software to write code.


Programming software and programming tools enable developers to develop, write, test and debug other
software programs. Examples of programming software include assemblers, compilers, debuggers and
interpreters.

INTERACTION OF SOFTWARE AND HARDWARE:


The interaction between the software and hardware is really required because without the interaction
neither software nor hardware can perform any task required by the user.
-We write code in a text editor using any language like C++, JAVA, Python, etc.
-This code is given to the compiler and it actually converts it to assembly code that is very close to
machine hardware as it depends on an instruction set which is then converted to the binary that is 0s and
1s which actually represent digital voltage fed to transistors inside the chip.
-Now we have voltages that are actually required to run the hardware. These voltages actually connect
the correct circuitry inside the chip and perform that specific task for example addition, subtraction, etc.
All these operations are done by the combination of little transistors if we go into low level or flip-flops
which are the combination of gates and gates are a combination of transistors. So, it all started with the
invention of transistors.
-The chip or microprocessor has a lot of circuits inside it to perform various tasks like arithmetic and
logical tasks. The computer hardware also contains RAM which is another chip that can store data
temporarily and a Hard disk that can permanently store data.
-The operating system is also responsible for feeding the software to the right hardware like the
keyboard, mouse, screen, etc.

GENERAL FUNCTION OF CPU,ALU,CONTROL UNIT & MEMORY:


CPU: Central Processing Unit. The central processing unit (CPU) is the primary component of any digital
computer system, consisting of the main memory, the control unit, and the arithmetic-logic unit. It is the
physical heart of the entire computer system, to which various peripheral equipment, such as
input/output devices and auxiliary storage units, are connected.The central processing unit’s control unit
regulates and integrates the computer’s operations. It selects and retrieves instructions from the main
memory in the correct sequence and interprets them so that the other functional elements of the system
can perform their respective operations at the appropriate time. All input data are transferred via main
memory to the arithmetic-logic unit for processing, which includes the four basic arithmetic functions
(addition, subtraction, multiplication, and division) as well as certain logic operations such as data
comparison and selection of the desired problem-solving procedure or a viable alternative based on
predetermined decision criteria.

ALU: Arithmetic and Logical Unit Sections of Arithmetic and Logic:


Arithmetic Unit: The arithmetic unit’s function is to perform arithmetic operations such as addition,
subtraction, multiplication, and division. All complex operations are carried out by repeatedly performing
the aforementioned operations.
Logic Unit: The logic unit’s function is to perform logic operations on data such as comparing, selecting,
matching, and merging.
Registers: A processor register (CPU register) is one of a small set of data holding places that are part
of the computer processor. A register may hold an instruction, a storage address, or any kind of data
(such as a bit sequence or individual characters). Some instructions specify registers as part of the
instruction.

CONTROL UNIT: This unit manages the operations of all computer components but does not perform
any actual data processing. To function properly, all CPU components must be synchronized. The control
unit performs this function at a rate determined by the clock speed and is in charge of directing the
operations of the other units through the use of timing signals that run throughout the CPU.

MEMORY: RAM: Random Access Memory(also known as Main Memory) Your computer RAM is
essentially short term memory where data is stored as the processor needs it.Needed for program
execution and other purposes.
Secondary Memory: Memory which stores data which can be edited but unlike RAM it doesn't erase as
soon as the computer is turned off. It is used to store image,video, text or other kinds of files.
ROM: Read Only Memory. It can’t be edited by the user by normal means it stores all the important files
which are needed for booting and other important functions which are necessary. For Example
BIOS,POST,etc.
Cache: The CPU never has direct access to RAM. Modern CPUs have one or more cache layers. The
CPU’s calculation speed is much faster than the RAM’s ability to feed data to the CPU.

MOTHERBOARD AND BIOS:


A Motherboard provides connectivity between the hardware components of a computer, like the
processor (CPU), memory (RAM), hard drive, and video card. There are multiple types of motherboards,
designed to fit different types and sizes of computers.

BIOS: BIOS (basic input/output system) is the program a computer's microprocessor uses to start the
computer system after it is powered on. It also manages data flow between the computer's operating
system (OS) and attached devices, such as the hard disk, video adapter, keyboard, mouse and printer.
The BIOS software is stored in ROM Memory.

BOOTING PROCESS:
Booting is basically the process of starting the computer. When the CPU is first switched on it has
nothing inside the Memory. In order to start the Computer, load the Operating System into the Main
Memory and then the Computer is ready to take commands from the User.
Booting happens when you start the computer. This happens when we turn ON the power or the
computer restarts. The system BIOS (Basic Input/Output System) makes the peripheral devices active.
Further, it requires that the boot device loads the operating system into the main memory.
Booting Device: Booting can be done either through hardware (pressing the start button) or by giving
software commands. Therefore, a boot device is a device that loads the operating system. Moreover, it
contains the instructions and files which start the computer. Examples are the hard drive, floppy disk
drive, CD drive, etc. Among them, the hard drive is the most used one.

Types Of Booting:
Warm Booting: Warm Boot is also called soft boot. It refers to when we restart the computer. Here, the
computer does not start from the initial state. When the system gets stuck sometimes it is required to
restart it while it is ON. Therefore, in this condition the warm boot takes place. Restart button or
CTRL+ALT+DELETE keys are used for warm boot.
Cold Booting: A cold boot is also called a hard boot. It is the process when we first start the computer.
In other words, when the computer is started from its initial state by pressing the power button it is called
cold boot. The instructions are read from the ROM and the operating system is loaded in the main
memory.

STEPS OF BOOTING:
1.The Startup:
It is the first step that involves switching the power ON. It supplies electricity to the main components like
BIOS and processor.
2. BIOS: Power On Self Test:
It is an initial test performed by the BIOS. Further, this test performs an initial check on the input/output
devices, computer’s main memory, disk drives, etc. Moreover, if any error occurs, the system produces a
beep sound.
3. Loading of OS:
In this step, the operating system is loaded into the main memory. The operating system starts working
and executes all the initial files and instructions.
4. System Configuration:
In this step, the drivers are loaded into the main memory. Drivers are programs that help in the
functioning of the peripheral devices.
5. Loading System Utilities:
System utilities are basic functioning programs, for example, volume control, antivirus, etc. In this step,
system utilities are loaded into the memory.

User Authentication:
If any password has been set up in the computer system, the system checks for user authentication.
Once the user enters the login Id and password correctly the system finally starts.
MODULE-II: INTRODUCTION TO FLOWCHART AND ALGORITHMS:

ALGORITHMS: A procedure for solving a programming problem in a finite number of steps that involves
least operations.

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.
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.
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.
Processing: A box(Rectangle) represents arithmetic instructions. All arithmetic processes such as
adding, subtracting, multiplication and division are indicated by action or process symbol.
Decision: Diamond symbol represents a decision point. Decision based operations such as yes/no
question or true/false are indicated by diamond in flowchart.
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.
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.

GENERATIONS OF PROGRAMMING LANGUAGES:

1. First Generation Programming Language: The first generation languages are also called machine
languages/ 1G language. This language is machine-dependent. The machine language statements are
written in binary code (0/1 form) because the computer can understand only binary language.
Advantages : 1. Fast & efficient as statements are directly written in binary language.
2. No translator is required.
Disadvantages : 1. Difficult to learn binary codes.
2. Difficult to understand – both programs & where the error occurred.

2. Second Generation Programming Language: The second-generation languages are also called
assembler languages/ 2G languages. Assembly language contains human-readable notations that can
be further converted to machine language using an assembler.
Assembler – converts assembly level instructions to machine level instructions.
Programmers can write the code using symbolic instruction codes that are meaningful abbreviations of
mnemonics. It is also known as low-level language.
Advantages : 1. It is easier to understand compared to machine language.
2. Modifications are easy.
3. Correction & location of errors are easy.
Disadvantages :1. Assembler is required.
2. This language is architecture /machine-dependent, with a different instruction set for different
machines
.
3. Third Generation Language :The third generation is also called procedural language /3 GL. It
consists of the use of a series of English-like words that humans can understand easily, to write
instructions. It's also called High-Level Programming Language. For execution, a program in this
language needs to be translated into machine language using Compiler/ Interpreter. Examples of this
type of language are C, PASCAL, FORTRAN, COBOL, etc.
Advantages :1. Use of English-like words makes it a human-understandable language.
2. Lesser number of lines of code as compared to above 2 languages.
3. Same code can be copied to another machine & executed on that machine by using compiler-specific
to that machine.
Disadvantages :1. Compiler/ interpreter is needed.
2. Different compilers are needed for different machines.

4. Fourth Generation Language :The fourth-generation language is also called a non – procedural
language/ 4GL. It enables users to access the database. Examples: SQL, Foxpro, Focus, etc.
These languages are also human-friendly to understand.
Advantages :1. Easy to understand & learn.
2. Less time required for application creation.
3. It is less prone to errors.
Disadvantages :1. Memory consumption is high.
2. Has poor control over Hardware.
3. Less flexible.

5. Fifth Generation Language :The fifth-generation languages are also called 5GL. It is based on the
concept of artificial intelligence. It uses the concept that rather than solving a problem algorithmically,
an application can be built to solve it based on some constraints, i.e., we make computers learn to solve
any problem. Parallel Processing & superconductors are used for this type of language to make real
artificial intelligence.
Example: PROLOG, LISP, etc.
Advantages :1. Machines can make decisions.
2. Programmer effort reduces to solving a problem.
3. Easier than 3GL or 4GL to learn and use.
Disadvantages :1. Complex and long code.
2. More resources are required & they are expensive too.

HISTORY OF C LANGUAGE:
C programming language was developed in 1972 by Dennis Ritchie at Bell Laboratories of AT&T
(American Telephone & Telegraph), located in the U.S.A.
Dennis Ritchie is known as the founder of the c language.
It was developed to overcome the problems of previous languages such as B, BCPL, etc.
Initially, C language was developed to be used in the UNIX operating system. It inherits many features of
previous languages such as B and BCPL.

CHARACTERISTICS OF C LANGUAGE:
*Simple and Efficient. *The basic syntax style of implementing C language is very simple and easy to
learn, *Fast. *Portability. *Extensibility. *Function-Rich Libraries. *Dynamic Memory Management.
*Modularity With Structured Language. *Mid-Level Programming Language.

STRUCTURE OF C PROGRAM:
1.Preprocessor Commands (Header Commands(<include stdio.h>))
2.Functions (Can be predefined or User defined or imported from libraries.)
3.Variables (like int a=10,b,c; or float,char,arrays,etc)
4.Statements & Expressions (Consists of functions and operators)
5.Comments (Used to explain what we wanted to achieve or a piece of program that does not run.)

EXAMPLE:

#include <stdio.h> ← Preprocessor Cmd


int main() { ← Main Function
// Comment ← Comment
printf("Hello, World! \n"); ← Statements
return 0; }

DATA TYPES:
A data type, in programming, is a classification that specifies which type of value a variable has and what
type of mathematical, relational or logical operations can be applied to it without causing an error. A
string, for example, is a data type that is used to classify text and an integer is a data type used to
classify whole numbers. IN C LANGUAGE MAJOR: Char, Int, Float, and Double.

Data Type Format Specifier Minimal Specific Range Typical Bit Size

char %c -127 to 127(ASCII Value) 8

int %d -32,767 to 32,767 16 or 32

float %f 1E-37 to 1E+37 along with six digits of 32


the precisions here

double %lf 1E-37 to 1E+37 along with six digits of 64


the precisions here

VARIABLES: A variable in C is a memory location associated with some name in order to store some
form of data and retrieve it when required. We can store different types of data in the variable and reuse
the same variable for storing some other data any number of times.
For using a variable in C, we have to first define it to tell the compiler about its existence so that the
compiler can allocate the required memory to it.
SYNTAX: data_type var_name = intial_value;

KEYWORDS: In the context of a programming language, a keyword is a closely related or associated


word that is reserved by a program because the word has a special meaning that defines commands and
specific parameters for that code set. C language has 32 reserved Keywords.
KEYWORDS IN C:
auto double int struct
break else long switch
case enum register typedef
char extern return union
continue for signed void
do if static while
default goto sizeof volatile
const float short unsigned

CONSOLE INPUT/OUTPUT STATEMENTS:


C language has standard libraries that allow input and output in a program. The stdio.h or standard input
output library in C that has methods for input and output.
1. INPUT: scanf(): The scanf() method, in C, reads the value from the console as per the type specified.
SYNTAX: scanf(“%X”,&Variable_of_Type_X);
Where %X is the format specifier of the variable that needs to be input.

2. OUTPUT: printf(): The printf() method, in C, prints the value passed as the parameter to it, on the
console screen.
SYNTAX: printf(“Any_common_String %X”,Variable_of_Type_X);
Where %X is the format specifier of the variable that needs to be output in place of it.

COMPILING And LINKING:

COMPILING: The process of compilation consists of accessing the source code, written by the
programmer, and performing a check to ensure nothing is ambiguous to the computer. Each and every
programming language has a set of keywords that initiate a particular function. The order in which the
keywords are used to form meaningful instructions understood by the computer is called syntax. The
process of compilation also ensures that the syntax of the source code is correct. Then the source code
is converted step by step into the machine language.

IN C LANGUAGE:

A.Pre-Processing: Pre-processing is the first step in the compilation process in C performed using the
preprocessor tool (A pre-written program invoked by the system during the compilation). All the
statements starting with the # symbol in a C program are processed by the preprocessor, and it converts
our program file into an intermediate file with no # statements. Under following pre-processing tasks are
performed :
i. Comments Removal
Comments in a C Program are used to give a general idea about a particular statement or part of code
actually, comments are the part of code that is removed during the compilation process by the
preprocessor as they are not of particular use for the machine. The comments in the below program will
be removed from the program when the pre-processing phase completes.
ii. Macros Expansion
Macros are some constant values or expressions defined using the #define directives in C Language. A
macro call leads to the macro expansion. The pre-processor creates an intermediate file where some
pre-written assembly level instructions replace the defined expressions or constants (basically matching
tokens). To differentiate between the original instructions and the assembly instructions resulting from the
macros expansion, a '+' sign is added to every macros expanded statement.
iii. File inclusion
File inclusion in C language is the addition of another file containing some pre-written code into our C
Program during the pre-processing. It is done using the #include directive. File inclusion during
pre-processing causes the entire content of filename to be added to the source code, replacing the
#include<filename> directive, creating a new intermediate file.
Example: If we have to use basic input/output functions like printf() and scanf() in our C program, we
have to include a predefined standard input output header file i.e. stdio.h.
iv. Conditional Compilation
Conditional compilation is running or avoiding a block of code after checking if a macro is defined or not
(a constant value or an expression defined using #define). The preprocessor replaces all the conditional
compilation directives with some predefined assembly code and passes a newly expanded file to the
compiler. Conditional compilation can be performed using commands like #ifdef, #endif, #ifndef, #if,
#else and #elif in a C Program. Example :
Printing the AGE macro, if AGE macro is defined, else printing Not Defined and ending the conditional
compilation block with an #endif directive.

B. Compiling
Compiling phase in C uses an inbuilt compiler software to convert the intermediate (.i) file into an
Assembly file (.s) having assembly level instructions (low-level code). To boost the performance of the
program, the compiler translates the intermediate file to make an assembly file.
Assembly code is a simple English-type language used to write low-level instructions (in microcontroller
programs, we use assembly language). The whole program code is parsed (syntax analysis) by the
compiler software in one go, and it tells us about any syntax errors or warnings present in the source
code through the terminal window.

C. Assembling
Assembly level code (.s file) is converted into machine-understandable code (in binary/hexadecimal
form) using an assembler. Assembler is a pre-written program that translates assembly code into
machine code. It takes basic instructions from an assembly code file and converts them into
binary/hexadecimal code specific to the machine type known as the object code.
The file generated has the same name as the assembly file and is known as an object file with an
extension of .obj in DOS and .o in UNIX OS.

D. Linking
Linking is a process of including the library files into our program. Library Files are some predefined files
that contain the definition of the functions in the machine language and these files have an extension of
.lib. Some unknown statements are written in the object (.o/.obj) file that our operating system can't
understand. You can understand this as a book having some words that you don't know, and you will use
a dictionary to find the meaning of those words. Similarly, we use Library Files to give meaning to some
unknown statements from our object file. The linking process generates an executable file with an
extension of .exe in DOS and .out in UNIX OS.

Expecting:
Exception handling is a mechanism that separates code that detects and handles exceptional
circumstances from the rest of your program. Note that an exceptional circumstance is not necessarily
an error. When a function detects an exceptional situation, you represent this with an object.
EXPECTING NOT AVAILABLE IN C LANGUAGE.
MODULE-III: OPERATORS AND EXPRESSIONS :
OPERATORS:
Arithmetic Operators: An arithmetic operator performs mathematical operations such as addition,
subtraction, multiplication, division etc on numerical values (constants and variables).

OPERATORS MEANING OF OPERATORS

+ Addition(Unary)

- Subtraction

* Multiplication

/ Division

% Modulo/ Remainder after division operator

Increment and Decrement Operators: C programming has two operators increment ++ and decrement
-- to change the value of an operand (constant or variable) by 1.
Increment ++ increases the value by 1 whereas decrement -- decreases the value by 1. These two
operators are unary operators, meaning they only operate on a single operand.
++a pre increment; a++ post increment, –a pre decrement, a– post decrement.

Assignment Operators: An assignment operator is used for assigning a value to a variable. The most
common assignment operator is =.
Operators Example: a+=b → a = a+b :SAME FOR (+=, -=, *=, /=, %=)

Relational Operators: A relational operator checks the relationship between two operands. If the
relation is true, it returns 1; if the relation is false, it returns value 0.
Relational operators are used in decision making and loops.
→ == equals to, != not equals to, < less than, > greater than, >= greater than equal to,
<= less than equal to

Logical Operators: An expression containing a logical operator returns either 0 or 1 depending upon
whether the expression results true or false. Logical operators are commonly used in decision making in
C programming.

OPERATOR MEANING

&& (AND) True if both conditions are true

|| (OR) True if any of two condition is true

! (NOT) True if statement if false or 0

Bitwise Operators: During computation, mathematical operations like: addition, subtraction,


multiplication, division, etc are converted to bit-level which makes processing faster and saves power.
Bitwise operators are used in C programming to perform bit-level operations.
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR : ~ Bitwise complement
<< Shift left : >> Shift right
TYPE CASTING/ TYPE CONVERSIONS:
Type conversion in C is the process of converting one data type to another. The type conversion is only
performed to those data types where conversion is possible. Type conversion is performed by a
compiler. In type conversion, the destination data type can’t be smaller than the source data type. Type
conversion is done at compile time and it is also called widening conversion because the destination
data type can’t be smaller than the source data type.

Implicit Type Conversion: Also known as ‘automatic type conversion’.


→ Done by the compiler on its own, without any external trigger from the user.
→ Generally takes place when in an expression more than one data type is present. In such conditions
type conversion (type promotion) takes place to avoid loss of data.
→ All the data types of the variables are upgraded to the data type of the variable with the largest data
type. bool -> char -> short int -> int -> unsigned int -> long -> unsigned -> long long -> float ->
double -> long double
→ It is possible for implicit conversions to lose information, signs can be lost (when signed is implicitly
converted to unsigned), and overflow can occur (when long long is implicitly converted to float).

Explicit Type Conversion: This process is also called type casting and it is user-defined. Here the user
can typecast the result to make it of a particular data type. The syntax in C Programming:
(type) expression → Type indicates the data type to which the final result is converted.

BRANCHING STATEMENTS(IF-ELSE STATEMENTS):


If, Else, Else IF:
if (condition) {statement needed to be executed} ; Used to check if a condition is true, if the condition
is true then the statement used to run, otherwise the statement inside is ignored.
else {statement needed to run when if_block is false}; Used with if and when the if condition is false
the statements inside the else block use to run.
else if (condition other than if) {statement needed to be run}; else if command can be used with if
cmd if more then one condition is needed to be checked.
PROCESS:
1. If, if condition is true then if block is executed and the control returns outside the if else blocks.
2. When else if cmds are present on if they are false these conditions are checked and on being true the
statements inside these blocks get executed and control returns to the basic manner.
3. If all the conditions are false then the else part is executed and the control comes out of the branching
statements.

SWITCH STATEMENTS:
SYNTAX:

switch (expression)
​{ case constant1:
// statements
break;
case constant2:
// statements
break; // if break is not present than all statements below the true case will run including true case
.
.
.
default:
// default statements these are optional }
The expression is evaluated once and compared with the values of each case label.
If there is a match, the corresponding statements after the matching label are executed. For example, if
the value of the expression is equal to constant2, statements after case constant2: are executed until
break is encountered.
If there is no match, the default statements are executed.

LOOPING STATEMENTS:
FOR LOOP:

for (initializationStatement; testExpression; updateStatement)


{
// statements inside the body of loop
}

InitializationStatement: Runs only once and initializes the iterator.


testExpression: Sets the statement which terminates the loop.
Updatestatement: Updates the iterator, or the loop can be infinite.

WHILE LOOP:

while (testExpression) {
// the body of the loop
}

If testexpression is true then the loop start. We usually insert break statements inside the while loop to
stop it before it crashes the memory.

DO WHILE LOOP:

do {
// the body of the loop
}
while (testExpression);

The do..while loop is similar to the while loop with one important difference. The body of do...while loop is
executed at least once. Only then, the test expression is evaluated. If the test expression is true then the
loop runs again and this process continues.

JUMP STATEMENTS: Jump statements are used to manipulate the flow of the program if some
conditions are met. It is used to terminate or continue the loop inside a program or to stop the execution
of a function. In C++ there are four jump statements: continue, break, return, and goto.

A break statement is used to terminate the execution of the rest of the block where it is present and
takes the control out of the block to the next statement. Used as → break;

The continue jump statement like any other jump statement interrupts or changes the flow of control
during the execution of a program. Continue is mostly used in loops. Used As → continue;

The goto jump statement is used to transfer the flow of control to any part of the program desired. The
programmer needs to specify a label or identifier with the goto statement in the following manner:
goto there; // where there is present somewhere else (Generally outside the loop)
there:
printf("Anubhav is Great");

Return jump statement is usually used at the end of a function to end or terminate it with or without a
value. It takes the control from the calling function back to the main function(main function itself can also
have a return).
Used As: return value;
ARRAYS:
● It is a group of variables of similar data types referred to by a single element.
● Its elements are stored in a contiguous memory location.
● The size of the array should be mentioned while declaring it.
● Array elements are always counted from zero (0) onward.
● Array elements can be accessed using the position of the element in the array.
● The array can have one or more dimensions.
Advantages:-
● Random access of elements using the array index.
● Use of fewer lines of code as it creates a single array of multiple elements.
● Easy access to all the elements.
● Traversal through the array becomes easy using a single loop.
● Sorting becomes easy as it can be accomplished by writing fewer lines of code.
Disadvantages:-
● Allows a fixed number of elements to be entered which is decided at the time of declaration.
Unlike a linked list, an array in C is not dynamic.
● Insertion and deletion of elements can be costly since the elements are needed to be managed in
accordance with the new memory allocation.

ARRAY DECLARATION: data_type name_of_array[size_of_array];


Initializing Array: int arr[5] = {0,1,2,3,4}

MULTIDIMENSIONAL ARRAY :
Declaration: data_type name_of_array[size1][size2]...[sizen]; //sizes of diff. Dimension
→ It can store size1*size2*...*sizen elements.
Initializing Array: int arr[3][4] = {{0,1,2,3},{5,6,7,8},{9,10,11,12}}

Visualization of Array(Figure).
MODULE-IV: FUNCTIONS:

FUNCTIONS: A function is a block of code that performs a specific task.Dividing a complex problem into
smaller chunks makes our program easy to understand and reuse.

TYPES OF FUNCTIONS:
→ Built-in Functions: The standard library functions are built-in functions in C programming.
These functions are defined in header files. For example,
The printf() is a standard library function to send formatted output to the screen (display output on the
screen). This function is defined in the stdio.h header file.Hence, to use the printf()function, we need to
include the stdio.h header file using #include <stdio.h>.The sqrt() function calculates the square root of a
number. The function is defined in the math.h header file.
→ User-Defined Functions: You can also create functions as per your need. Such functions created by
the user are known as user-defined functions.
SYNTAX:

#include <stdio.h>
data_type function_Name(data_type arrg1, data_type arrg2); // function prototype

int main()
{
function_Name(a,b); // function call
}

return_data_type function_Name(data_type arrg1, data_type arrg2) // function definition


{
// Statement under functions
return result; // return statement
}

Prototype: Provides us name of function, return type of functions, which type and how much argument
will it need.
Function Call: Control of the program is transferred to the user-defined function by calling it.
Function Definition: Function definition contains the block of code to perform a specific task.
Return Statement: The return statement terminates the execution of a function and returns a value to
the calling function. The program control is transferred to the calling function after the return statement.

ADVANTAGES OF USER-DEFINED FUNCTIONS:


● The program will be easier to understand, maintain and debug.
● Reusable codes that can be used in other programs
● A large program can be divided into smaller modules. Hence, a large project can be divided
among many programmers.

STORAGE CLASS AND SCOPE OF VARIABLES:


Storage Classes are used to describe the features of a variable/function. These features basically
include the scope, visibility and life-time which help us to trace the existence of a particular variable
during the runtime of a program. C language uses 4 storage classes, namely:

auto: This is the default storage class for all the variables declared inside a function or a block. Hence,
the keyword auto is rarely used while writing programs in C language. Auto variables can be only
accessed within the block/function they have been declared and not outside them (which defines their
scope). Of course, these can be accessed within nested blocks within the parent block/function in which
the auto variable was declared. However, they can be accessed outside their scope as well using the
concept of pointers given here by pointing to the very exact memory location where the variables reside.
They are assigned a garbage value by default whenever they are declared.

extern: Extern storage class simply tells us that the variable is defined elsewhere and not within the
same block where it is used. Basically, the value is assigned to it in a different block and this can be
overwritten/changed in a different block as well. So an extern variable is nothing but a global variable
initialized with a legal value where it is declared in order to be used elsewhere. It can be accessed within
any function/block. Also, a normal global variable can be made extern as well by placing the ‘extern’
keyword before its declaration/definition in any function/block. This basically signifies that we are not
initializing a new variable but instead we are using/accessing the global variable only. The main purpose
of using external variables is that they can be accessed between two different files which are part of a
large program. For more information on how external variables work, have a look at this link.

static: This storage class is used to declare static variables which are popularly used while writing
programs in C language. Static variables have the property of preserving their value even after they are
out of their scope! Hence, static variables preserve the value of their last use in their scope. So we can
say that they are initialized only once and exist till the termination of the program. Thus, no new memory
is allocated because they are not re-declared. Their scope is local to the function to which they were
defined. Global static variables can be accessed anywhere in the program. By default, they are assigned
the value 0 by the compiler.

register: This storage class declares register variables that have the same functionality as that of the
auto variables. The only difference is that the compiler tries to store these variables in the register of the
microprocessor if a free registration is available. This makes the use of register variables to be much
faster than that of the variables stored in the memory during the runtime of the program. If a free
registration is not available, these are then stored in the memory only. Usually few variables which are to
be accessed very frequently in a program are declared with the register keyword which improves the
running time of the program. An important and interesting point to be noted here is that we cannot obtain
the address of a register variable using pointers.

SYNTAX: storage_class var_data_type var_name;

SCOPE OF VARIABLES: A scope is a region of the program, and the scope of variables refers to the
area of the program where the variables can be accessed after its declaration.
File Scope Scope of an Identifier starts at the beginning of the file and ends at the end of the file. It
refers to only those Identifiers that are declared outside of all functions. The Identifiers of File scope are
visible all over the file Identifiers having file scope are global
Block Scope: Scope of an Identifier begins at opening of the block / ‘{‘ and ends at the end of the block /
‘}’. Identifiers with block scope are local to their block
Function Prototype Scope:Identifiers declared in function prototype are visible within the prototype
Function scope: Function scope begins at the opening of the function and ends with the closing of it.
Function scope is applicable to labels only. A label declared is used as a target to goto statement and
both goto and label statement must be in same function

STRINGS: String in C programming is a sequence of characters terminated with a null character ‘\0’.
Strings are defined as an array of characters. The difference between a character array and a string is
that the string is terminated with a unique character ‘\0’.
SYNTAX: char str_name[size];
1. Assigning a string literal without size: char str[] = "GeeksforGeeks";
2. Assigning a string literal with a predefined size:char str[50] = "GeeksforGeeks";
3. Assigning character by character with size: char str[14] = { 'G','e','e','k','s','f','o','r','G','e','e','k','s','\0'};
4. Assigning character by character without size:char str[] = { 'G','e','e','k','s','f','o','r','G','e','e','k','s','\0'};

STRING MANIPULATION FUNCTIONS:


strlen() computes string's length
strcpy() copies a string to another
strcat() concatenates(joins) two strings
strcmp() compares two strings
strlwr() converts string to lowercase
strupr() converts string to uppercase
GETS AND PUTS:
gets(): used to take input from the user.
puts(): used to give output to the user.

STRUCT: STRUCTURES:

struct structureName {
dataType member1;
dataType member2;
...
};

Create struct Variables: When a struct type is declared, no storage or memory is allocated. To allocate
memory of a given structure type and work with it, we need to create variables.

struct Person {
// code
};

int main() {
struct Person person1, person2, p[20];
return 0; }

//Another way of creating a struct variable is:


struct Person {
// code
} person1, person2, p[20];

Accessing Member: person1.member


We can use typedef to write an equivalent code with a simplified syntax:

typedef struct Distance {


int feet;
float inch;
} distances;

int main() {
distances d1, d2;
}
Union: A union is a user-defined type similar to structs in C except for one key difference. Structures
allocate enough space to store all their members, whereas unions can only hold one member value at a
time.With a union, all members share the same memory. Syntax similar to structures.

ENUMERATED DATA TYPES: In C programming, an enumeration type (also called enum) is a data type
that consists of integral constants. To define enums, the enum keyword is used.
enum flag {const1, const2, ..., constN};
By default, const1 is 0, const2 is 1 and so on. You can change default values of enum elements during
declaration (if necessary). EXAMPLE:

#include <stdio.h>
enum week {Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday};
int main()
{
// creating today variable of enum week type
enum week today;
today = Wednesday;
printf("Day %d",today+1);
return 0;
}
Output: Day 4

Static variables: have a property of preserving their value even after they are out of their scope! Hence,
static variables preserve their previous value in their previous scope and are not initialized again in the
new scope.
Syntax: static data_type var_name = var_value;
1) A static int variable remains in memory while the program is running. A normal or auto variable is
destroyed when a function call where the variable was declared is over.
2) Static variables are allocated memory in the data segment, not the stack segment. See memory layout
of C programs for details.
3) Static variables (like global variables) are initialized as 0 if not initialized explicitly. For example in the
below program, the value of x is printed as 0, while the value of y is something garbage. See this for
more details.
4) In C, static variables can only be initialized using constant literals. For example, the following program
fails in compilation. See this for more details.
5) Static global variables and functions are also possible in C/C++. The purpose of these is to limit scope
of a variable or function to a file.
MODULE-V:POINTERS:

POINTERS CONCEPT: You learned from the previous chapter, that we can get the memory address of a
variable with the reference operator &.
A pointer is a variable that stores the memory address of another variable as its value.
A pointer variable points to a data type (like int) of the same type, and is created with the * operator. The
address of the variable you are working with is assigned to the pointer:
SYNTAX:

int myAge = 43; // An int variable


int* ptr = &myAge; // A pointer variable, with the name ptr, that stores the address of myAge
printf("%d\n", myAge); // Output the value of myAge (43)
printf("%p\n", &myAge); // Output the memory address of myAge (0x7ffe5367e044)
printf("%p\n", ptr); // Output the memory address of myAge with the pointer (0x7ffe5367e044)

Function Pointers: As we know that we can create a pointer of any data type such as int, char, float, we
can also create a pointer pointing to a function. The code of a function always resides in memory, which
means that the function has some address. We can get the address of memory by using the function
pointer. func_data_type (*function_name) (arg_data_type , arg_data_type);
Pointer’s Pointer: As we know, a pointer is used to store the address of a variable in C. Pointer reduces
the access time of a variable. However, In C, we can also define a pointer to store the address of another
pointer. Such a pointer is known as a double pointer (pointer to pointer). The first pointer is used to store
the address of a variable whereas the second pointer is used to store the address of the first pointer.
data_type_of_pointer **name_of_variable = & normal_pointer_variable;
Array’s Pointer: Pointers to an array point the address of the memory block of an array variable. The
following is the syntax of array pointers. datatype *variable_name[size]; Here, datatype − The datatype of
variables like int, char, float etc. datatype *variable_name[size];

ARRAY OF POINTERS: “Array of pointers” is an array of the pointer variables. It is also known as
pointer arrays.
Syntax: int *var_name[array_size];
Declaration of an array of pointers: int *ptr[3];
We can make separate pointer variables which can point to the different values or we can make one
integer array of pointers that can point to all the values.

<struct_name> * <array_name> [ <size_of_array> ] ; // Declaration


<array_name> [ <index_number> ] = <pointer_to_the_structure> ; // Initialization
<array_name> [<index_number>] -> <data to be accessed which is present inside the structure >
//access

2D Arrays
Step 1 – Declaring and initializing 2D arrays
<structure_name> * <array_name> [number_of_rows][number_of_columns];
<array_name> [row_number][column_number] = <pointer_to_structure> ;
Step 2- Accessing elements of our 2D array
< array_name >[ <row_number> ][ <column_number> ] -> <data to be accessed which is present inside
the structure >;

C Pointers to struct

struct name {
member1;
Member2; };
int main()
{ struct name *ptr, Harry;}

Here, ptr is a pointer to struct.

DYNAMIC MEMORY ALLOCATION:


Sometimes the size of the array you declared may be insufficient. To solve this issue, you can allocate
memory manually during run-time. This is known as dynamic memory allocation in C programming.
To allocate memory dynamically, library functions are malloc(), calloc(), realloc() and free() are used.
These functions are defined in the <stdlib.h> header file.
C malloc() :The name "malloc" stands for memory allocation.
The malloc() function reserves a block of memory of the specified number of bytes. And, it returns a
pointer of void which can be casted into pointers of any form.
Syntax of malloc()
ptr = (castType*) malloc(size);
C calloc(): The name "calloc" stands for contiguous allocation.
The malloc() function allocates memory and leaves the memory uninitialized, whereas the calloc()
function allocates memory and initializes all bits to zero.
Syntax of calloc()
ptr = (castType*)calloc(n, size);
C free(): Dynamically allocated memory created with either calloc() or malloc() doesn't get freed on their
own. You must explicitly use free() to release the space.
Syntax of free()
free(ptr);
C realloc(): If the dynamically allocated memory is insufficient or more than required, you can change
the size of previously allocated memory using the realloc() function.
Syntax of realloc()
ptr = realloc(ptr, x);
Here, ptr is reallocated with a new size x.

Types of Data Structures in C


The data structures in C can be classified into two categories:
Primitive Data Structures
The primitive data structures in C are those basic data structures that are already defined in the C
language. These data structures can be used to store only a single value. They are the foundation of
data manipulation. The primitive data structures in C (also known as primitive data types) include int,
char, float, double, and pointers.

Non-Primitive Data Structures


The non-primitive data structures in C are also known as the derived data structures as they are derived
from primitive ones. A large number of values can be stored using the non-primitive data structures. The
data stored can also be manipulated using various operations like insertion, deletion, searching, sorting,
etc. The data structures like arrays, trees, stacks, and many more come under this category.

The non-primitive data structures in C can further be divided into two categories:

1. Linear Data Structures


Linear data structures in C store the data in a sequential or linear fashion. The memory location of each
element stored can be accessed sequentially. The elements may not be present adjacently in the
memory, however, each element is attached to the next element in some way. Example - arrays, linked
lists, stacks, etc.

2. Non-Linear Data Structures


Non-linear data structures in C store the data in a non-sequential manner. The data is stored in multiple
levels. The implementation of non-linear data structures is more complex than linear data structures.
Example - graphs, trees.

On the basis of size, the data structures in C can also be classified as:

Static Data Structures


The static nature of data structures is exhibited in the memory allocated to them. The size of such data
structures is fixed as the memory is allocated to them during the compile time. However, the values of
the elements stored are not static and can be modified at any time. Example - Array.

Dynamic Data Structures


The dynamic data structures in C are capable of resizing themselves during the run time of the program.
The memory space allocated to such data structures can be modified (increased or decreased), thus
providing more flexibility to manipulate the data stored in them. Example - Linked List.

You might also like