[go: up one dir, main page]

0% found this document useful (0 votes)
2K views23 pages

Unit I

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

Unit I

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

Syllabus

Programming for Problem Solving (KCS201)

Module – 1: (Introduction to Programming)

Introduction to components of a computer system: Memory, processor, I/O Devices, storage, operating
system, Concept of assembler, compiler, interpreter, loader and linker.
Idea of Algorithm: Representation of Algorithm, Flowchart, Pseudo code with examples, From algorithms
to programs, source code.
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.

Module – 2: (Arithmetic expressions & Conditional Branching)

Arithmetic expressions and precedence: Operators and expression using numeric and relational operators,
mixed operands, type conversion, logical operators, bit operations, assignment operator, operator
precedence and associativity.
Conditional Branching: Applying if and switch statements, nesting if and else, use of break and default with
switch.

Module – 3: (Loops & Functions)

Iteration and loops: use of while, do while and for loops, multiple loop variables, use of break and
continue statements. Functions: Introduction, types of functions, functions with array, passing parameters
to functions, call by value, call by reference, recursive functions.

Module – 4: (Arrays & Basic Algorithms)

Arrays: Array notation and representation, manipulating array elements, using multi-dimensional arrays.
Character arrays and strings, Structure, union, enumerated data types, Array of structures, Passing arrays
to functions.
Basic Algorithms: Searching &Basic Sorting Algorithms (Bubble, Insertion and Selection), Finding roots of
equations, Notion of order of complexity.

Module – 5 :( Pointer& File Handling)

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, Standard C preprocessors, defining and calling macros, command-line
arguments.

PRAMOD KUMAR, ASST. PROF., CSE DEPTT., HCST (ver 2.0) 1|Page
Module – 1: (Introduction to Programming)

Introduction to components of a computer system: Memory, processor, I/O Devices, storage, operating system,
Concept of assembler, compiler, interpreter, loader and linker.

Idea of Algorithm: Representation of Algorithm, Flowchart, Pseudo code with examples, From algorithms to
programs, source code.

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.

Basics of Computer
What is a computer?

The term ‘computer’ is derived from the word ‘compute’ which means to calculate.

Definition

“A computer is an electronic device that processes data and converts it into information that is useful to people.”

OR

“A computer is an electronic device capable of performing arithmetic and logical operations. It can also store a
large volume of information.”

Data: It is the collection of raw facts, figures & symbols.

Example: Names of students and their marks in different subjects listed in random order.

Information: It is the data that is processed & presented in an organized manner.

Example: When the names of students are arranged in alphabetical order, total and average marks are
calculated & presented in a tabular form, it is information.

Basic Operations of Computer


The computer performs five basic operations to perform any task. The five

basic operations are:

• Input It is the process of capturing or acquiring the information, or it is the process of accepting data or
information.

• Process It is a transformation process. It converts input data into useful information.

• Output It is the process by which the useful information is made available to the user by displaying it or
by printing a hard copy of it.

• Storing It is the process of storing or retaining the data or information or instruction, so that the user
can retain and retrieve it whenever required.
• Controlling It is the process of directing the manner and sequence in which all the operations are to be
performed.

Functional Components of Computer

PRAMOD KUMAR, ASST. PROF., CSE DEPTT., HCST (ver 2.0) 2|Page
Figure shows the block diagram of a computer. It shows the functional components with flow of data and
instructions between them.

The functional components of computer are:

• Arithmetic and Logic Unit (ALU)

• Control Unit

• Memory Unit

• Input Unit

• Output Unit

1. The Control Unit Controls all the activities of the Computer. It sends commands and control signals and
finds the sequence of instruction to be executed.

PRAMOD KUMAR, ASST. PROF., CSE DEPTT., HCST (ver 2.0) 3|Page
2. Memory Unit stores instruction and data and provides them to the various other units as and when
required. It is basically the working memory of the computer system. This memory unit is volatile,
i.e. it is temporary memory and nothing can be stored here permanently. The information is stored
in the main memory as long the computer is switched on or as long as it is required by the
computer.

3. ALU Consists of circuits for arithmetic operations (+,-,*, /) and logical operations (<,>,>=, <=, ==, !=)

4. Input device is used for transferring data from the users’ end to the computer.

Example- Keyboard, mouse, Joystick, camera, scanner etc.

