Syllabus - CO Wise - Programming For Problem Solving (KCS-101/KCS-201) - 2020-21
Syllabus - CO Wise - Programming For Problem Solving (KCS-101/KCS-201) - 2020-21
Syllabus - CO Wise - Programming For Problem Solving (KCS-101/KCS-201) - 2020-21
Programming Basics: Structure of C Program Writing and executing the first C program, Syntax and
logical errors in compilation, object and executable code. Components of C language.
Standard I/O in C, Fundamental data types, Variables and memory locations, Storage classes
Operators and expression using numeric and relational operators, mixed operands, Type conversion
Logical operators, bit operations, assignment operator, Operator precedence and associativity.
Applying if statement Applying switch statement Nesting if and else Use of break and default with switch.
Use of while, do while Use of for loops Multiple loop variables, use of break and continue statements.
CO-4: To decompose a problem into functions and synthesize a complete program using divide and conquer
approach.
Functions: Introduction, Types of functions Passing parameters to functions, call by value Call by
reference Recursive functions. Functions with array
CO-5: To use arrays, pointers and structures to develop algorithms and programs.
Arrays: Array notation and representation, manipulating array elements Using multi-dimensional arrays
passing arrays to functions Character arrays and strings Structure Array of structures Union, enumerated
data types Basic Algorithms: Searching Basic Sorting Algorithms (Bubble, Insertion) Selection Sorting
Finding roots of equations, Notion of order of complexity Pointers: Introduction, declaration, applications
Introduction to dynamic memory allocation (malloc, calloc, realloc, free) Use of pointers in self-
referential structures Notion of linked list (no implementation) File handling: File I/O functions File
handling: File I/O functions Standard C preprocessors Defining and calling macros, command-line
arguments
PO Statement
Engineering knowledge: Apply the knowledge of mathematics, science,
PO1 engineering fundamentals, and an engineering specialization to the solution of
complex computer engineering problems.
Problem analysis: Identify, formulate, review research literature, and analyze
PO2 complex computer engineering problems reaching substantiated conclusions
using first principles of mathematics, natural sciences, and engineering sciences.
Design/development of solutions: Design solutions for complex computer
engineering problems and design system components or processes that meet the
PO3
specific needs with appropriate considerations for the public health and safety,
and the cultural, societal, and environmental considerations.
Conduct investigations of complex problems: Use research-based knowledge
PO4 and research methods including design of experiments, analysis and
interpretation of data, and synthesis of the information to provide conclusions
Modern tool usage: Create, select, and apply appropriate techniques, resources,
PO5 and modern engineering and IT tools including prediction and modeling to
complex engineering activities with an understanding of the limitations
The engineer and society: Apply reasoning informed by the contextual
PO6 knowledge to assess societal, health, safety, legal and cultural issues and the
consequent relevant to the professional engineering practices
Environment and sustainability: Understand the impact of the professional
PO7 engineering solutions in societal and environmental contexts, and demonstrate
the knowledge of, and need for sustainable development
Ethics: Apply ethical principles and commit to professional ethics and
PO8
responsibilities and norm of the engineering practices
Individual and team work: Function effectively as an individual, and as a
PO9
member or leader in diverse teams, and in multidisciplinary settings
Communications: Communicate effectively on complex engineering activities
with the engineering community and with society at large, such as, being able to
PO10
comprehend and write effective reports and design documentation, make
effective presentations, and give and receive clear instructions
Project management and finance: Demonstrate knowledge and understanding
of the engineering and management principles and apply these to one’s own
PO11
work, as a member and leader in a team, to manage projects and in
multidisciplinary environments.
Life-long learning: Recognize the need for, and have the preparation and ability
to engage in independent and life learning in the broadest context of
PO12
technological change.
Solving problems is the core of computer science. Programmers must first understand
how a human solves a problem, then understand how to translate this "algorithm" into
something a computer can do, and finally how to "write" the specific syntax (required by
a computer) to get the job done. It is sometimes the case that a machine will solve a problem
in a completely different way than a human.
Especially when it comes to programming, problem-solving is the must. If you do not
develop sound problem-solving skills, you will end up messing around with a given problem,
and you would not be able to obtain a solution for ages.
Computer Programmers are problem solvers. In order to solve a problem on a computer
you must: Know how to represent the information (data) describing the problem &Determine
the steps to transform the information from one representation into another.
Programming Basics: Structure of C Program Writing and executing the first C program,
Syntax and logical errors in compilation, object and executable code. Components of C
language. Standard I/O in C, Fundamental data types, Variables and memory locations,
Storage classes
Operators and expression using numeric and relational operators, mixed operands, Type
conversion Logical operators, bit operations, assignment operator, Operator precedence and
associativity.
Applying if statement Applying switch statement Nesting if and else Use of break and
default with switch. Use of while, do while Use of for loops Multiple loop variables, use of
break and continue statements.
CO-4: To decompose a problem into functions and synthesize a complete program using
divide and conquer approach.
CO-5: To use arrays, pointers and structures to develop algorithms and programs.
Arrays: Array notation and representation, manipulating array elements Using multi-
dimensional arrays passing arrays to functions Character arrays and strings Structure Array
of structures Union, enumerated data types Basic Algorithms: Searching Basic Sorting
Algorithms (Bubble, Insertion) Selection Sorting Finding roots of equations, Notion of order
of complexity Pointers: Introduction, declaration, applications Introduction to dynamic
memory allocation (malloc, calloc, realloc, free) Use of pointers in self-referential structures
Notion of linked list (no implementation) File handling: File I/O functions File handling:
File I/O functions Standard C preprocessors Defining and calling macros, command-line
arguments
PO Statement
Engineering knowledge: Apply the knowledge of mathematics, science, engineering
PO1 fundamentals, and an engineering specialization to the solution of complex computer engineering
problems.
Problem analysis: Identify, formulate, review research literature, and analyze complex
PO2 computer engineering problems reaching substantiated conclusions using first principles of
mathematics, natural sciences, and engineering sciences.
Design/development of solutions: Design solutions for complex computer engineering problems
and design system components or processes that meet the specific needs with appropriate
PO3
considerations for the public health and safety, and the cultural, societal, and environmental
considerations.
Modern tool usage: Create, select, and apply appropriate techniques, resources, and modern
PO5 engineering and IT tools including prediction and modeling to complex engineering activities
with an understanding of the limitations
The engineer and society: Apply reasoning informed by the contextual knowledge to assess
PO6 societal, health, safety, legal and cultural issues and the consequent relevant to the professional
engineering practices
Environment and sustainability: Understand the impact of the professional engineering
PO7 solutions in societal and environmental contexts, and demonstrate the knowledge of, and need for
sustainable development
Ethics: Apply ethical principles and commit to professional ethics and responsibilities and norm
PO8
of the engineering practices
Individual and team work: Function effectively as an individual, and as a member or leader in
PO9
diverse teams, and in multidisciplinary settings
Communications: Communicate effectively on complex engineering activities with the
engineering community and with society at large, such as, being able to comprehend and write
PO10
effective reports and design documentation, make effective presentations, and give and receive
clear instructions
Project management and finance: Demonstrate knowledge and understanding of the
PO11 engineering and management principles and apply these to one’s own work, as a member and
leader in a team, to manage projects and in multidisciplinary environments.
Life-long learning: Recognize the need for, and have the preparation and ability to engage in
PO12
independent and life learning in the broadest context of technological change.
Teaching-
Syllabus coverage (including revisions and practice programs) through 52 online/offline
lectures
Lecture Notes/PPT/Video Lectures will be provided just after the completion of lecture.
Revision /Q & A sessions after each CO syllabus coverage.
For fast learner’s initiation of project based learning. (As applicable)
Assessment-
2 test (CAE-1 & CAE-2)
5 Online /Offline quiz (CO wise)
Teacher Assessment -10 Marks based on 5 CO wise assignment
Attendance-10 Marks (Criteria- you`ll get 10 marks if attendance is more than 90%)
Pre-requisite keywords
Program-
A program can be defined as a collection of instructions written to perform any user`s defined task in
computer.
Data-
Any raw facts
Information-
Collection of data that has some meaning (Meaningful Data)
Hardware-
Computer hardware is a collective term used to describe any of the physical components of an analog or
digital computer.
Software-
Software commands the hardware what to do & how to do it. Together, the hardware & software form the
computer system. This software is further classified as system software & application software.
System Software-
System software are a set of programs, responsible for running the computer, controlling various operations
of computer systems and management of computer resources. They act as an interface between the hardware
of the computer & the application software. E.g.: Operating System.
Application software
Application Software is a set of programs designed to solve a particular problem for users. It allows the end
user to do something besides simply running the hardware. E.g.: Web Browser, Gaming Software, etc.
Right from its inception, to the present day, all computer system (irrespective of their shape & size)
perform the following 5 basic operations. It converts the raw input data into information, which is useful to
the users.
Input: It is the process of entering data & instructions to the computer system.
Storing: The data & instructions are stored for either initial or additional processing, as & when
required.
Processing: It requires performing arithmetic or logical operation on the saved data to convert it
into useful information.
Output: It is the process of producing the output data to the end user.
Controlling: The above operations have to be directed in a particular sequence to be completed.
Input Unit
We need to first enter the data & instruction in the computer system, before any computation begins.
This task is accomplished by the input devices. (The data accepted is in a human readable form. The input
device converts it into a computer readable form).
Input device: The input device is the means through which data and instructions enter in a computer.
1. Camera - The camera transmits a picture from one computer to another, or can be used to record a short
video.
2.Compact Disc (CD) - CDs store information. The CD can then be put into another computer, and the
information can be opened and added or used on the second computer. Note: A CD-R or CD-RW can also
be used as an OUTPUT device.
4.Mouse - The mouse is used to open and close files, navigate web sites, and click on a lot of commands
(to tell the computer what to do) when using different applications.
5.Microphone - A microphone is used to record sound. The sound is then saved as a sound file on the
computer.
6.Scanner - A scanner is used to copy pictures or other things and save them as files on the computer.
7.Joystick - A joystick is used to move the cursor from place to place, and to click on various items in
programs. A joystick is used mostly for computer games.
8.Bar Code Scanner - A bar code scanner scans a little label that has a bar code on it. The information is
then saved on the computer. Bar code scanners are used in libraries a lot.
Storing/Storage Unit
The data & instruction that are entered have to be stored in the computer. Similarly, the end results & the
intermediate results also have to be stored somewhere before being passed to the output unit. The storage
unit provides solution to all these issues. The storage unit is designed to save the initial data, the intermediate
result & the final result. They are of two types: Primary storage & Secondary storage.
Primary Storage:
The primary storage, also called as the main memory, holds the data when the computer is currently on.
As soon as the system is switched off or restarted, the information held in primary storage disappears (i.e. it
is volatile in nature). Moreover, the primary storage normally has a limited storage capacity, because it is
very expensive as it is made up of semiconductor devices.RAM is a primary storage.
a. Magnetic Disk
The Magnetic Disk is Flat, circular platter with metallic coating that is rotated beneath read/write heads. It
is a Random access device; read/write head can be moved to any location on the platter.
b. floppy Disk
These are small removable disks that are plastic coated with magnetic recording material. Floppy disks
are typically 3.5″ in size (diameter) and can hold 1.44 MB of data. This portable storage device is a
rewritable media and can be reused a number of times. Floppy disks are commonly used to move files
between different computers. The main disadvantage of floppy disks is that they can be damaged easily and,
therefore, are not very reliable.
c.Hard disk
A hard disk consists of one or more rigid metal plates coated with a metal oxide material that allows data to
be magnetically recorded on the surface of the platters. The hard disk platters spin at a high rate of speed,
typically 5400 to 7200 revolutions per minute (RPM). Storage capacities of hard disks for personal
computers range from 10 GB to 120 GB (one billion bytes are called a gigabyte).
d.CD:
Compact Disk (CD) is portable disk having data storage capacity between 650-700 MB. It can hold large
amount of information such as music, full-motion videos, and text etc. It contains digital information that
can be read, but cannot be rewritten. Separate drives exist for reading and writing CDs. Since it is a very
e.DVD
Digital Versatile Disk (DVD) is similar to a CD but has larger storage capacity and enormous clarity.
Depending upon the disk type it can store several Gigabytes of data (as opposed to around 650MB of a CD).
DVDs are primarily used to store music or movies and can be played back on your television or the computer
too. They are not rewritable media. It’s also termed DVD (Digital Video Disk)
Processing
Together the Control Unit & the Arithmetic Logic Unit are called as the Central Processing Unit (CPU).
The CPU is the brain of the computer. Like in humans, the major decisions are taken by the brain itself &
other body parts function as directed by the brain. Similarly, in a computer system, all the major calculations
& comparisons are made inside the CPU. The CPU is responsible for activating & controlling the operation
of other units of the computer system.
The actual execution of the instructions (arithmetic or logical operations) takes place over here. The data
& instructions stored in the primary storage are transferred as & when required. No processing is done in the
primary storage. Intermediate results that are generated in ALU are temporarily transferred back to the
primary storage, until needed later. Hence, data may move from the primary storage to ALU & back again
to storage, many times, before the processing is done.
OutputUnit
The job of an output unit is just the opposite of an input unit. It accepts the results produced by the
computer in coded form. It converts these coded results to human readable form. Finally, it displays the
converted results to the outside world with the help of output devices (E.g.: monitors, printers, projectors
etc.).
Output device: Device that lets you see what the computer has accomplished.
1.Monitor - A monitor is the screen on which words, numbers, and graphics can be seem. The monitor is
the most common output device.
2.Compact Disk - Some compact disks can be used to put information on. This is called burning information
to a CD. NOTE: A CD can also be an input device.
4.Speaker - A speaker gives you sound output from your computer. Some speakers are built into the
computer and some are separate.
5.Headphones - Headphones give sound output from the computer. They are similar to speakers, except
they are worn on the ears so only one person can hear the output at a time.
Control Unit:
This unit controls the operations of all parts of the computer but does not carry out any actual data
processing. It is responsible for the transfer of data and instructions among other units of the computer. It
manages and coordinates all the units of the system. It also communicates with Input/Output devices for
transfer of data or results from the storage units.
Volatile Memory: This loses its data, when power is switched off.
Non-Volatile Memory: This is a permanent storage and does not lose any data when power is
switched off.
Auxiliary memory access time is generally 1000 times that of the main memory, hence it is at the bottom
of the hierarchy.
The main memory occupies the central position because it is equipped to communicate directly with the
CPU and with auxiliary memory devices through Input/output processor (I/O).
When the program not residing in main memory is needed by the CPU, they are brought in from auxiliary
memory. Programs not currently needed in main memory are transferred into auxiliary memory to provide
space in main memory for other programs that are currently in use.
The cache memory is used to store program data which is currently being executed in the CPU.
Approximate access time ratio between cache memory and main memory is about 1 to 7~10
Pre-requisite keywords
Program-
A program is a set of instruction written to implement any task.
Process-
A program in execution is known as process.
File-
A file can be understood as a container in a computer system for storing information/data. Data/information
Network-
Computer network can be defined as the group of computers connected for the purpose of communicating
data from one computer to other.
Resources-
In computer, resources can be CPU, RAM, Input/Output devices, Processor.
Multiprogramming-
A computer running more than one program at a time (like running Excel and Firefox simultaneously).
Bug-
Bug is a logical error which generate wrong output.
Debugging-
Identification of bug is debugging.
An operating system (OS) is a collection of software that manages computer hardware resources and
provides common services for computer programs.
Functions of OS
Following are some of important functions of an operating System.
Memory Management
Processor Management
Device Management
File Management
Memory Management
Memory management refers to management of Primary Memory or Main Memory. Main memory is a
large array of words or bytes where each word or byte has its own address.
Main memory provides a fast storage that can be accessed directly by the CPU. For a program to be
executed, it must in the main memory. An Operating System does the following activities for memory
management −
a. Keeps tracks of primary memory, i.e., what part of it are in use by whom, what part are not in
use.
b. In multiprogramming, the OS decides which process will get memory when and how much.
c. Allocates the memory when a process requests it to do so.
d. De-allocates the memory when a process no longer needs it or has been terminated.
Processor Management
In multiprogramming environment, the OS decides which process gets the processor when and for how
much time. This function is called process scheduling. An Operating System does the following activities
for processor management −
Keeps tracks of processor and status of process. The program responsible for this task is
known as traffic controller.
Device Management
An Operating System manages device communication via their respective drivers. It does the following
activities for device management −
Keeps tracks of all devices. Program responsible for this task is known as the I/O
controller.
Decides which process gets the device when and for how much time.
De-allocates devices.
Keeps track of information, location, uses, status etc. The collective facilities are often
known as file system.
Pre-requisite Keywords
Problem statement-
A problem statement is usually one or two sentences to explain the problem you are going to address
by programming.
Algorithm:
It’s an organized logical sequence of the actions or the approach towards a particular problem. A
programmer implements an algorithm to solve a problem. Algorithms are expressed using natural
verbal but somewhat technical annotations.
Example: Algorithm to calculate factorial
1. Start
2. Input number N (for which we want to calculate factorial.)
3. Let M=1 and F=1.
4. F=F*M.
5. Is M=N?
6. If NO then M=M+1 and go to step 3.
7. If YES then output F
8. End
Input specified-The input is the data to be transformed during the computation to produce the output. Input
precision requires that you know what kind of data, how much and what form the data should be required
for algorithm.
Output specified-The output is the data resulting from the computation (your intended result). Output
precision also requires that you know what kind of data, how much and what form the output should be (or
even if there will be any output at all!)
Definiteness-Each statement of algorithm should be clear, well defined and precise in nature.
Effectiveness-For an algorithm to be effective, it means that all those steps that are required to get to output
MUST BE DOABLE!
What is pseudocode?
Pseudo code:
a. It’s simply an implementation of an algorithm in the form of annotations and informative
text written in plain English. It has no syntax like any of the programming language and thus
can’t be compiled or interpreted by the computer.
b. Pseudocode is an artificial and informal language that helps programmers develop
algorithms. Pseudocode is a "text-based" detail (algorithmic) design tool.
c. The rules of Pseudocode are reasonably straightforward. All statements showing
"dependency" are to be indented. These include while, do, for, if, switch. Examples below will
illustrate this notion.
d. It is a methodology that allows the programmer to represent the implementation of an
algorithm. Simply, we can say that it’s the cooked up representation of an algorithm.
e. Often at times, algorithms are represented with the help of pseudo codes as they can be
interpreted by programmers no matter what their programming background or knowledge is.
f. Pseudo code, as the name suggests, is a false code or a representation of code which can
be understood by even a layman with some school level programming knowledge.
Advantages of Pseudocode
Improves the readability of any approach. It’s one of the best approaches to start implementation
of an algorithm.
Acts as a bridge between the program and the algorithm or flowchart. Also works as a rough
documentation, so the program of one developer can be understood easily when a pseudo code is
written out. In industries, the approach of documentation is essential. And that’s where a pseudo-
code proves vital.
The way the if-else, for, while loops are indented in a program, indent the statements likewise, as
it helps to comprehend the decision control and execution mechanism. They also improve the
readability to a great extent.
Example:
if "1"
print response
"I am case 1"
if "2"
print response
"I am case 2"
Use appropriate naming conventions. The human tendency follows the approach to follow what we
see. If a programmer goes through a pseudo code, his approach will be the same as per it, so the
naming must be simple and distinct.
Elaborate everything which is going to happen in the actual code. Don’t make the pseudo code
abstract.
Use standard programming structures such as ‘if-then’, ‘for’, ‘while’, ‘cases’ the way we use it in
programming.
Check whether all the sections of a pseudo code is complete, finite and clear to understand and
comprehend.
Don’t write the pseudo code in a complete programmatic manner. It is necessary to be simple to
understand even for a layman or client, hence don’t incorporate too many technical terms.
Examples of pseudocode
*For students: Can you guess for what purpose the following pseudocode has been written?
1.
If student's grade is greater than or equal to 60
Print "passed"
Else
Print "failed"
3.
Initialize total to zero
Initialize counter to zero
Input the first grade
while the user has not as yet entered the sentinel
add this grade into the running total
add one to the grade counter
input the next grade (possibly the sentinel)
if the counter is not equal to zero
set the average to the total divided by the counter
print the average
else
print 'no grades were entered'
4.
initialize passes to zero
initialize failures to zero
initialize student to one
while student counter is less than or equal to ten
input the next exam result
if the student passed
add one to passes
else
add one to failures
add one to student counter
print the number of passes
print the number of failures
if eight or more students passed
print "raise tuition"
A flowchart is a type of diagram that represents an algorithm or process, showing the steps as boxes of
various kinds, and their order by connecting these with arrows. This diagrammatic representation can give
a step-by-step solution to a given problem.
Algorithm:
(i) Step 1: Read amount,
(ii) Step 2: Read years,
(iii) Step 3: Read rate,
(iv) Step 4: Calculate the interest with formula "Interest=Amount*Years*Rate/100
(v) Step 5: Print interest,
Flowchart:
Algorithm:
(i) Step 1: Read number N,
(ii) Step 2: Set remainder as N modulo 2,
(iii) Step 3: If remainder is equal to 0 then number N is even, else number N is odd,
(iv) Step 4: Print output.
Algorithm:
(i) Step 1: Input grades of 4 courses M1, M2, M3 and M4,
(ii) Step 2: Calculate the average grade with formula "Grade=(M1+M2+M3+M4)/4"
(iii) Step 3: If the average grade is less than 60, print "FAIL", else print "PASS".
Flowchart:
Topic Programming Basics: Concept of assembler, compiler, interpreter, loader and linker
Structure of C program, First C program
CO Covered To translate the algorithms to programs & execution in C language
Lecture Objective To get the idea of programing language translators and structure of C program
Lecture structure Pre-requisite Keywords
Programming Language Translators
Structure of C Program
First C program
Related Questions 1. Explain structure of a C program with example.
2. Explain following terms-a)Assembler b)Interpreter c)Loader d)Linker e)Compiler
Extra topics for fast History of computer languages, Compiler design issues, Types of compiler
learners/Topics beyond
syllabus
Pre-requisite Keywords
Computer Language-
A language that is acceptable to a computer system is called a computer language or
programming language and the process of creating a sequence of instructions in such a language is
called programming or coding.
A program is a set of instructions, written to perform a specific task by the computer. A set of large
program is called software. To develop software, one must have knowledge of a programming
language.
Before moving on to any programming language, it is important to know about the various types
of languages used by the computer.
Just as every language like English, Hindi has its own grammatical rules; every computer language
is also bounded by rules known as syntax of that language. The user is bound by that syntax while
communicating with the computer system.
The term low level highlights the fact that it is closer to a language which the machine
understands. The low level languages are classified as:
Machine Language:
This is the language (in the form of 0’s and 1’s, called binary numbers) understood
directly by the computer. It is machine dependent. It is difficult to learn and even more difficult
to write programs.
Assembly Language:
This is the language where the machine codes comprising of 0’sand 1’s are substituted
by symbolic codes (called mnemonics) to improve their understanding. It is the first step to
improve programming structure. Assembly language programming is simpler and less time
As you know that high level language is machine independent and assembly language though it is
machine dependent yet mnemonics that are being used to represent instructions are not directly
understandable by the machine. Hence to make the machine understand the instructions provided by
both the languages, programming language instructors are used.
They transform the instruction prepared by programmers into a form which can be interpreted &
executed by the computer. Flowing are the various tools to achieve this purpose:
Compiler: The software that reads a program written in high level language and translates it into an
equivalent program in machine language is called as compiler. The program written by the programmer in
high level language is called source program and the program generated by the compiler after translation is
called as object program.
Interpreter: it also executes instructions written in a high level language. Both complier & interpreter have
the same goal i.e. to convert high level language into binary instructions, but their method of execution is
different. The complier converts the entire source code into machine level program, while the interpreter
takes 1 statement, translates it, executes it & then again takes the next statement.
Assembler: The software that reads a program written in assembly language and translates it into an
equivalent program in machine language is called as assembler.
Structure of C Program
The structure of a C program is a protocol (rules) to the programmer, which he has to follow while
writing a C program. The general basic structure of C program is shown in the figure below.
First C program
Based on the structure, we can sketch a C program.
Example:
/* this program accepts a number & displays it to the user*/
#include <stdio.h>
void main(void)
{
int number;
printf( "Please enter a number: " );
scanf( "%d", &number );
printf( "You entered %d", number );
return 0;
}
#include
The part of the compiler which actually gets your program from the source file is called the
preprocessor.
#include <stdio.h>
#include is a pre-processor directive. It is not really part of our program, but instead it is an
instruction to the compiler to make it do something. It tells the C compiler to include the contents of a
file (in this case the system file called stdio.h).
The compiler knows it is a system file, and therefore must be looked for in a special place, by the
fact that the filename is enclosed in <> characters
void
This literally means that this means nothing. In this case, it is referring to the function whose name
follows.Void tells to C compiler that a given entity has no meaning, and produces no error.
Main
In this particular example, the only function in the program is called main. A C program is typically
made up of large number of functions. Each of these is given a name by the programmer and they refer
to each other as the program runs.C regards the name main as a special case and will run this function
first i.e. the program execution starts from main. A parameter to a function gives the function something
to work on.
{ (Brace)
This is a brace (or curly bracket). As the name implies, braces come in packs of two - for every open
brace there must be a matching close one. Braces allow us to group pieces of program together, often
called a block. A block can contain the declaration of variable used within it, followed by a sequence of
program statements. In this case the braces enclose the working parts of the function main.
;( semicolon)
The semicolon marks the end of the list of variable names, and also the end of that declaration
statement.
All statements in C programs are separated by ";" (semicolon) characters. The ";" character is
actually very important. It tells the compiler where a given statement ends. If the compiler does not find
one of these characters where it expects to see one, then it will produce an error.
scanf
In other programming languages, the printing and reading functions are a part of the language. In C
this is not the case; instead they are defined as standard functions which are part of the language
specification, but are not a part of the language itself. The standard input/output library contains a
number of functions for formatted data transfer; the two we are going to use are scanf (scan formatted)
and printf (print formatted).
printf
The printf function is the opposite of scanf. It takes text and values from within the program and
sends it out onto the screen. Just like scanf, it is common to all versions of C and just like scanf, it is
described in the system file stdio.h.The first parameter to a printf is the format string, which contains
text, value descriptions and formatting instructions.
Extra topics for fast Explore Floating exception error,Parse error ,Implicit declaration error,Parsing
learners/Topics beyond
syllabus
Pre-requisite Keywords
Source File- This file contains the source code of the program. The file extension of any c file is .c.
The file contains C source code that defines the main function & maybe other functions.
Header File- A header file is a file with extension .h which contains the C function declarations and
macro definitions and to be shared between several source files.
Object File- An object file is a file containing object code, with an extension .obj, meaning relocatable
format machine code that is usually not directly executable. Object files are produced by an assembler,
compiler, or other language translator, and used as input to the linker, which in turn typically generates
an executable or library by combining parts of object files.
Executable File- The binary executable file is generated by the linker. The linker links the various
object files to produce a binary file that can be directly executed.
IDE Introduction
IDE can improve the productivity of a programmer or developer because of its fast setup and various
tools. Without this, a programmer takes a lot of time deciding various tools to use for their tasks.
The source code editor is something where programmers can write the code, whereas, build automation
tool is used by the programmers for compiling the codes and the debugger is used to test or debug the
program in order to resolve any errors in the code. Furthermore, these IDEs also comes with additional
features like object and data modeling, unit testing, source code library, and a lot more.
As a teacher I am going to use following IDE (Because this is the lab setup@GCET and you can
relate your learning easily)
But, you can use any one of the following integrated development environment (IDE) for C
programming-
Object code is the output of a compiler after it processes the source code. The object code is usually
a machine code, also called a machine language, which can be understood directly by a specific type
of CPU (central processing unit), such as x86 (i.e., Intel-compatible) or PowerPC. However, some
compilers are designed to convert source code into an assembly language or some other another
programming language.
Executable (also called the Binary) is the output of a linker after it processes the object code. A
machine code file can be immediately executable (i.e., runnable as a program), or it might
require linking with other object code files (e.g. libraries) to produce a complete executable program.
Error is an illegal operation performed by the user which results in abnormal working of the program.
Programming errors often remain undetected until the program is compiled or executed. Some of the
errors inhibit the program from getting compiled or executed. Thus errors should be removed before
compiling and executing.
The most common errors can be broadly classified as follows.
Type of errors
Syntax errors:
Errors that occur when you violate the rules of writing C/C++ syntax are known as syntax errors. This
compiler error indicates something that must be fixed before the code can be compiled. All these errors
are detected by compiler and thus are known as compile-time errors.
Most frequent syntax errors are:
1. Missing Parenthesis (})
2. Printing the value of variable without declaring it
3. Missing semicolon like this:
Error:
Run-time Errors:
Errors which occur during program execution (run-time) after successful compilation are called
run-time errors. One of the most common run-time error is division by zero also known as Division
error. These types of error are hard to find as the compiler doesn’t point to the line at which the
error occurs.
For more understanding run the example given below.
In the given example, there is Division by zero error. This is an example of run-time error i.e errors
occurring while running the program.
Logical Errors:
On compilation and execution of a program, desired output is not obtained when certain input values
are given. These types of errors which provide incorrect output but appears to be error free are called
logical errors. These are one of the most common errors done by beginners of programming.
These errors solely depend on the logical thinking of the programmer and are easy to detect if we
follow the line of execution and determine why the program takes that path of execution.
Topic Components of C language , Fundamental Data Types, Variables and Memory locations,
Type Conversion
CO Covered To translate the algorithms to programs & execution in C language
Lecture Objective To get the idea of different components of C language
Lecture structure Components of C Language
Fundamental Data Types
Type Casting
Components of C language
Every language has some basic elements & grammatical rules. Before starting with programming, we
should be acquainted with the basic elements that build the language.
Character Set
Communicating with a computer involves speaking the language the computer understands. In C, various
characters have been given to communicate. Character set in C consists of;
Keywords
Keywords are the words whose meaning has already been explained to the C compiler. The
keywords cannot be used as variable names because if we do so we are trying to assign a new meaning
to the keyword, which is not allowed by the computer. There are only 32 keywords available in C.
Below figure gives a list of these keywords for your ready reference.
Data Type
In the C programming language, data types refer to a domain of allowed values & the operations
that can be performed on those values. The type of a variable determines how much space it occupies
in storage and how the bit pattern stored is interpreted. There are 4 fundamental data types in C, which
are- char, int, float &, double. Char is used to store any single character; int is used to store any integer
value, float is used to store any single precision floating point number & double is used to store any
double precision floating point number.
We can use 2 qualifiers with these basic types to get more types.
Sign qualifier- signed & unsigned
Size qualifier- short & long
The data types in C can be classified as follows:
Variables-
Variables are names that are used to store values. It can take different values but one at a time. A
data type is associated with each variable & it decides what values the variable can take. Variable
declaration requires that you inform C of the variable's name and data type.
Syntax – data type variable name;
Eg:int page_no;
char grade;
float salary;
long y;
Declaring Variables:
There are two places where you can declare a variable:
After the opening brace of a block of code (usually at the top of a function)
Before a function name (such as before main() in the program) Consider various examples:
Initialization of Variables
When a variable is declared, it contains undefined value commonly known as garbage value. If we
want we can assign some initial value to the variables during the declaration itself. This is called
initialization of the variable.
Eg-int pageno=10;
Expressions
An expression consists of a combination of operators, operands, variables & function calls. An
expression can be arithmetic, logical or relational. Here are some expressions:
a+b – arithmetic operation
a>b- relational operation a
== b - logical operation
func (a,b) – function call
Statements
Statements are the primary building blocks of a program. A program is a series of statements with
some necessary punctuation. A statement is a complete instruction to the computer. In C, statements
are indicated by a semicolon at the end. a semicolon is needed to identify instructions that truly are
statements.
printf
(
"Hello, World! \n"
)
;
Semicolons
In a C program, the semicolon is a statement terminator. That is, each individual statement must be ended
with a semicolon. It indicates the end of one logical entity.
Whitespace in C
A line containing only whitespace, possibly with a comment, is known as a blank line, and a C compiler
totally ignores it.
Whitespace is the term used in C to describe blanks, tabs, newline characters and comments. Whitespace
separates one part of a statement from another and enables the compiler to identify where one element in a
statement, such as int, ends and the next element begins. Therefore, in the following statement −
int age;
There must be at least one whitespace character (usually a space) between int and age for the compiler to
be able to distinguish them. On the other hand, in the following statement −
Type casting /type conversion is a way to convert a variable from one data type to another data
type. For example, if you want to store a long value into a simple integer then you can typecast
long to int.
You can convert values from one type to another explicitly using the cast operator. There are two
types of type casting in c languages that are implicit conversions and Explicit Conversions.
New data type should be mentioned before the variable name or value in brackets which to be
typecast.
Example-
In the below C program, 7/5 alone will produce integer value as 1.So, type cast is done before
division to retain float value (1.4).
#include <stdio.h>
int main ()
{
float x;
x = (float) 7/5;
printf(“%f”,x);
}
Output:
1.400000
Types of typecasting in C
Implicit Conversion
Explicit Conversion
Implicit Conversion
Implicit conversions do not require any operator for converted. They are automatically performed when
a value is copied to a compatible type in the program.
#include<stdio.h>
#include<conio.h>
void main()
{
int i=20;
double p;
clrscr();
p=i; // implicit conversion
Output:-
implicit value is 20.
Explicit Conversion
In C language, Many conversions, especially those that imply a different interpretation of the value,
require an explicit conversion.
Example :-
#include<stdio.h>
#include<conio.h>
void main()
{
int i=20;
short p;
clrscr();
p = (short) i; // Explicit conversion
printf(“Explicit value is %d”,p);
getch();
}
Output:-
Explicit value is 20.
Standard I/O in C
When we say Input, it means to feed some data into a program. An input can be given in the form of a file
or from the command line. C programming provides a set of built-in functions to read the given input and
feed it to the program as per requirement.
When we say Output, it means to display some data on screen, printer, or in any file. C programming
provides a set of built-in functions to output the data on the computer screen as well as to save it in text or
binary files.
File
Standard File Device
Pointer
Standard input stdin Keyboard
Standard output stdout Screen
Standard error stderr Your screen
#include <stdio.h>
int main( ) {
int c;
printf( "Enter a value :");
c = getchar( );
return 0;
}
When the above code is compiled and executed, it waits for you to input some text. When you enter a text
and press enter, then the program proceeds and reads only a single character and displays it as follows −
The int puts(const char *s) function writes the string ‘s’ and ‘a’ trailing newline to stdout.
#include <stdio.h>
int main( ) {
char str[100];
return 0;
}
When the above code is compiled and executed, it waits for you to input some text. When you enter a text
and press enter, then the program proceeds and reads the complete line till end, and displays it as follows −
The int printf(const char *format, …) function writes the output to the standard output stream stdout and
produces the output according to the format provided.
The format can be a simple constant string, but you can specify %s, %d, %c, %f, etc., to print or read strings,
integer, character or float respectively. There are many other formatting options available which can be
used based on requirements. Let us now proceed with a simple example to understand the concepts better -
#include <stdio.h>
int main( ) {
char str[100];
int i;
return 0;
}
When the above code is compiled and executed, it waits for you to input some text. When you enter a text
and press enter, then program proceeds and reads the input and displays it as follows −
Here, it should be noted that scanf() expects input in the same format as you provided %s and %d, which
means you have to provide valid inputs like “string integer”. If you provide “string string” or “integer
integer”, then it will be assumed as wrong input. Secondly, while reading a string, scanf() stops reading as
soon as it encounters a space, so “this is test” are three strings for scanf().
#include<stdio.h>
int main()
{printf("Case 1:%6d\n",9876);
/* Prints the number right justified within 6 columns */
printf("Case 2:%3d\n",9876);
/* Prints the number to be right justified to 3 columns but, there are 4 digits so number is not right
justified */
printf("Case 3:%.2f\n",987.6543);
/* Prints the number rounded to two decimal places */
printf("Case 4:%.f\n",987.6543);
/* Prints the number rounded to 0 decimal place, i.e, rounded to integer */
printf("Case 5:%e\n",987.6543);
/* Prints the number in exponential notation (scientific notation) */
return 0;
}
Output
Case 1: 9876
Case 2:9876
Case 3:987.65
Case 4:988
Extra topics for fast CPU registers,Microprocessors,Types of CPU registers,Cost of CPU registers
learners/Topics beyond
syllabus
Storage classes
Generally, there are two kinds of locations in a computer where such a value can be present, these are Memory
and CPU registers. The storage class of a particular variable determines in which of the above two locations
the variable’s value is stored.
There are four properties by which storage class of a variable can be recognized. These are scope, default
initial value, scope and life.
A variable’s storage class reveals the following things about a variable
(i) Where the variable is stored.
(ii) What is the initial value of the variable if the value of the variable is not specified?
(iii) What is the scope of the variable (To which function or block the variable is available)?
(iv) What is the life of particular variable (Up to what extent the variable exists in a program)?
In c there are four types of storage class. They are: 1. Auto 2. Register 3. Static 4. Extern
Visibility of a variable in c:
Visibility means accessibility. Up to witch part or area of a program, we can access a variable, that
area or part is known as visibility of that variable. For example: In the following figure yellow color
represents visibility of variable a.
Scope of a variable in c:
Meaning of scope is to check either variable is alive or dead. Alive means data of a variable has not
destroyed from memory. Up to which part or area of the program a variable is alive, that area or part
is known as scope of a variable. There are four type of scope in c:
1. Block scope.
Example:
auto int i;
For example loop counters are declared as register variables, which are defined as follows:
int main()
{
register int a;
for(a=0;i<50000;i++)
printf(“%d\t”,a);
return 0;
In the above program, variable a was used frequently as a loop counter so the variable a is defined as a
register variable. Register is a not a command but just a request to the compiler to allocate the memory for the
variable into the register. If free registers are available than memory will be allocated in to the registers. And if
there are no free registers then memory will be allocated in the RAM only (Storage is in memory i.e. it will act
as automatic variable).
Every type of variables can be stored in CPU registers. Suppose the microprocessor has 16 bit registers then
they can’t hold a float or a double value which requires 4 and 8 bytes respectively.But if you use register storage
class for a float or double variable then you will not get any error message rather the compiler will treat the float
and double variable as be of automatic storage class(i.e. Will treat them like automatic variables).
Now look at the previous program with k is declared as static instead of automatic.
void test();
void main()
{
test();
test();
test();
}
void test()
{
static int k=10;
printf(“%d\n”,k);
k++;
}
Output:10 11 12
Here in the above program the output is 10, 11, 12, because if a variable is declared as static then it is
initialized only once and that variable will never be initialized again. Here variable k is declared as static, so
when test() is called for the first time k value is initialized to 10 and its value is incremented by 1 and becomes
11. Because k is static its value persists. When test() is called for the second time k is not reinitialized to 10
instead its old value 11 is available. So now 11 is get printed and it value is incremented by 1 to become 12.
Similarly, for the third time when test() is called 12(Old value) is printed and its value becomes 13 when executes
the statement ‘k++;’
So the main difference between automatic and static variables is that static variables are initialized to zero if
not initialized but automatic variables contain an unpredictable value(Garbage Value) if not initialized and static
variables does not disappear when the function is no longer active , their value persists, i.e. if the control comes
back to the same function again the static variables have the same values they had last time.
General advice is avoid using static variables in a program unless you need them, because their values are
kept in memory when the variables are not active which means they occupies space in memory that could
otherwise be used by other variables.
So if a variable is to be used by many functions and in different files can be declared as external variables.
The value of an uninitialized external variable is zero. The declaration of an external variable declares the type
and name of the variable, while the definition reserves storage for the variable as well as behaves as a declaration.
The keyword extern is specified in declaration but not in definition. Now look at the following four statements
1. auto int a;
2. register int b;
3. static int c;
4. extern int d;
Out of the above statements first three are definitions where as the last one is a declaration.
Suppose there are two files and their names are File1.c and File2.c respectively. Their contents are as
follows:
File1.c
int n=10;
void hello()
{
printf(“Hello”);
}
File2.c
extern int n;
extern void hello();
In the above program File1.obj+ File2.obj=File2.exe and in File2.c value of n will be 10.
Extra topics for fast Examples of increment and decrement (Pre/Post) operators on different IDEs.
learners/Topics beyond Working of Bitwise operators via program
syllabus
Operators-
An operator is a symbol that tells the compiler to perform specific mathematical or logical
manipulations. Types are-
Logical Operators:
Assume variable A holds 1 and variable B holds 0, then:
Operator Description Example
&& Called Logical AND operator. If both the operands are nonzero, then condition (A && B)
becomes true. is
false.
|| Called Logical OR Operator. If any of the two operands is non-zero, then condition (A || B) is
becomes true. true.
! Called Logical NOT Operator. Use to reverses the logical state of its operand. If a !(A && B)
condition is true then Logical NOT operator will make false. is true.
Bitwise Operators
Bitwise operator works on bits and performs bit-by-bit operation. These operators can operate upon int
and char but not on float and double..Bit wise operators in C language are; & (bitwise AND), | (bitwise
OR), ~ (bitwise OR), ^ (XOR), << (left shift) and >> (right shift).The truth tables for &, |, and ^ are as
follows:
P Q p&q p|q p^q
0 0 0 0 0
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1
Conditional Operators (? :)
Conditional operators are used in decision making in C programming, i.e, executes different statements
according to test condition whether it is either true or false.
Syntax of conditional operators;
conditional_expression?expression1:expression2
If the test condition is true (that is, if its value is non-zero), expression1 is returned and if false expression2
is returned.
y = ( x> 5 ? 3 : 4 ) ;this statement will store 3 in y if x is greater than 5, otherwise it will store 4 in y.
Misc Operators:
There are few other operators supported by c language.
Operator Description Example
It is a unary operator which is used in
finding the size of data type, constant, sizeof(a), where a is integer, will
sizeof() arrays, structure etc. return 4.
&a; will give actual address of
& Returns the address of a variable. the variable.
* Pointer to a variable. *a; will pointer to a variable.
Related Questions 1. What do you mean by operator precedence and associativity? Explain with examples.
2. What will be the output of the following code?
void main( )
{
int a=5,b=6,c;
c=a++>b&&++b<10||b++;
printf("%d%d%d",a,b,c);
}
3. If int a = 2 , b = 3, x = 0; Find the value of x = (++a, b+=a).
4. Find the value of Y (assume Y is integer data type) Y=4 * 2 / 4 – 6 /2 + 3 % 2 *
6 / 2 + 2 > 2 && 4 != 2.
5. Find the output of the statement printf("%d%d%d",n++,++n,--n);if n=3.
Extra topics for fast Solve at least 10 example of expression solving which includes logical
learners/Topics beyond operator,bitwise operator, assignment operator from any book or from internet.
syllabus
Operators Precedence in C
Operator precedence determines the grouping of terms in an expression. This affects how an expression is
evaluated. Certain operators have higher precedence than others; for example, the multiplication operator has
higher precedence than the addition operator.
For example x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher precedence than +,
so it first gets multiplied with 3*2 and then adds into 7.For Example-
Solution: In this case, the order of evaluation of operators will be parentheses ( () ), relational operators
(<, >), AND ( && ) operator, OR ( || ) operator.
(age < 12 && height < 48) || (age > 65 && height > 72)
1
=> (10 < 12 && 45 < 48) || (10 > 65 && 45 > 72)
2
=> (1 && 1) || (10 > 65 && 45 > 72)
3
=> 1 || (10 > 65 && 45 > 72)
4
=> 1 || (0 && 0)
5
=> 1 || 0
6
=> 1
7
Solution: In this case, the order of evaluation of operators will be parentheses ( () ), Modular division
(%), Relational operators (==, !=) AND ( && ) operator, OR ( || ) operator.
Control Statements-
Control statements enable us to specify the order in which the various instructions in the program are to be
executed. They define how the control is transferred to other parts of the program. Control statements are
classified in the following ways:
if(boolean_expression)
{ /* statement(s) will execute if the Boolean expression is true */
}
If the Boolean expression evaluates to true then the block of code inside the if statement will be
executed. If boolean expression evaluates to false then the first set of code after the end of the if
statement (after the closing curly brace) will be executed. C programming language assumes any
non-zero and non-null values as true and if it is either zero or null then it is assumed as false value.
Flow Diagram:
Example:
#include <stdio.h>
int main ()
{ int a = 10;
if( a < 20 )
{ Printf("a is less than 20\n" );
}
Printf("value of a is : %d\n", a);
}
When the above code is compiled and executed, it produces following result:
a is less than 20;
value of a is : 10
if(boolean_expression)
{ /* statement(s) will execute if the boolean expression is true */
}
else
{ /* statement(s) will execute if the boolean expression is false */
}
If the Boolean expression evaluates to true then the if block of code will be executed otherwise else
block of code will be executed programming language assumes any non-zero and non-null values
as true and if it is either zero or null then it is assumed as false value.
Flow Diagram:
Example:
#include <stdio.h>
main ()
{ int a = 100;
if( a < 20 )
{ Printf("a is less than 20\n" );
}
else
{ Printf("a is not less than 20\n" );
} Printf("value of a is : %d\n", a);}
When the above code is compiled and executed, it produces following result:
a is not less than 20;
value of a is : 100
if( boolean_expression 1)
{ /* Executes when the Boolean expression 1 is true */
if(boolean_expression 2)
{ /* Executes when the Boolean expression 2 is true */
}
}
Example:
#include <stdio.h>
main ()
{ int a = 100;
int b = 200;
if( a == 100 )
{ if( b == 200 )
{ printf("Value of a is 100 and b is 200\n" );
}
}
printf("Exact value of a is : %d\n", a );
printf("Exact value of b is : %d\n", b );
return 0;
}
When the above code is compiled and executed, it produces following result:
Value of a is 100 and b is 200
Exact value of a is : 100
Exact value of b is : 200
A switch statement
Allows a variable to be tested for equality against a list of values. Each value is called a case, and the
variable being switched on is checked for each switch case.
Syntax:
switch(expression)
{ case constant-expression :
statement(s);
break; /* optional */
case constant-expression :
statement(s);
break; /* optional */
Flow Diagram:
Example:
main ()
{ char grade = 'B';
switch(grade)
{ case 'A' :
printf("Excellent!\n" );
break;
case 'B' :
case 'C' :
printf("Well done\n" );
break;
case 'D' :
printf("You passed\n" );
break;
case 'F' :
printf("Better try again\n" );
break;
default :
printf("Invalid grade\n" );
} printf("Your grade is %c\n", grade );
}
When the above code is compiled and executed, it produces following result:
Well done
Your grade is B
Extra topics for fast 1.Write a C program to count and print prime numbers within given range.
learners/Topics beyond 2.Write a C program to convert a 10 base number into 2 base number.(Binary)
syllabus
Program Loops and Iteration A loop statement allows us to execute a statement or group of statements
multiple times and following is the general from of a loop statement in most of the programming languages:
Example:
#include <stdio.h>
main ()
{ int a = 10;
while( a < 20 )
{
printf("value of a: %d\n", a);
a++;
}
}
When the above code is compiled and executed, it produces following result:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
Example:
#include <stdio.h>
main ()
{ int a = 10;
do
{ printf("value of a: %d\n", a);
a = a + 1;
} while ( a < 20 );
}
When the above code is compiled and executed, it produces following result:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
Example:
#include <stdio.h>
main ()
{ for( int a = 10; a < 20; a = a + 1 )
{ printf("value of a: %d\n", a);
}
}
When the above code is compiled and executed, it produces following result:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
#include <stdio.h>
int main()
{
for (int i=0; i<2; i++)
{
for (int j=0; j<4; j++)
{
printf("%d, %d\n",i ,j);
}
}
return 0;
}
Output:
0, 0
0, 1
0, 2
0, 3
1, 0
1, 1
1, 2
1, 3
In the above example we have a for loop inside another for loop, this is called nesting of loops. One of the
example where we use nested for loop is Two dimensional array.
What’s the difference between above for loop and a simple for loop?
#include <stdio.h>
int main()
{
int i,j;
for (i=1,j=1 ; i<3 || j<5; i++,j++)
{
printf("%d, %d\n",i ,j);
}
return 0;
}
Jump statements
Syntax:
Break;
Flow Diagram:
(ii) Continue statement: Causes the loop to skip the remainder of its body and immediately retest
its condition prior to reiterating. The continue statement in C programming language works
somewhat like the break statement. Instead of forcing termination, however, continue forces the
next iteration of the loop to take place, skipping any code in between. Syntax: continue;
Flow Diagram:
Example:
#include <stdio.h>
main ()
{ int a = 10;
(iii) Goto Statement: Transfers control to the labeled statement. Though it is not advised to use
goto statement in your program A goto statement in C programming language provides an
unconditional jump from the goto to a labeled statement in the same function. Syntax:
goto label;
label: statement;
Flow Diagram:
Function-
A function is a group of statements that together perform a task. Every C program has at least one function,
which is main (), and all the most trivial programs can define additional functions.
Syntax:
return type function name (type1 arg1 , type2 arg2);
OR
return type function name (type1 type2);
1. Calling function need information about called function. If called function is place before calling
function, then the declaration is not needed.
Function Definition:
2. It consists of code description and code of a function. It consists of two parts
Function header
Function coding
Function definition tells what the I/O functions are and what is going to do.
Syntax:
return type function name (type1 arg1 , type2 arg2)
{local variable; statements ;
return (expression);
}
Function definition can be placed anywhere in the program but generally placed after the main
function.Local variable declared inside the function is local to that function. It cannot be used anywhere in
the program and its existence is only within the function.Function definition cannot be nested.Return type
denote the type of value that function will return and return type is optional if omitted it is assumed to be
integer by default.
Function Categories-
There are four main categories of the functions these are as follows:
1. Function with no arguments and no return values.
2. Function with no arguments and a return value.
3. Function with arguments and no return values.
4. Function with arguments and return values.
Actual Arguments:
1. Arguments which are mentioned in the function in the function call are known as calling function.
2. These are the values which are actual arguments called to the function.
Formal Arguments:
a) Arguments which are mentioned in function definition are called dummy or formal argument.
b) These arguments are used to just hold the value that is sent by calling function.
c) Formal arguments are like other local variables of the function which are created when function
call starts and destroyed when end function.
Call by value
In call by value, original value can not be changed or modified. In call by value, when you passed
value to the function it is locally stored by the function parameter in stack memory location. If you
change the value of function parameter, it is changed for the current function only but it not change the
value of variable inside the caller method such as main().
// C program to illustrate
// call by value
#include
// Function Prototype
void swapx(int x, int y);
// Main function
int main()
{
int a = 10, b = 20;
// Pass by Values
swapx(a, b);
return 0;
}
Output:
x=20 y=10
a=10 b=20
Related Questions 1. Differentiate Call by Value and Call by Reference method of function calling.
2. Explain call by reference method of function calling with proper example.
Extra topics for fast Pointer,Address Mapping,Importance of pointer,Risks while using pointers
learners/Topics beyond
syllabus
Call by reference
In call by reference, original value is changed or modified because we pass reference (address). Here,
address of the value is passed in the function, so actual and formal arguments shares the same address
space. Hence, any value changed inside the function, is reflected inside as well as outside the function.
#include
// Function Prototype
void swapx(int*, int*);
// Main function
int main()
{
int a = 10, b = 20;
// Pass reference
swapx(&a, &b);
return 0;
}
t = *x;
*x = *y;
*y = t;
Output:
x=20 y=10
a=20 b=10
Related Questions i. Write C program to calculate factorial of any number using recursion.
ii. Write a C program to print terms of Fibonacci series up to given term.
Extra topics for fast Stack overflow,Infix/Prefix notation,Recursive function`s behavior in context of
learners/Topics beyond memory
syllabus
Recursion
When Function is call within same function is called Recursion. The function which calls same function
is called recursive function. In other word when a function calls itself then that function is
called Recursive function.
void recurse()
{ ... .. ...
recurse();
... .. ...
}
int main()
{ ... .. ...
recurse();
... .. ...
}
#include <stdio.h>
int sum(int n);
int main() {
int number, result;
result = sum(number);
int sum(int n) {
if (n != 0)
// sum() function calls itself
return n + sum(n-1);
else
return n;
}
Output
Disadvantage of Recursion
1. It is a very slow process due to stack overlapping.
2. Recursive programs can create stack overflow.
3. Recursive functions can create as loops.
Related Questions 1. How to declare an array? Explain about various operations of an array.
2. Write a ‘C’ program to read in 10 integers and print their average, minimum and
maximum numbers.
Extra topics for fast Data structure,Derived data types
learners/Topics beyond
syllabus
Introduction
A data structure is the way data is stored in the machine and the functions used to access that data.
An easy way to think of a data structure is a collection of related data items.
An array is a data structure that is a collection of variables of one type that are accessed through a
common name.
Each element of an array is given a number by which we can access that element which is called
an index. It solves the problem of storing a large number of values and manipulating them.
In an Array values of same type are stored. An array is a group of memory locations related by the
fact that they all have the same name and same type. To refer to a particular location or element in
the array we specify the name to the array and position number of particular element in the array.
data_type represents the type of elements present in the array. array_name represents the name of the array.
Size represents the number of elements that can be stored in the array.
Example:
int age[100];
float sal[15];
char grade[20];
Initialization:
We can explicitly initialize arrays at the time of declaration.
Syntax:
data_type array_name[size]={value1, value2,……..valueN};
Value1, value2, valueN are the constant values known as initializers, which are assigned to the array elements
one after another.
Example:
int marks[5]={10,2,0,23,4};
The values of the array elements after this initialization are: marks[0]=10, marks[1]=2, marks[2]=0,
marks[3]=23, marks[4]=4
Note-:
In 1-D arrays it is optional to specify the size of the array. If size is omitted during initialization, then the
compiler assumes the size of array equal to the number of initializers. Example:int marks []={10,2,0,23,4};Here
the size of array marks is initialized to 5.
We can’t copy the elements of one array to another array by simply assigning it. Example:
Arrays that we have considered up to now are one dimensional array, a single line of elements. Often data come
naturally in the form of a table, e.g. spreadsheet, which need a two-dimensional array.
Declaration:
The syntax is same as for 1-D array but here 2 subscripts are used.
Syntax:
data_type array_name[rowsize][columnsize];
Rowsize specifies the no.of rows
Columnsize specifies the no.of columns.
Example:
int a[4][5];
This is a 2-D array of 4 rows and 5 columns. Here the first element of the array is a[0][0] and last element of the
array is a[3][4] and total no.of elements is 4*5=20.
Initialization:
2-D arrays can be initialized in a way similar to 1-D arrays.
Example:
int m[4][3]={1,2,3,4,5,6,7,8,9,10,11,12};
The values are assigned as follows:
Processing:
For processing of 2-D arrays we need two nested for loops. The outer loop indicates the rows and the inner loop
indicates the columns.
Example:
int a[4][5];
Reading values in a
for(i=0;i<4;i++)
for(j=0;j<5;j++)
scanf(“%d”,&a[i][j]);
Displaying values of a
for(i=0;i<4;i++)
for(j=0;j<5;j++)
printf(“%d”,a[i][j]);
Rule: Addition of two matrixes is only possible if both matrixes are of same size. Suppose two
matrixes A and B is of same size m X n
Sum of two marixes is defined as
(A + B)ij = Aij + Bij
Where 1 ≤ i ≤ m and 1 ≤ j ≤ n
For example:
Suppose two matrixes A and B of size of 2 X 3 is as follow:
Related Questions i. Write a user defined function that receives an array of 10 elements and return the
biggest element of that array.
ii. Write a user defined function that accept 10 integer element, count the number of
prime numbers and return the total number of prime numbers present in that array.
As we already know in this type of function call, the actual parameter is copied to the formal parameters.
#include <stdio.h>
void disp( char ch)
{
printf("%c ", ch);
}
int main()
{
char arr[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'};
for (int x=0; x<10; x++)
{
/* I’m passing each element one by one using subscript*/
disp (arr[x]);
}
return 0;
}
Output:a b c d e f g h i j
#include <stdio.h>
void disp( int *num)
{
printf("%d ", *num);
}
int main()
{
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
for (int i=0; i<10; i++)
{
/* Passing addresses of array elements*/
disp (&arr[i]);
}
return 0;
}
Output:1 2 3 4 5 6 7 8 9 0
In the above example, we have passed the address of each array element one by one using a for loop in C.
However you can also pass an entire array to a function like this:
Note: The array name itself is the address of first element of that array. For example if array name is arr
then you can say that arr is equivalent to the &arr[0].
#include <stdio.h>
void myfuncn( int *var1, int var2)
{
/* The pointer var1 is pointing to the first element of
* the array and the var2 is the size of the array. In the
* loop we are incrementing pointer so that it points to
* the next element of the array on each increment.
*
*/
for(int x=0; x<var2; x++)
{
printf("Value of var_arr[%d] is: %d \n", x, *var1);
/*increment pointer for next element fetch*/
var1++;
}
}
int main()
{
int var_arr[] = {11, 22, 33, 44, 55, 66, 77};
myfuncn(var_arr, 7);
return 0;
}
Output:
Topic Strings
CO Covered To use arrays, pointers and structures to develop algorithms and programs.
Lecture Objective To understand the the concept of string in C language
Lecture structure What is string?
Fundamentals of string
How to read string in C language?
How to write string in C language?
Some predefined functions used in string manipulations
Related Questions i. Write a program in C that reads the two strings of length at least 7, then concatenate
these strings.
ii. Explain at least 6 predefined function used in handling strings in C language.
Extra topics for fast *Design user defined function to copy string.
learners/Topics beyond *Design user defined function co concatenate two strings.
syllabus
String Fundamentals-
A string is a series of characters treated as a single unit. A string may include letters, digits and various
special characters such as +, -, *, / and $. String literals or string constants in C are written in double
quotation marks as follows:
“1000 Main Street” (a street address)
In C language strings are stored in array of char type along with null terminating character ‘\0’ at the end.
When sizing the string array we need to add plus one to the actual size of the string to make space for the
null terminating character, ‘\0’.
syntax:
char fname[4];
The above statement declares a string called fname that can take up to 3 characters. It can be indexed just
as a regular array as well.
fname[]={‘t’,’w’,’o’};
If we want to print a string from a variable, such as four name string above we can do this.
e.g., printf(“First name:%s”,fname);
We can insert more than one variable. Conversion specification %s is used to insert a string and then go to
each %s in our string, we are printing.
Reading strings:
If we declare a string by writing
char str[100];
then str can be read from the user by using three ways;
Using scanf() function
The string can be read using scanf() by writing scanf(“%s”,str);
Although the syntax of scanf() function is well known and easy to use, the main pitfall with this
function is that it terminates as soon as it finds a blank space. For example, if the user enters
Hello World, then str will contain only Hello. This is because the moment a blank space is
encountered, the string is terminated by the scanf() function.
Example:
char str[10];
printf(“Enter a string\n”); scanf(“%s”,str);
gets() is a function that overcomes the drawbacks of scanf(). The gets() function takes the starting
address of the string which will hold the input. The string inputted using gets() is automatically
terminated with a null character.
Example:
char str[10];
printf(“Enter a string\n”); gets(str);
The string can also be read by calling the getchar() repeatedly to read a sequence of single
characters (unless a terminating character is encountered) and simultaneously storing it in a character array
as follows:
int i=0;
char str[10],ch;
getchar(ch);
while(ch!=’\0’)
{
str[i]=ch; // store the read character in str
i++;
getch(ch); // get another character
}
str[i]=’\0’; // terminate str with null character
Writing string
We can use width and precision specification along with %s. The width specifies the minimum output field
width and the precision specifies the maximum number of characters to be displayed. Example:
printf(“%5.3s”,str);
this statement would print only the first three characters in a total field of five charaters; also these three
characters are right justified in the allocated width.
It terminates the line with a newline character (‘\n’). It returns an EOF(-1) if an error occurs and returns a
positive number on success.
int i=0;
char str[10];
while(str[i]!=’\0’)
{putchar(str[i]); // print the character on the screen
i++;
}
strcpy():
It is used to copy one string to another string. The content of the second string is copied to the content of
the first string.
Syntax:
strcpy (string 1, string 2);
Example:
char mystr[10];
mystr = “Hello”; // Error! Illegal !!! Because we are assigning the value to mystr which is not possible in
case of an string. We can only use "=" at declarations of C-String.
strcpy(mystr, “Hello”);
It sets value of mystr equal to “Hello”.
strcat():
It is used to concatenate i.e, combine the content of two strings.
Syntax:
strcat(string 1, string 2);
Example:
char fname[30]={“bob”};
char lname[]={“by”};
printf(“%s”, strcat(fname,lname));
Output:
bobby.
strlen():
It is used to return the length of a string.
Syntax:
int strlen(string);
Example:
char fname[30]={“bob”};
int length=strlen(fname);
It will return 3
strchr():
It is used to find a character in the string and returns the index of occurrence of the character for the first
time in the string.
Syntax:
strchr(cstr);
Example:
char mystr[] = "This is a simple string";
char pch = strchr(mystr,‘s’);
Related Questions i.Write a program using structures to read and display the information about an employee.
ii.Write a program to read, display, add and subtract two complex numbers.
iii.Write a program to enter two points and then calculate the distance between them.
iv.Write a program to define a structure named employee having empid, name and
designation. Use this structure to store the data in a file named "employee.dat. Once all the
records are entered display the employee details stored in a file.
v.Create the database of students in C having the following attributes: Roll_no, Stud_name,
Stud_address; Stud_city, Stud_PINCode, Stud_Semester, Rank, and Branch. Also write the
program in C to enter the data for 100 students in any order and then display the list of
students for a given branch and Semester on display.
Extra topics for fast Develop structures for Library Management System,Hostel Management System,Hospital
learners/Topics beyond Management System
syllabus
Definition
A Structure is a user defined data type that can store related information together. The variable within a
structure are of different data types and each has a name that is used to select it from the structure. C arrays
allow you to define type of variables that can hold several data items of the same kind but structure is
another user defined data type available in C programming, which allows you to combine data items of
different kinds.
Structures are used to represent a record; suppose you want to keep track of your books in a library. You
might want to track the following attributes about each book:
1. Title
2. Author
3. Subject
4. Book ID
Structure Initialization-
Assigning constants to the members of the structure is called initializing of structure.
Syntax:
struct struct_name
{
data _type member_name1;
data _type member_name2;
} struct_var={constant1,constant2};
Declaring an array of structure is same as declaring an array of fundamental types. Since an array is a
collection of elements of the same type. In an array of structures, each element of an array is of the
structure type.
struct car
{
char make[20];
char model[30];
int year;
};
Here arr_car is an array of 10 elements where each element is of type struct car. We can use arr_car to
store 10 structure variables of type struct car. To access individual elements we will use subscript notation
([]) and to access the members of each element we will use dot (.) operator as usual.
Recall that the precedence of [] array subscript and dot(.) operator is same and they evaluates from left to
right. Therefore in the above expression first array subscript([]) is applied followed by dot (.) operator.
The array subscript ([]) and dot(.) operator is same and they evaluates from left to right. Therefore in the
above expression first [] array subscript is applied followed by dot (.) operator.
We can also initialize the array of structures using the same syntax as that for initializing arrays. Let's take
an example:
struct car
{
char make[20];
char model[30];
int year;
};
struct car arr_car[2] = {
{"Audi", "TT", 2016},
{"Bentley", "Azure", 2002}
};
Union-
Union is a collection of variables of different data types, in case of union information can only be stored In
one field at any one time.
A union is a special data type available in C that enables you to store different data types in the same
memory location.
You can define a union with many members, but only one member can contain a value at any given time.
Unions provide an efficient way of using the same memory location for multi-purpose.
Declaring Union
union union-name
{
data_type var-name;
data_type var-name;
};
The union tag is optional and each member definition is a normal variable definition, such as int i; or float
f; or any other valid variable definition. At the end of the union's definition, before the final semicolon, you
can specify one or more union variables but it is optional.
Here is the way you would define a union type named Data which has the three members i, f, and str. Now,
a variable of Data type can store an integer, a floating-point number, or a string of characters. This means
that a single variable ie. same memory location can be used to store multiple types of data. You can use any
built-in or user defined data types inside a union based on your requirement.
Enumerated Types
Enumerations are integer types that you define in a program. The definition of an enumeration begins with
the keyword enum, possibly followed by an identifier for the enumeration, and contains a list of the type's
possible values, with a name for each value:
enum [identifier] { enumerator-list };
The identifier color is the tag of this enumeration. The identifiers in the listblack, red, and so onare the
enumeration constants , and have the type int. You can use these constants anywhere within their scopeas
case constants in a switch statement, for example.
Each enumeration constant of a given enumerated type represents a certain value, which is determined
either implicitly by its position in the list, or explicitly by initialization with a constant expression. A
constant without an initialization has the value 0 if it is the first constant in the list, or the value of the
preceding constant plus one. Thus in the previous example, the constants listed have the values 0, 1, 2, 3,
4, 7, 8.
An enumerated type always corresponds to one of the standard integer types. Thus your C programs
may perform ordinary arithmetic operations with variables of enumerated types. The compiler may
select the appropriate integer type depending on the defined values of the enumeration constants. In the
previous example, the type char would be sufficient to represent all the values of the enumerated type
enum color.Different constants in an enumeration may have the same value:
enum { OFF, ON, STOP = 0, GO = 1, CLOSED = 0, OPEN = 1 };
As the preceding example also illustrates, the definition of an enumerated type does not necessarily have to
include a tag. Omitting the tag makes sense if you want only to define constants, and not declare any
variables of the given type. Defining integer constants in this way is generally preferable to using a long
list of #define directives, as the enumeration provides the compiler with the names of the constants as well
as their numeric values.
What is Searching?
Searching is the process of finding a given value position in a list of values.
It decides whether a search key is present in the data or not.
It is the algorithmic process of finding a particular item in a collection of items.
It can be done on internal data structure or on external data structure.
Searching Techniques
To search an element in a given array, it can be done in following ways:
1. Sequential Search
2. Binary Search
Sequential Search
Sequential search is also called as Linear Search.
Sequential search starts at the beginning of the list and checks every element of the list.
It is a basic and simple search algorithm.
Sequential search compares the element with all the other elements given in the list. If the element is
matched, it returns the value index, else it returns -1.
The above figure shows how sequential search works. It searches an element or value from an array till
the desired element or value is not found. If we search the element 25, it will go step by step in a sequence
The above array is sorted in ascending order. As we know binary search is applied on sorted lists
only for fast searching.For example, if searching an element 25 in the 7-element array, following figure
shows how binary search works:
Binary searching starts with middle element. If the element is equal to the element that we are searching
then return true. If the element is less than then move to the right of the list or if the element is greater
than then move to the left of the list. Repeat this, till you find an element.
Output:
Sorting-
Sorting is nothing but storage of data in sorted order, it can be in ascending or descending order. The term
Sorting comes into picture with the term Searching. There are so many things in our real life that we need
to search, like a particular record in database, roll numbers in merit list, a particular telephone number,
any particular page in a book etc.
Sorting Efficiency
There are many techniques for sorting. Implementation of particular sorting technique depends upon
situation. Sorting techniques mainly depends on two parameters. First parameter is the execution time of
program, which means time taken for execution of program.Second is the space, which means space taken
by the program.
Types of Sorting-
An internal sort is any data sorting process that takes place entirely within the main memory of a
computer. This is possible whenever the data to be sorted is small enough to all be held in the main
memory.
External sorting is a term for a class of sorting algorithms that can handle massive amounts of data.
External sorting is required when the data being sorted do not fit into the main memory of a computing
device (usually RAM) and instead they must reside in the slower external memory (usually a hard drive).
External sorting typically uses a hybrid sort-merge strategy. In the sorting phase, chunks of data small
enough to fit in main memory are read, sorted, and written out to a temporary file. In the merge phase, the
sorted sub files are combined into a single larger file.
We can say a sorting algorithm is stable if two objects with equal keys appear in the same order in sorted
output as they appear in the input unsorted array.
Bubble Sort is an algorithm which is used to sort N elements that are given in a memory for eg: an Array
with N number of elements. Bubble Sort compares all the element one by one and sort them based on their
values.
It is called Bubble sort, because with each iteration the smaller element in the list bubbles up towards the
first place, just like a water bubble rises up to the water surface.
Sorting takes place by stepping through all the data items one-by-one in pairs and comparing adjacent
data items and swapping each pair that is out of order.
Following are the steps involved in bubble sort (for sorting a given array in ascending order):
1. Starting with the first element (index = 0), compare the current element with the next element of
the array.
2. If the current element is greater than the next element of the array, swap them.
3. If the current element is less than the next element, move to the next element. Repeat Step 1.
Related Questions i- Write algorithm and C code to demonstrate Insertion sort in detail.
Extra topics for fast Search-Practical utilization of sorting techniques used in real life/software/program.
learners/Topics beyond
syllabus
Insertion sort
It is a simple sorting algorithm that builds the final sorted array (or list) one item at a time. This algorithm
is less efficient on large lists than more advanced algorithms such as quicksort, heapsort, or merge sort.
However, insertion sort provides several advantages:
1. Simple implementation
2. Efficient for small data sets
3. Stable; i.e., does not change the relative order of elements with equal keys
4. In-place; i.e., only requires a constant amount O(1) of additional memory space.
return 0;
}
Output:
5 6 11 12 13
Related Questions i- Write algorithm and C code to demonstrate Selection sort in detail.
Extra topics for fast Search-Practical utilization of sorting techniques used in real life/software/program.
learners/Topics beyond
syllabus
Selection Sort
Selection sorting is conceptually the simplest sorting algorithm. This algorithm first finds the smallest
element in the array and exchanges it with the element in the first position, then find the second smallest
element and exchange it with the element in the second position, and continues in this way until the entire
array is sorted
How Selection Sort works
In the first pass, the smallest element found is 1, so it is placed at the first position, then leaving first
element, smallest element is searched from the rest of the elements, 3 is the smallest, so it is then placed
at the second position. Then we leave 1 and 3, from the rest of the elements, we search for the smallest
and put it at third position and keep doing this, until array is sorted
Complexity-
Algorithmic complexity is concerned about how fast or slow particular algorithm performs. We define
complexity as a numerical function T(n) - time versus the input size n. We want to define time taken by an
algorithm without depending on the implementation details. But you agree that T(n) does depend on the
implementation! A given algorithm will take different amounts of time on the same inputs depending on
such factors as: processor speed; instruction set, disk speed, brand of compiler and etc. The way around is
to estimate efficiency of each algorithm asymptotically. We will measure time T(n) as the number of
elementary "steps" (defined in any way), provided each such step takes constant time.
Let us consider two classical examples: addition of two integers. We will add two integers digit by digit (or
bit by bit), and this will define a "step" in our computational model. Therefore, we say that addition of two
n-bit integers takes n steps. Consequently, the total computational time is T(n) = c * n, where c is time taken
by addition of two bits. On different computers, additon of two bits might take different time, say c1 and c2,
thus the additon of two n-bit integers takes T(n) = c1 * n and T(n) = c2* n respectively. This shows that
different machines result in different slopes, but time T(n) grows linearly as input size increases.
The process of abstracting away details and determining the rate of resource usage in terms of the input size
is one of the fundamental ideas in computer science.
** Asymptotic Notations
The goal of computational complexity is to classify algorithms according to their performances. We will
represent the time function T(n) using the "big-O" notation to express an algorithm runtime complexity.
For example, the following statement
T(n) = O(n2)
says that an algorithm has a quadratic time complexity.
1 = O(n)
n = O(n2)
log(n) = O(n)
2 n + 1 = O(n)
An algorithm is said to run in constant time if it requires the same amount of time regardless of the input
size. Examples:
binary search
Related Questions i-What do mean by pointers? How pointer variables are initialized? Write a program in C to
swap the values of any two integer variables using pointers.
An Introduction to Pointers
Pointer Notation
Consider the declaration,
int i = 3 ;
This declaration tells the C compiler to:
(a) Reserve space in memory to hold the integer value.
(b) Associate the name i with this memory location.
(c) Store the value 3 at this location.
We see that the computer has selected memory location 65524 as the place to store the value 3. The location
number 65524 is not a number to be relied upon, because some other time the computer may choose a
different location for storing the value 3. The important point is, i’s address in memory is a number.
We can print this address number through the following program:
main( )
{
int i = 3 ;
printf ( "\nAddress of i = %u", &i ) ;
Look at the first printf( ) statement carefully. ‘&’ used in this statement is C’s ‘address of’ operator. The
expression &i returns the address of the variable i, which in this case happens to be 65524. Since 65524
represents an address, there is no question of a sign being associated with it. Hence it is printed out using
%u, which is a format specifier for printing an unsigned integer.
We have been using the ‘&’ operator all the time in the scanf( ) statement. The other pointer operator
available in C is ‘*’, called ‘value at address’ operator. It gives the value stored at a particular address. The
‘value at address’ operator is also called ‘indirection’ operator.
Note that printing the value of *( &i ) is same as printing the value of i. The expression &i gives the address
of the variable i. This address can be collected in a variable, by saying, j = &i ;
Here, alpha, ch and s are declared as pointer variables, i.e. variables capable of holding addresses.
Remember that, addresses (location nos.) are always going to be whole numbers, therefore pointers always
contain whole numbers.
Now we can put these two facts together and say—pointers are variables that contain addresses, and since
addresses are always whole numbers, pointers would always contain whole numbers.
The declaration float *s does not mean that s is going to contain a floating-point value. What it means is, s
is going to contain the address of a floating-point value. Similarly, char *ch means that ch is going to
contain the address of a char value. Or in other words, the value at address stored in ch is going to be a
char.
Pointers
Consider the following example:
main( )
{ int i = 3, *x ;
float j = 1.5, *y ;
char k = 'c', *z ;
printf ( "\nValue of i = %d", i ) ;
printf ( "\nValue of j = %f", j ) ;
printf ( "\nValue of k = %c", k ) ;
x = &i ;
y = &j ;
z = &k ;
printf ( "\nOriginal address in x = %u", x ) ;
printf ( "\nOriginal address in y = %u", y ) ;
printf ( "\nOriginal address in z = %u", z ) ;
x++ ;
y++ ;
Observe the last three lines of the output. 65526 is original value in x plus 2, 65524 is original value in y
plus 4, and 65520 is original value in z plus 1. This so happens because every time a pointer is incremented
it points to the immediately next location of its type.
That is why, when the integer pointer x is incremented, it points to an address two locations after the current
location, since an int is always 2 bytes long (under Windows/Linux since int is 4 bytes long, new value of
x would be 65528).
Similarly, y points to an address 4 locations after the current location and z points 1 location after the current
location. This is a very important result and can be effectively used while passing the entire array to a
function.
The way a pointer can be incremented, it can be decremented as well, to point to earlier locations. Thus, the
following operations can be performed on a pointer:
One pointer variable can be subtracted from another provided both variables point to elements of the
same array. The resulting value indicates the number of bytes separating the corresponding array
elements. This is illustrated in the following program.
main( ) {
int arr[ ] = { 10, 20, 30, 45, 67, 56, 74 } ;
int *i, *j ;
**A word of caution! Do not attempt the following operations on pointers... they would never work
out.
(a) Addition of two pointers
(b) Multiplication of a pointer with a constant
(c) Division of a pointer with a constant
Extra topics for fast Explore Importance and utilization of DMA functions.
learners/Topics beyond
syllabus
DMA-
Dynamic memory management refers to manual memory management. This allows you to obtain more
memory when required and release it when not necessary.
Although C inherently does not have any technique to allocate memory dynamically, there are 4 library
functions defined under <stdlib.h> for dynamic memory allocation.
Syntax of malloc()
Here, ptr is pointer of cast-type. The malloc() function returns a pointer to an area of memory with size of
byte size. If the space is insufficient, allocation fails and returns NULL pointer.
This statement will allocate either 200 or 400 according to size of int 2 or 4 bytes respectively and the
pointer points to the address of first byte of memory.
calloc()
The name calloc stands for "contiguous allocation".
The only difference between malloc() and calloc() is that, malloc() allocates single block of memory
whereas calloc() allocates multiple blocks of memory each of same size and sets all bytes to zero.
Syntax of calloc()
This statement will allocate contiguous space in memory for an array of n elements. For example:
This statement allocates contiguous space in memory for an array of 25 elements each of size of float, i.e,
4 bytes.
free()
Dynamically allocated memory created with either calloc() or malloc() doesn't get freed on its own. You
must explicitly use free() to release the space.
free(ptr);
This statement frees the space allocated in the memory pointed by ptr.
Write a C program to find sum of n elements entered by user. To perform this program, allocate memory
dynamically using malloc() function.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int num, i, *ptr, sum = 0;
printf("Enter number of elements: ");
scanf("%d", &num);
ptr = (int*) malloc(num * sizeof(int)); //memory allocated using malloc
if(ptr == NULL)
{
printf("Error! memory not allocated.");
exit(0);
}
printf("Enter elements of array: ");
for(i = 0; i < num; ++i)
{
scanf("%d", ptr + i);
sum += *(ptr + i);
}
Write a C program to find sum of n elements entered by user. To perform this program, allocate memory
dynamically using calloc() function.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int num, i, *ptr, sum = 0;
printf("Enter number of elements: ");
scanf("%d", &num);
int main()
{
int *ptr, i , n1, n2;
printf("Enter size of array: ");
scanf("%d", &n1);
Introduction
One disadvantage of using arrays to store data is that arrays are static structures and therefore cannot
be easily extended or reduced to fit the data set. Arrays are also expensive to maintain new
insertions and deletions. In this chapter we consider another data structure called Linked Lists that
addresses some of the limitations of arrays.
A linked list is a linear data structure where each element is a separate object.
Each element (we will call it a node) of a list is comprising of two items - the data and a reference
to the next node. The last node has a reference to null. The entry point into a linked list is called
the head of the list. It should be noted that head is not a separate node, but the reference to the first
node. If the list is empty then the head is a null reference.
A linked list is a dynamic data structure. The number of nodes in a list is not fixed and can grow and shrink
on demand. Any application which has to deal with an unknown number of objects will need to use a linked
list.
One disadvantage of a linked list against an array is that it does not allow direct access to the individual
elements. If you want to access a particular item then you have to start at the head and follow the references
until you get to that item.
A doubly linked list is a list that has two references, one to the next node and another to previous node.
Another important type of a linked list is called a circular linked list where last node of the list
points back to the first node (or the head) of the list.
A linked list is a linear data structure, in which the elements are not stored at contiguous memory locations.
The elements in a linked list are linked using pointers as shown in the below image:
Related Questions 1. . a) List out various file operations in C. Write a C program to count the number of
characters in a file. b) Write a C program to copy the content of one file into another file.
2. A file name DATA contains a series of integer numbers write a program to read these
numbers and then write all ‘odd’ numbers to a file to be called ODD and all even numbers
to a file to be called EVEN.
3. Write a program in ‘C’ that takes 10 integers from al file and write square of these integers
into another file.
Extra topics for fast Complete any MIS type project using file handling
learners/Topics beyond
syllabus
File-
A File is a collection of data stored on a secondary storage device like hard disk. File operation is to combine
all the input data into a file and then to operate through the C program.
Various operations like insertion, deletion, opening closing etc can be done upon a file. When the program
is terminated, the entire data is lost in C programming.
If you want to keep large volume of data, it is time consuming to enter the entire data. But, if file is created
these information can be accessed using few commands.
There are large numbers of functions to handle file I/O in C language. High level file I/O functions can be
categorized as: Text file & Binary file
File Operations
In C, you can perform four major operations on files, either text or binary:
1. Creating a new file
2. Opening an existing file
3. Closing a file
4. Reading from and writing information to a file
printf(“Enter marks”);
scanf(“%d”, &marks);
fprintf(fptr, “\nName: %s\nMarks=%d\n”, name, marks);
}
fclose(fptr);
Return 0;
}
The fclose function causes the stream pointed to be flushed and the associated file to be closed. Any
unwritten buffered data for the stream are delivered to the host environment to be written to the file; any
unread buffered data are discarded. The stream is disassociated from the file. If the associated buffer was
automatically allocated, it is deallocated. The function returns zero if the stream was successfully closed or
EOF if any errors were detected.
Q.3. Write a program to read data from file and close using fclose function.
Ans:
#include <stdio.h>
int main()
int n
FILE *fptr;
if ((fptr=fopen("C:\\program.txt","r"))==NULL){
printf("Error! opening file");
exit(1); // Program exits if file pointer returns NULL.
}
fscanf(fptr,"%d",&n);
printf("Value of n=%d",n);
fclose(fptr);
return 0;
}
Features of C Preprocessor
There are several steps involved from the stage of writing a C program to the stage of getting it executed.
Note that if the source code is stored in a file PR1.C then the expanded source code gets stored in a file
PR1.I. When this expanded source code is compiled the object code gets stored in PR1.OBJ. When this
object code is linked with the object code of library functions the resultant executable code gets stored in
PR1.EXE.
Macro Expansion
Have a look at the following program.
#define UPPER 25
main( )
{
int i ;
for ( i = 1 ; i <= UPPER ; i++ )
printf ( "\n%d", i ) ;
}
In this program instead of writing 25 in the for loop we are writing it in the form of UPPER, which has
already been defined before main( ) through the statement,
#define UPPER 25
This statement is called ‘macro definition’ or more commonly, just a ‘macro’. What purpose does it
serve? During preprocessing, the preprocessor replaces every occurrence of UPPER in the program
with 25.
When we compile the program, before the source code passes to the compiler it is examined by the C
preprocessor for any macro definitions. When it sees the #define directive, it goes through the entire
program in search of the macro templates; wherever it finds one, it replaces the macro template with
the appropriate macro expansion. Only after this procedure has been completed is the program handed
over to the compiler.
In this program wherever the preprocessor finds the phrase AREA(x) it expands it into the statement ( 3.14
* x * x ). However, that’s not all that it does. The x in the macro template AREA(x) is an argument that
matches the x in the macro expansion ( 3.14 * x * x ). The statement AREA(r1) in the program causes the
variable r1 to be substituted for x. Thus the statement AREA(r1) is equivalent to:
Be careful not to leave a blank between the macro template and its argument while defining the macro. For
example, there should be no blank between AREA and (x) in the definition, #define AREA(x) ( 3.14 * x *
x)
If we use a macro hundred times in a program, the macro expansion goes into our source code at hundred
different places, thus increasing the program size. On the other hand, if a function is used, then even if it is
called from hundred different places in the program, it would take the same amount of space in the program.
But passing arguments to a function and getting back the returned value does take time and would therefore
slow down the program. This gets avoided with macros since they have already been expanded and placed
in the source code before compilation.
Moral of the story is—if the macro is simple and sweet like in our examples, it makes nice shorthand and
avoids the overheads associated with function calls. On the other hand, if we have a fairly large macro and
it is used fairly often, perhaps we ought to replace it with a function.
Conditional Compilation
We can, if we want, have the compiler skip over part of a source code by inserting the preprocessing
commands #ifdef and #endif, which have the general form:
#ifdef macroname
statement 1 ;
statement 2 ;
statement 3 ;
#endif
If macroname has been #defined, the block of code will be processed as usual; otherwise not.
main( )
{
#if TEST <= 5
statement 1 ;
statement 2 ;
statement 3 ;
#else
statement 4 ;
statement 5 ;
statement 6 ;
#endif
}
If the expression, TEST <= 5 evaluates to true then statements 1, 2 and 3 are compiled otherwise statements
4, 5 and 6 are compiled. In place of the expression TEST <= 5 other expressions like ( LEVEL == HIGH
|| LEVEL == LOW ) or ADAPTER == CGA can also be used.
The above program segment can be made more compact by using another conditional compilation directive
called #elif. The same program using this directive can be rewritten as shown below. Observe that by using
the #elif directives the number of #endifs used in the program get reduced.
#undef Directive
On some occasions it may be desirable to cause a defined name to become ‘undefined’. This can be
accomplished by means of the #undef directive.
#pragma Directive
This directive is another special-purpose directive that you can use to turn on or off certain features.
Pragmas vary from one compiler to another. There are certain pragmas available with Microsoft C compiler
that deal with formatting source listings and placing comments in the object file generated by the compiler.
Turbo C/C++ compiler has got a pragma that allows you to suppress warnings generated by the compiler.
Some of these pragmas are discussed below.
(a) #pragma startup and #pragma exit: These directives allow us to specify functions that are called upon
program startup (before main( )) or program exit (just before the program terminates). Their usage is as
follows:
void fun1( ) ;
void fun2( ) ;
#pragma startup fun1
#pragma exit fun2
main( )
{
printf ( "\nInside maim" ) ;
}
void fun1( )
{
printf ( "\nInside fun1" ) ;
}
void fun2( )
{
printf ( "\nInside fun2" ) ;
}
{
f1( ) ;
f2 ( 7 ) ;
f3( ) ;
}
So far, we have seen that no arguments were passed in the main function. But the C programming
language gives the programmer the provision to add parameters or arguments inside the main function to
reduce the length of the code. These arguments are called Command Line Arguments in C.
In this lecture , we will discuss:
Command line arguments are simply arguments that are specified after the name of the program in the
system’s command line, and these argument values are passed on to your program during program
execution.
1. argc: It refers to “argument count”. It is the first parameter that we use to store the number of
command line arguments. It is important to note that the value of argc should be greater than or
equal to 0.
2. agrv: It refers to “argument vector”. It is basically an array of character pointer which we use to list
all the command line arguments.
In order to implement command line arguments, generally, 2 parameters are passed into the main
function:
#include<stdio.h>
#include<conio.h>
void main()
{
int r;
float pi=3.14,area,ci;
clrscr();
printf(“enter radius of circle: ”);
scanf(“%d”,&r);
area=pi*r*r;
printf(“area of circle=%f ”,area);
ci=2*pi*r;
printf(“circumference=%f ”,ci);
getch();
}
Output:
enter radius of a circle: 5
area of circle=78.000
circumference=31.4
#include<stdio.h>
#include<conio.h>
void main()
{
int p,r,t,si;
clrscr();
printf(“enter principle, Rate of interest & time to find simple interest: ”);
scanf(“%d%d%d”,&p,&r,&t);
si=(p*r*t)/100;
printf(“simple intrest= %d”,si);
getch();
}
Output:
enter principle, rate of interest & time to find simple interest: 500
5
2
simple interest=50
#include<stdio.h>
#include<conio.h>
void main()
{
float c,f;
clrscr();
printf(“enter temp in centigrade: ”);
scanf(“%f”,&c);
f=(1.8*c)+32;
printf(“temp in Fahrenheit=%f ”,f);
getch();
}
Output:
enter temp in centigrade: 32
temp in Fahrenheit=89.59998
#include<stdio.h>
#include<conio.h>
void main()
{
int s1,s2,s3,s4,s5,sum,total=500;
float per;
clrscr();
printf(“enter marks of 5 subjects: ”);
scanf(“%d%d%d%d%d”,&s1,&s2,&s3,&s4,&s5);
sum=s1+s2+s3+s4+s5;
printf(“sum=%d”,sum);
per=(sum*100)/total;
printf(“percentage=%f”,per);
getch();
}
Output:
enter marks of 5 subjects: 60
65
50
60
60
sum=300
percentage=60.000
#include <stdio.h>
int main()
{
int i, n, flag;
//Flag is used as notification. Initially we have supposed that the number is prime.
flag = 1;
/*
* If flag contains 1 then it is prime
*/
if(flag==1)
{
printf("\n%d is prime number", n);
}
else
{
printf("\n%d is not prime number", n);
}
return 0;
}
#include <stdio.h>
int main()
{
int n, num, lastDigit, sum = 0;
/*
* Finds the sum of cubes of each digit of number
*/
while(n != 0)
{
/* Finds last digit of number */
lastDigit = n % 10;
/* Finds cube of last digit and adds to sum */
sum += (lastDigit * lastDigit * lastDigit);
n = n / 10;
}
/* Checks if sum of cube of digits is equal to original value or not. */
if(num == sum)
{
printf("\n%d is Armstrong number.", num);
}
else
{
printf("\n%d is not Armstrong number.", num);
}
return 0;}
#include <stdio.h>
int main()
{ int i, num, sum = 0;
#include <stdio.h>
int main()
{
int i, j, n, isPrime; //isPrime is used as flag variable
/*
* Finds all prime numbers between 1 to n
*/
for(i=2; i<=n; i++)
{
/*
* Checks if the current number i is Prime or not
*/
isPrime = 1;
for(j=2; j<=i/2 ;j++)
{
if(i%j==0)
{
isPrime = 0;
break;
}
}
/*
* If i is Prime then add to sum
*/
if(isPrime==1)
Now Fibonacci series algorithm is simple and contains only four steps.
Step 1: Print the value of c.
Step 2: a = b.
Step 3: b = c.
Step 4: c = a + b.
#include <stdio.h>
int main()
a=b;
b=c;
c=a+b;
}
return 0;}
#include <stdio.h>
/* Function declarations */
int isPrime(int num);
int isArmstrong(int num);
int isPerfect(int num);
int main()
{
int num;
return 0;
}
/**
* Checks whether a number is prime or not. Returns 1 if the number is prime
* otherwise returns 0.
*/
int isPrime(int num)
{
int i;
/**
* Checks whether a number is Armstrong number or not. Returns 1 if the number
* is Armstrong number otherwise returns 0.
*/
int isArmstrong(int num)
{
int lastDigit, sum, n;
sum = 0;
n = num;
while(n!=0)
{
/* Finds last digit of number */
lastDigit = n % 10;
n = n/10;
}
/**
* Checks whether the number is perfect number or not. Returns 1 if the number
* is perfect otherwise returns 0.
*/
int isPerfect(int num)
{
int i, sum, n;
sum = 0;
n = num;
#include <stdio.h>
#include <math.h>
/* Fuction declaration */
int reverse(int num);
int main()
{
int num, rev;
return 0;
}
/**
* Recursive function to find reverse of any number
*/
int reverse(int num)
{
int digit;
//Base condition
if(num==0)
return 0;
#include <stdio.h>
//Function declaration
long long fibo(int num);
int main()
{
fibonacci = fibo(num);
return 0;
}
/**
* Recursive function to find nth Fibonacci term
*/
long long fibo(int num)
{
if(num == 0) //Base condition
return 0;
else if(num == 1) //Base condition
return 1;
else
return fibo(num-1) + fibo(num-2); //Recursively calls fibo() to find nth fibonacci term.
}
int main()
{
int arr[MAX_SIZE];
int i, n, sum=0;
/*
* Reads size and elements in array from user
*/
printf("Enter size of the array: ");
scanf("%d", &n);
printf("Enter %d elements in the array: ", n);
/*
* Adds each element of array to sum
*/
for(i=0; i<n; i++)
{
sum = sum + arr[i];
}
return 0;
}
int main()
{
int arr[100];
int i, max, min, size;
/*
* Reads size array and elements in the array
*/
printf("Enter size of the array: ");
/*
* Finds maximum and minimum in all array elements.
*/
for(i=1; i<size; i++)
{
/* If current element of array is greater than max */
if(arr[i]>max)
{
max = arr[i];
}
/*
* Prints the maximum and minimum element
*/
printf("Maximum element = %d\n", max);
printf("Minimum element = %d", min);
return 0;
}
int main()
{
int arr[100], reverse[100];
int size, i, j;
/*
* Reads the size of array and elements in array
*/
printf("Enter size of the array: ");
scanf("%d", &size);
printf("Enter elements in array: ");
for(i=0; i<size; i++)
{
scanf("%d", &arr[i]);
}
/*
* Reverse the array
/*
* Prints the reversed array
*/
printf("\nReversed array : ");
for(i=0; i<size; i++)
{
printf("%d\t", reverse[i]);
}
return 0;
}
int main()
{
int arr[100];
int size, i, num, flag;
/*
* Read size of array and elements in array
*/
printf("Enter size of array: ");
/*
* If element is not found in array
*/
if(flag==0)
{
printf("\n%d is not found in the array", num);
}
return 0;
}
int main()
{
int arr[100];
int size, i, j, temp;
/*
* Read size of array and elements in array
*/
printf("Enter size of array: ");
scanf("%d", &size);
/*
* Array sorting code
*/
for(i=0; i<size; i++)
{
for(j=i+1; j<size; j++)
{
/*
* If there is a smaller element towards right of the array then swap it.
*/
if(arr[j] < arr[i])
{
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
/*
* Prints the sorted array
*/
printf("\nElements of array in sorted ascending order: ");
for(i=0; i<size; i++)
{
printf("%d\t", arr[i]);
}
return 0;
}
#include <stdio.h>
/*
* Checks each character of string
*/
while(string[i]!='\0')
{
i++;
}
return 0;
}
Example:
Input any decimal number: 112
Output binary number: 0111000
Decimal number system:
Decimal number system is a base 10 number system. Decimal number system uses only 10
symbols to represent all number i.e. 0 1 2 3 4 5 6 7 8 9
Binary number system:
Binary number system is a base 2 number system. Binary number system uses only 2 symbols to
represent all numbers i.e. 0 and 1
Program:
#include <stdio.h>
int main()
{
long long decimal, tempDecimal, binary;
int rem, place = 1;
binary = 0;
/*
* Reads decimal number from user
*/
printf("Enter any decimal number: ");
scanf("%lld", &decimal);
tempDecimal = decimal;
/*
* Converts the decimal number to binary number
*/
while(tempDecimal!=0)
{
rem = tempDecimal % 2;
tempDecimal /= 2;
place *= 10;
}
return 0;
}