5. Output Device is used to transfer processed information from the computer to the user in a way
required by the user.

Example- Monitor, LCD, Printer

Connected components of CPU are called peripherals

Storage Devices:

1. Floppy disk

2. Hard disk
3. Compact disk

Computer Memory: Primary

Memory

• RAM (Random Access memory)


• ROM (Read only memory)

RAM: It is a temporary storage medium in a computer. The data to be processed by the computer are transferred
from a storage device or a keyboard to RAM results from an executed program are also stored in RAM. The data
stored will be erased when the computer is off.

ROM (Read only Memory): This is a non-volatile or data storage medium which stores start up programs
(operating systems). This essentially stores the BIOS (Basic Input Operating System)

Note: Basically, Computer System components communicate it binaries as (0’s & 1’s, 0 refers OFF state, 1 refer ON
state)

Secondary memory
Secondary storage, secondary memory or external memory, is a non-volatile memory (does not lose stored data
when the device is powered down) that is not directly accessible by the CPU, because it is not accessed via the
input/output channels (it is an external device).

Hard disk

A magnetic disk on which you can store computer data. The term hard is used to distinguish it from a soft, or
floppy, disk. Hard disks hold more data and are faster than floppy disks. A hard disk, for example, can store
anywhere from 10 to more than 100 gigabytes, whereas most floppies have a maximum storage capacity of 1.4
megabytes.

A single hard disk usually consists of several platters. Each platter requires two read/write heads, one for each
PRAMOD KUMAR, ASST. PROF., CSE DEPTT., HCST (ver 2.0) 4|Page
side. All the read/write heads are attached to a single access arm so that they cannot move independently. Each
platter has the same number of tracks, and a track location that cuts across all platters is called a cylinder. For
example, a typical 84-megabyte hard disk for a PC might have two platters (four sides) and 1,053 cylinders.

Program: Set of instructions that enables a computer to perform a given task.

Advantages of computers:
1. High speed: Computers have the ability to perform routine tasks at a greater speed than human beings. They
can perform millions of calculations in seconds.

2. Accuracy: Computers are used to perform tasks in a way that ensures accuracy.

3. Storage: Computers can store large amount of information. Any item of data or any instruction stored in the
memory can be retrieved by the computer at lightning speeds.

4. Automation: Computers can be instructed to perform complex tasks automatically (which increases the
productivity).

5. Diligence: Computers can perform the same task repeatedly & with the same accuracy without getting tired.

6. Versatility: Computers are flexible to perform both simple and complex tasks.

7. Cost effectiveness: Computers reduce the amount of paper work and human effort, thereby reducing
costs.

Limitations of computers:
1. Computers need clear & complete instructions to perform a task accurately. If the instructions are not clear
& complete, the computer will not produce the required result.

2. Computers cannot think.

3. Computers cannot learn by experience.

HARDWARE And SOFTWARE:

Hardware: Hardware refers to the physical elements of a computer. This is also sometime called the machinery
or the equipment of the computer. Examples of hardware in a computer are the keyboard, the monitor, the
mouse and the central processing unit (CPU).

Example: input and output devices, processors, circuits and the cables etc.

Software: commonly known as programs or apps, consists of all the instructions that tell the hardware how to
perform a task. These instructions come from a software developer in the form that will be accepted by the
platform (operating system + CPU) that they are based on. For example, a program that is designed for the
Windows operating system will only work for that specific operating system. Compatibility of software will
vary as the design of the software and the operating system differ

Operating System
• A program that acts as an intermediary between a user of a computer and the computer hardware.

• An operating system is a program that acts as an interface between the user and the computer hardware
and controls the execution of all kinds of programs.

• OS controls execution of programs to prevent errors and improper use of the computer.

• OS manages all resources and decides between conflicting requests for efficient and fair resource use.
PRAMOD KUMAR, ASST. PROF., CSE DEPTT., HCST (ver 2.0) 5|Page
Functions of an Operating System

COMMAND PROCESS MANAGEMENT DEVICE MANAGEMENT


INTERPRETER & SCHEDULING

FAULT TOLERANCE FILE MANAGEMENT


MANAGEMENT
OPERATING SYSTEM

COMMUNICATIO MEMORY
N MANAGEMENT

JOB ACCOUNTING &


SECURITY LOG MAINTENANCE HANDLING USERS

Process Management and scheduling

• Provide an interface between the computer hardware and the programmer that simplifies and makes
feasible for coding, creation, debugging and execution of application programs.

• Provide access to the compiler for translating the user program from high level language to machine
language.

• Organize processing time between programs and users.

• Organize priorities between program and users.

Device Management

• Recognize input from the keyboard.

• Send output to the display screen.

• Control peripherals such as disk drives and printers.

File Management

• Creating and deleting of files.

• Mapping files onto secondary storage.

• Creating and deleting directories.

• Backing up files on stable storage media.

• Transmission of file elements between main and secondary storage.

Memory Management

PRAMOD KUMAR, ASST. PROF., CSE DEPTT., HCST (ver 2.0) 6|Page
• Controls transfer of programs in and out of memory.

• Organize the use of memory between programs.

• Control the allocation and use of the computing system's memory among the various users and tasks.

Handling Users

• Maintain security and access rights of users with the help of password or access right information.

Command Interpretation

• Read, check, interpret and execute user commands like copy, print, rename, dir, type, delete, etc. ·

Job Accounting and Log Maintenance

• Compute the resource allocation time for different users, keep record of login and logout times for users
etc.

Security ·

• Provide data security among various users and prevent unauthorized access to any of the resources.

Communication

• Provide facility to users to communicate and interact with other users.

Fault Tolerance Management

• Deal with errors

DOS (Disk Operating System)

• The disk operating system (DOS) may seem out of date, it is still widely used and deserves to be included
in this discussion.

• DOS originally came with the appearance of the IBM PC, which was the first personal computer.

• DOS came with two versions. The first was PC DOS, which IBM released with its computer. The other was
Microsoft’s version of DOS, known as MS-DOS (Microsoft DOS), which was used on millions of IBM-
compatible PCs or clones.

MS-DOS Commands
Disk Commands
1. FORMAT: Prepares a disk so that MS-DOS can use it. Formatting a disk erases all the information on the
disk, so be careful. Example: FORMAT A:
2. CHKDSK: Checks for problems and repairs corrupted disks. A disk can sometimes get corrupted when, for
example, the power is turned off while a program is still running. Example: CHKDSK C:
3. DISKCOPY: Duplicates diskettes. Use this command to copy important diskettes, like newly purchased
programs. Example: DISKCOPY A: B:

Directory Manipulation Commands


1. MKDIR (MD): Makes a directory on the disk. Example: MD C:\DOS
2. RMDIR (RD): Removes empty directories from the disk. Example: RD C:\DOS
3. CHDIR (CD): Changes the current working directory. Example: CD C:\DOS
PRAMOD KUMAR, ASST. PROF., CSE DEPTT., HCST (ver 2.0) 7|Page
4. PATH: Provides a list of directories where MS-DOS can find programs. Put this in your AUTOEXEC.BAT file.
Example: PATH C:\;C:\DOS
5. File Copying & Backup Commands
6. COPY: Copies files between disks or directories. Example: COPY C:\AUTOEXEC.BAT A:
7. XCOPY: Copies files, or entire directories with their subdirectories, to other disks or directories. Example:
XCOPY C:\DOS C:\OLD_DOS /S
8. BACKUP: Copies entire hard disks onto many floppy diskettes to create a backup copy of the hard disk.
Example: BACKUP C:\*.* A: /S /F
9. RESTORE: Restores the BACKUP files back onto your hard disk. Example: RESTORE A: C:\*.*

File Management Commands


1. DIR: TYPE: Lists the files in a directory or disk. It includes file and directory names, file sizes, and file
creation dates. Example: DIR C:\
2. Displays the contents of a file on your computer screen. Example: TYPE C:\CONFIG.SYS
3. ERASE (DEL): Deletes files from the disk. Example: DEL C:\JUNK.TXT
4. RENAME (REN): Changes the name of a file. Example: REN TEMPLATE.WP REPORT.WP

Linux Operating System


Just like Windows XP, Windows 7, Windows 8, and Mac OS X, Linux is an operating system. An operating system
is software that manages all of the hardware resources associated with your desktop or laptop. The operating
system manages the communication between your software and your hardware. Without the operating
system (often referred to as the “OS”), the software wouldn’t function.

Linux is one of popular version of UNIX operating System. It is open source as its source code is freely available. It
is free to use. Linux was designed considering UNIX compatibility. It's functionality list is quite similar to that of
UNIX.

Basic Features
Following are some of the important features of Linux Operating System.

• Portable - Portability means softwares can works on different types of hardware in same way. Linux
kernel and application programs supports their installation on any kind of hardware platform.

• Open Source - Linux source code is freely available and it is community-based development project.
Multiple teams work in collaboration to enhance the capability of Linux operating system and it is
continuously evolving.

• Multi-User - Linux is a multiuser system means multiple users can access system resources like memory/
ram/ application programs at same time.

• Multiprogramming - Linux is a multiprogramming system means multiple applications can run at same
time.

• Hierarchical File System - Linux provides a standard file structure in which system files/ user files are
arranged.

• Shell - Linux provides a special interpreter program which can be used to execute commands of the
operating system. It can be used to do various types of operations, call application programs etc.

PRAMOD KUMAR, ASST. PROF., CSE DEPTT., HCST (ver 2.0) 8|Page
• Security - Linux provides user security using authentication features like password protection/ controlled
access to specific files/ encryption of data.

Architecture of Linux Operating System

Linux System Architecture consists of following layers

• Hardware layer - Hardware consists of all peripheral devices (RAM/ HDD/ CPU etc).

• Kernel - Core component of Operating System, interacts directly with hardware, provides low level
services to upper layer components.

• Shell - An interface to kernel, hiding complexity of kernel's functions from users. Takes commands from
user and executes kernel's functions.

• Utilities - Utility programs giving user most of the functionalities of an operating systems

Useful Commands of Linux Operating System


1. cd (change directories)

We can use cd command for changing directories suppose you are in the ‘asia’Directory and now you want to go
its subdirectory named ‘india’, you type ‘cd india’

2. ls (use to view list files and directories)

We use ls command to see a list of the files and directories located in current directory. Suppose you are in the
named ‘websites’ and you type ls, a list will appear that shows the content of websites directory.

ls –l ( shows details list)

ls –lt (shows newest or last modified file and directory first) ls –a (shows

hidden files and directories.)

3. pwd (use to find the current location or current working directory)

PRAMOD KUMAR, ASST. PROF., CSE DEPTT., HCST (ver 2.0) 9|Page
After issuing pwd command you’ll see the complete path of the directory you are currently in. This command is
very helpful when you forget which directory you’ve changed.
4. cp -r /Source Of Copy /Destination Of Copied Data Using “*” we can copy everything under /websites/
Directory.

5. mv (rename files and folders)

6. rm -r (delete files and folders)

7. cat (read text files) Using cat command we can read text file contents without opening it.

8. grep ( grep searches inside files and then print out them on shell window)

Suppose i have huge name list save in this “NameList.txt” file. I want to search name “Haider” from this list then i
use grep command to search specific word from this whole file Like

Machine language

• Machine language is the basic low-level programming language designed to be recognized by a computer.
• Actually, the language is written in a binary code of 0s and 1s that represent electric impulses or off and
on electrical states respectively. A group of such digits is called an instruction and it is translated into a
command that the central processing unit or CPU understands.
• More specifically, instructions are organized in patterns of 0s and 1s in various lengths such as 16, 24, 32,
and 64 digits or bits, representing specific tasks such as storing or transferring data.
• An instruction is made up of two parts: the operator or opcode and the operand. The first few bits of an
instruction are the "operator or opcode," whose role is to specify the kind of operation that needs to be
performed. The rest of the bits are the "operand," whose role is to indicate the location where the
operation is to be performed.

Assembly Language

• An assembly language is a low-level programming language for microprocessors and other programmable
devices.
• It is not just a single language, but rather a group of languages.
• Assembly language implements a symbolic representation of the machine code needed to program a
given CPU architecture.
• Assembly language is the most basic programming language available for any processor. With assembly
language, a programmer works only with operations that are implemented directly on the physical CPU.
• Assembly languages generally lack high-level conveniences such as variables and functions, and they are
not portable between various families of processors.
• It has the same structures and set of commands as machine language, but it allows a programmer to use
names instead of numbers.
• This language is still useful for programmers when speed is necessary or when they need to carry out an
operation that is not possible in high-level languages.

High-level programming language

• A high-level language is a computer programming language that isn't limited by the computer, designed
for a specific job, and is easier to understand.
• It is more like human language and less like machine language.
• Programs written in a high-level language must be translated into machine language by a compiler or
interpreter.
• The first high-level languages were introduced in the 1950's. Today, there are many high-level languages
in use, including BASIC, C, C++, Cobol, FORTRAN, Java, Pascal, Perl, PHP, Python, Ruby, and Visual Basic.

PRAMOD KUMAR, ASST. PROF., CSE DEPTT., HCST (ver 2.0) 10 | P a g e


Assembler

• Assembler is a software or a tool that translates Assembly language to machine code. So, an assembler is
a type of a compiler and the source code is written in Assembly language.
• Assembly is a human readable language but it typically has a one to one relationship with the
corresponding machine code.
• Therefore, an assembler is said to perform isomorphic (one to one mapping) translation.
• Advanced assemblers provide additional features that support program development and debugging
processes. For example, the type of assemblers called macro assemblers provides a macro facility.

Compiler

• A compiler is a piece of code that translates the high-level language into machine language.
• When a user writes a code in a high-level language such as C, Java and wants it to execute, a specific
compiler which is designed for C is used before it will be executed.
• The compiler scans the entire program first and then translates it into machine code which will be
executed by the computer processor and the corresponding tasks will be performed.

• Shown in the figure is basic outline of the compilation process, here program written in higher level
language is known as source program and the converted one is called object program.

Loader
• Loader is a program that loads machine codes of a program into the system memory.
• In Computing, a loader is the part of an Operating System that is responsible for loading programs.
• It is one of the essential stages in the process of starting a program. Because it places programs into
memory and prepares them for execution.
• Loading a program involves reading the contents of executable file into memory.
• Once loading is complete, the operating system starts the program by passing control to the loaded
program code.
• All operating systems that support program loading have loaders. In many operating systems the loader is
permanently resident in memory.

Linker

• In high level languages, some built in header files or libraries are stored.
• These libraries are predefined and these contain basic functions which are essential for executing the
program.
• These functions are linked to the libraries by a program called Linker. If linker does not find a library of a
function then it informs to compiler and then compiler generates an error.
• The compiler automatically invokes the linker as the last step in compiling a program.
• Not built in libraries, it also links the user defined functions to the user defined libraries. Usually a longer
program is divided into smaller subprograms called modules. And these modules must be combined to
execute the program.
• The process of combining the modules is done by the linker.

PRAMOD KUMAR, ASST. PROF., CSE DEPTT., HCST (ver 2.0) 11 | P a g e


Algorithm
Algorithm is a finite sequence of explicit and unambiguous steps required to solve the given problem. When the
required input values are provided, it produces an output and then terminates. The steps may repeat or require
decisions as per the requirement.

Properties of algorithm
• The steps used in algorithm must be unambiguous and precisely defined.
• The uncertainty about the instruction to be executed next, should be avoided.
• The steps used in algorithm should be finite and the algorithm should be terminated, that is, it cannot
be open-ended.
• The execution of the algorithm should conclude after a finite number of steps.
• The algorithm must be general enough to deal with any situation.

Example: Let us write an algorithm to calculate the addition of two given numbers.

Algorithm

Step 1: Start

Step 2: Read two numbers as A and B.

Step 3: Add numbers A and B and store results as C. Step 4:

Display C.

Step 5: Stop

Example: Write an algorithm to find greatest of three numbers.

Algorithm

Step1: Start Step2: Read A,

B,C

Step2: If A > B is True, then check whether A > C, if yes then A is greatest otherwise C is greatest

Step3: If A > B is False, then check whether B > C, if yes then B is greatest otherwise C is greatest

Step4: Stop

Flow Chart
• A flowchart depicts pictorially the sequence in which instructions are carried out in an algorithm.
• Pictorial representation of an algorithm is called flowchart.

• Flow charts are used not only as aids in developing algorithms but also to document algorithms.

• Flowcharts are used in analyzing, designing, documenting or managing a process or program in various
fields.

When to Use a Flowchart


• To develop understanding of how a process is done.

• To study a process for improvement.

PRAMOD KUMAR, ASST. PROF., CSE DEPTT., HCST (ver 2.0) 12 | P a g e


• To communicate to others how a process is done.

• When better communication is needed between people involved with the same process.

• To document a process.

• When planning a project.

Following are the symbols used in the flowcharts:

ii. Parallelograms are used to represent input and output operations.

iii. Rectangles are used to indicate any processing operation such as storage and Arithmetic.

iv. Decision based on a question. The question is written in the diamond. More than one arrow goes out of
the diamond, each one showing the direction the process takes for a given answer to the question. (Often
the answers are “ yes” and “ no.”)

v. Rectangles with rounded ends are used to indicate the beginning or end points of a procedure.

vi. A circle is used to join different parts of a flowchart. This is called a connector.

Arrows indicate the direction to be followed in a flowchart.

Flowchart Disadvantages

• Hard to modify
• Need special software
• Structured design elements nota all implemented.

Example: Draw a flowchart to find greatest of three numbers.

PRAMOD KUMAR, ASST. PROF., CSE DEPTT., HCST (ver 2.0) 13 | P a g e


Pseudocode
• Pseudocode is a method of writing out computer code in the English language.
• Instead of jumping straight into a programming language, computer programmers use pseudocode to
clearly and concisely list out what they hope to accomplish with their new program.
• Pseudocode is not actual programming language.
• It uses short phrases to write code for programs before you actually create it in a specific language. Once
you know what the program is about and how it will function, then you can use pseudocode to create
statements to achieve the required results for your program.

Understanding Pseudocode
• Pseudocode makes creating programs easier.
• Programs can be complex and long; preparation is the key. For years, flowcharts were used to map out
programs before writing one line of code in a language.
• However, they were difficult to modify and with the advancement of programming languages, it was
difficult to display all parts of a program with a flowchart

Examples of Pseudocode

1. To create a program to add 2 numbers together and then display the result.
Start Program
Enter two numbers, A, B
Add the numbers together
Print Sum
End Program
2. To compute the area of a rectangle
Get the length, l, and width, w
Compute the area = l*w
Display the area
3. If student's grade is greater than or equal to 60
Print "passed"
else
PRAMOD KUMAR, ASST. PROF., CSE DEPTT., HCST (ver 2.0) 14 | P a g e
Print "failed"
4. Find the biggest of three (3) Numbers
BEGIN
NUMBER num1, num2, num3
INPUT num1
INPUT num2
INPUT num3
IF num1>num2 AND num1>num3 THEN
OUTPUT num1+ "is higher"
ELSE IF num2 > num3 THEN
OUTPUT num2 + "is higher"
ELSE
OUTPUT num3+ "is higher"
ENDIF
END

Source Code

• Source code is the list of human readable instructions that a programmer writes after in programming
language.
• Source code is run through compiler to turn it into machine code, also called object code that a computer
can understand and execute.
• Object code consists of primarily of ones and zeros, so is not human readable.
• Source code is the program written in particular programming language like C, Java etc.
Example
#include<stdio.h>
#include<conio.h>
void main()
{
int r;
int A;
printf(“Enter Radius”);
scanf(“%d”,&r);
A=3.14*r*r;
printf(“\nArea =%f”,A);
getch();
}

BASIC STRUCTURE OF A C PROGRAM


Basic Structure of a C program contains following sections: -

Documentation Section
Link Section
Definition Section
Global Declaration Section
main()
{
Declaration Section
Executable part
}
Subprogram section
Function 1

PRAMOD KUMAR, ASST. PROF., CSE DEPTT., HCST (ver 2.0) 15 | P a g e


Function 2
.
.
function n

Documentation Section: It consists of a set of comment lines giving the name of the program and other details.
Link Section: It provides instructions to the compiler to link functions from the system library. C program depends
upon some header files for function definition that are used in the program. Each header file has extension ‘.h’. The
header files are included at the beginning of the program in the C language. These files should be included using
#include directive as given below
Example:
#include
(This will find header file in standard directory)
Definition Section: It defines all symbolic constants.
Global Declaration Section: There are some variables and those variables are declared in this section that is outside
of all functions.
main() function: Every C program must have one main() function section. int main(void): This is the function
definition for main().Parenthesis followed to main is to tell the user again that main() is a function. Int main(void)
function return an integer.
void main(void): This function takes no arguments and return nothing.
Declaration and Executable Part: It is user defined function. The Opening braces sometimes called logical start and
Closing braces known as logical end of the program.
-Declaration Part declares all the variables used in the executable part. There should be at least one statement in
the executable part which contains instructions to perform certain task. The declaration and executable part must
appear between the opening and closing braces. All statements in the declaration part should end with the
semicolon.
Subprogram Section: contains all the user defined functions that are called in the main function.

EXAMPLE PROGRAM:

/*Documentation Section: program to find the area of circle*/


#include<stdio.h> /*link section*/
#include<conio.h> /*link section*/
#define pi 3.14 /*global declaration section*/
void main()
{
float r; /*declaration part*/
printf("Enter the radius of the circle\n"); /*executable part starts here*/
scanf("%f",&r);
area=pi*r*r;
printf("Area of the circle=%f",area);
getch();
}

Syntax and Logical Errors in Compilation

Syntax Errors:
• Errors that occur when you violate the rules of writing 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:
• Missing Parenthesis (})
• Printing the value of variable without declaring it
PRAMOD KUMAR, ASST. PROF., CSE DEPTT., HCST (ver 2.0) 16 | P a g e
• Missing semicolon like this:

// C program to illustrate
// syntax error
#include<stdio.h>
void main()
{
int x = 10;
printf("%d", x) // semicolon missed
}

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.
• Here are some examples of mistakes which lead to logical errors:
o using the wrong variable name
o indenting a block to the wrong level
o using integer division instead of floating-point division
o getting operator precedence wrong
o making a mistake in a boolean expression
o off-by-one, and other numerical errors

// C program to illustrate logical error


#include<stdio.h>
#include<conio.h>
void main()
{
int a=10, b=3, c;
c=a/b; integer division instead of floating-point division
printf(“c=%d”,c);
getch();
}

Development of “C” (Introduction and history)


“C” is a programming language developed at AT & T Bell Laboratories of USA in 1972. It was developed Dennis
Ritchie in late 1972’s. It began to replace the more familiar languages of that time like PL/1, ALGOL etc.

PRAMOD KUMAR, ASST. PROF., CSE DEPTT., HCST (ver 2.0) 17 | P a g e


Note: C is a middle level language because it was due to have both a relatively good programming efficiency and
relativity good machine efficiency.
Features of “C” Language:
1. It is robust language.
2. It is efficient and fast because of its various data-types and powerful operation.
3. It is highly Portable i.e., programs written in one computer can be run on another
4. It is well suited for structure program, thus allows the user to think about the problem in the terms of
functional blocks.
5. Debugging, testing and maintenance is easy
6. Ability to extend itself, we can continuously add our own functions to the program.

Components of C Language

Character Set: The characters that can be used to form words and expressions depends upon the computer to
which the program is run
The Characters in C are
1. Letters:
a. Uppercase Letters: A,B,C…
b. Lowercase Letters: a, b, c…

2. Digits: 0,1,2…9
3. Special Characters: @#$% ..etc.
4. White Space Characters:
i. Blank space Character
ii. Horizontal tab space character ‘\t’
iii. New line character ‘\n’

C Tokens:

Individual words and punctuation marks are characters. In a C program the smallest individual units are known as
C tokens. C language has six types of tokens.

PRAMOD KUMAR, ASST. PROF., CSE DEPTT., HCST (ver 2.0) 18 | P a g e


1. Keywords:

• Keywords are reserved words by compiler.


• Keywords are assigned with fixed meaning and they cannot be used as variable name.
• No header file is needed to include the keywords.

There are 32 keywords in C

Keywords in C Programming

auto break case char

const continue default do

double else enum extern

float for goto if

int long register return

short signed sizeof static

struct switch typedef union

unsigned void volatile while

2. Identifiers: These are the names of variables, functions and arrays. They are the user defined

names. The rules to write an identifier name in C are:

• Can have letters, digits or underscores.

• First character must be a letter or an underscore but can’t be a digit.

• No special character except underscore can be used.

• Keywords or reserved words cannot form a valid identifier name.

• Maximum number of characters that form an identifier name is compiler dependent.

PRAMOD KUMAR, ASST. PROF., CSE DEPTT., HCST (ver 2.0) 19 | P a g e


Example:

#include<stdio.h> identifiers (variables)


#include<conio.h>
void main() Data types Format Specifier
{ char %c
int a=10,b=4; int %d
float c; float %f
clrscr(); string %s
c=a/b;
printf(“Division is %f”, c);
getch();
}

Output: Division is 2.5

3. Constants: constants in “C” are applicable to the values which not change during the execution of a

program.

Integer Constants:
• Sequence of number 0-9 without decimal points, fractional part or any other symbols.
• It requires two or four bytes, can be +ve, -ve or Zero the number without a sign is as positive. Eg: -10, +20,
40
Character Constants
Single character constants: A single character constants are given within a pair of single quote mark. Eg : ‘a’,
‘8’ etc.
String Constant: These are the sequence of character within double quote marks Eg : “Straight”, “India”, “4”

4. Variables:

• This is a data name used for storing a data.


• its value may be changed during the execution.
• The variables value keep changing during the execution of the program Eg : height, average, sum, etc.
Declaration of Variable:
It tells the complier what the variable name is used, what type of date is held by the variable.
Syntax:
datatype v1, v2;
Example: int a, b; float sum;
double ratio;
Assigning values to variables
Example: int x,y;
x= 10;
y=5;
Or
int i=10,y=5

5. Data types: C language is rich in data types

PRAMOD KUMAR, ASST. PROF., CSE DEPTT., HCST (ver 2.0) 20 | P a g e


Data Types Size (In Range of Data Types
Bytes)
char or signed char 1 -128 to 127
unsigned char 1 0 to 255
int or signed int 2 -32,768 to 32,767
unsigned int 2 0 to 65,535
float 4 3.4E-38 to 3.4E+38
double 8 1.7E-308 to 1.7E+308

void datatype:
• A void type has no value this is usually used to specify the return type of function;
• This function does not return any value to calling function.
Example: void main()
{
}

Storage Class:
• A storage class defines the scope (visibility) and life time of variables and/or functions within a C Program.
• There are following storage classes which can be used in a C Program

• auto
• register
• static
• extern

auto - Storage Class: auto is the default storage class for all local variables.
PRAMOD KUMAR, ASST. PROF., CSE DEPTT., HCST (ver 2.0) 21 | P a g e
void main()
{
int Count;
auto int Month;
}
The example above defines two variables with the same storage class. auto can only be used within functions, i.e.
local variables.
register - Storage Class:
• register is used to define local variables that should be stored in a register instead of RAM.
• This means that the variable has a maximum size equal to the register size (usually one word) and can’t have
the unary '&' operator applied to it (as it does not have a memory location).

void main()
{
register int Miles;
}
• Register should only be used for variables that require quick access - such as counters.
• It should also be noted that defining 'register' goes not mean that the variable will be stored in a register.
• It means that it MIGHT be stored in a register - depending on hardware and implementation restrictions.

static - Storage Class:


• static is the default storage class for global variables. The two variables below (count and road) both have a
static storage class.

#include<stdio.h>
static int Count;
int Road;
void main()
{
printf("%d\n", Road);
}
• static variables can be 'seen' within all functions in this source file. At link time, the static variables defined
here will not be seen by the object modules that are brought in.
• static can also be defined within a function. If this is done the variable is initialised at run time but is not
reinitialized when the function is called. This inside a function static variable retains its value during various
calls.

void func(void);
static count=10; /* Global variable - static is the default */
#include<stdio.h>
void main()
{
while (count--)
{
func();
}
}
void func( void )
{
static i = 5;
i++;
PRAMOD KUMAR, ASST. PROF., CSE DEPTT., HCST (ver 2.0) 22 | P a g e
printf("i is %d and count is %d\n", i, count);
}
Output:
i is 6 and count is 9
i is 7 and count is 8
i is 8 and count is 7
i is 9 and count is 6
i is 10 and count is 5
i is 11 and count is 4
i is 12 and count is 3
i is 13 and count is 2
i is 14 and count is 1
i is 15 and count is 0
extern - Storage Class
• extern is used to give a reference of a global variable that is visible to ALL the program files. When you use
'extern' the variable cannot be initialized as all it does is point the variable name at a storage location that
has been previously defined.
• When you have multiple files and you define a global variable or function which will be used in other files
also, then extern will be used in another file to give reference of defined variable or function. Just for
understanding extern is used to declare a global variable or function in another files.

File 1: main.c
int count=5;
main() PRAMOD KUMAR, Assist. Prof., CSE Department, HCST Mathura First Year (CS-A and CS-B) 20 | Page

{
write_extern();
}
File 2: write.c
void write_extern(void);
extern int count;
void write_extern(void)
{
printf("count is %i\n", count);
}
Here extern keyword is being used to declare count in another file.

PRAMOD KUMAR, ASST. PROF., CSE DEPTT., HCST (ver 2.0) 23 | P a g e

You might also like