0% found this document useful (0 votes)
110 views73 pages

Understanding Programming Languages

Uploaded by

sun077542
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)
110 views73 pages

Understanding Programming Languages

Uploaded by

sun077542
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

Programming Concept & Logic

Introduction
Computer Program: A computer program is the step by step set of instructions written in a specific
programming language that a computer‟s CPU can execute to solve a problem or perform a task.
The programs are again integrated to make software. Software is a collection of different interrelated
programs to perform specific function.
Computer programming means creating a set of instructions for a computer to accomplish a specific task.
Qualities of good program:
 It should be easily understood.
 A program should give accurate result.
 It should be error free.
 It should be portable and flexible.

Introduction to Programming Languages


 A programming language is a way for humans to communicate with computers.
 Computers only understand binary code (0s and 1s), which is difficult for humans to write or read.
 Programming languages make it easier by using English-like words and symbols to create commands.
 It provides a set of rules, symbols, and instructions that allow programmers to write programs

 Characteristics of a Programming Language

 The language should be easy to learn and understand.


 It should have a simple and clear syntax so that programmers can focus on solving problems, not
memorizing complex rules
 The language should use computer resources (memory, CPU time) effectively.
 Programs written in it should run fast and perform well.
 A good programming language should allow programs to run on different computers or operating
systems with little or no modification.
 The language should make it easy to modify or update programs later without breaking other parts of
the code.
 A good programming language should provide ways to detect and fix errors easily,
 Should provide single environment known as Integrated Development Environment (IDE).
Types of Programming Language

Figure: Classification of Programming language

1. Low level language: Low level language are the machine dependent language which means program
written for one type of system cannot be run in another system. Developer should have detail analysis
and knowledge about the system for which s/he is going to write a program for. Hence, programming in
low level language is very much difficult and time consuming. Different types of programming
language are:

a. Machine level language(1GL): This language consists a sequence of 0’s and 1’s to generate
instruction. Since, it uses binary numbers, this type of language is directly understood by processor. So, it
has higher execution speed. It is also a machine dependent language in which programmers should have
detailed knowledge of the system.

Advantage:

1. It is directly understood by the processor so execution speed is relatively high.


2. Language translator or processor is not needed.
3. They can be used to program specific purpose computer.

Disadvantage:

1. It is difficult and time consuming to develop and debug program.


2. It is machine dependent language. So, program developed for one system cannot be operated in
another system.
3. All the syntax and commands are in the form of binary numbers which is difficult to remember.
4. Programmers should have detail knowledge about particular system and its architecture.

b. Assembly language(2GL): Assembly language are also an example of low-level language. In this
language, instead of writing instruction in the series of 0‟s and 1‟s we can use mnemonics (symbolic
instructions) like ADD, SUB, RST, DIV, MOD and so on. Since it is closer to machine level language, a
programmer should have detailed knowledge about computer internal architecture. This language is faster in
comparison to high level language. Since, this language is not directly understood by the computer, we need
language translator like assembler to convert it into machine level language.

Advantage:
1. It is easier to write, debug and understand programming written in assembly level language
compared to machine level language.
2. Program execution is higher compared to high level language,
3. Since they are machine dependent, they are used to develop different device drivers.

Disadvantage:

1. It is machine dependent language, i.e. program made for one processor doesn‟t run in another
processor.
2. Use of mnemonics code makes assembly language much more complex.
3. Program development and debugging is more difficult and time consuming compared to high level
language.

Machine-Level Language Assembly Language


The machine level language comes at the lowest The assembly language comes above the machine
level in the hierarchy, so it has zero abstraction language means that it has less abstraction level
level from the hardware. from the hardware.

It cannot be easily understood by humans.


It is easy to read, write, and maintain.

The assembly language is written in simple


The machine-level language is written in binary
English language, so it is easily understandable
digits, i.e., 0 and 1.
by the users.
It does not require any translator as the machine In assembly language, the assembler is used to
code is directly executed by the computer. convert the assembly code into machine code.

It is a first-generation programming language. It is a second-generation programming language.

2. High level language: This language is close to English language. High level language code is written in
English like structure using mathematical notation. Since it is similar to English language, it is easier to
develop and debug the program. It is machine independent language (i.e. program developed for one
processor can work on another processor). Since HLL (high level language) are not directly understood by
the computers, we need language processor or translator such as complier and interpreter for converting
program written in high level language to machine level language. E.g. FORTAN (Formula Translator), C,
C++, python, JavaScript, etc.

Advantage:

1. Since it is closer to English language, program written in this language is easier to write, debug and
understand.
2. Since it is machine independent, program written for one processor can work in another processor.
3. Programmer doesn‟t have to remember large number of mnemonics and other unusual codes.
4. Program development is faster and requires less effort than other language.

Disadvantage:
1. Computer doesn‟t understand high level language directly. So the program needs conversion before
execution.
2. Program execution is slower compared to low level language.

High level language can further be classified into:

a. Procedural oriented Language (3GL):

 This type of language is high level language which primarily focuses on procedure rather than on
data. Hence, they are used to express the logic and the procedure of the program.
 Since it focuses only on procedure, it is complex and time consuming to write a large program. This
type of language follows top to bottom approach i.e. main function is written at the bottom of the
program.
 Because of their flexibility, procedure language is able to solve varieties of problem. Examples: C,
FORTAN, QBasic, etc.

Advantage:

1. Program development and debugging is easier compared to low level language.


2. More advance and user-friendly software can be developed.
3. It is also a machine independent language.
4. It is used as general purpose programming.

Disadvantage:

1. Language translator or processor is required to execute the program.


2. Program execution is slower.
3. Data security is less in comparison to other high-level language.

b. Problem/object Oriented Language(4GL):

 This is the advance form of high-level language which primarily focuses on data rather than
procedure.
 It allows the user to specify what the output should be without describing all the detail (i.e.
procedure) of how the data should be manipulated.
 This type of language follows bottom up approach.
 Since it has several powerful features such as data encapsulation, data extraction and inheritance,
the data are more secure compared to procedure language. Examples: C#, C++, Java, etc.

Advantage:

1. Web based application and software can be developed.


2. More advance and user-friendly software can be developed.
3. It is also machine independent language.

Disadvantage:

1. Language translator is required to execute the program.


2. Program execution is slower.
3. It is difficult to develop hardware-oriented language.
c. Natural Language (5GL): Natural language uses simple statement of common communication language
where we could write statements that would look like normal sentences. It is still in developing stage;
computer scientists are working hard for developing such language.

Advantage:

1. It will be even easier to develop and debug the program.


2. It will also be machine independent language.
3. More advance and user-friendly program will be made.

Disadvantage:

1. Language translator is required to execute the program.


2. Program execution is slower
3. It is difficult to develop hardware-oriented language.

Language translator/processor:
Language translator is that system development software which helps to convert program written in
assembly or high-level language (source program) into machine level language (object program).

Since it is difficult and inconvenient to write a program in machine level language, language developer uses
several assemblies and high level language which are not directly understood by the computer.

Hence, we use different types of language processor to convert and make machine understandable. There
are different types of language translators.

1. Assembler:

These language translator/processor converts program written in assembly level language (source
program) into machine understandable language (object language)

Since assembly level language are closer to machine level language, the conversion taken by
assembler is relatively less.

It converts program at once into machine level language.

2. Compiler:

These language processors help to convert program written in high level language (source program)
into machine level program (object program).

It converts whole program into machine level language at once.

It is the largest method of translating a program in which debugging is complex and time consuming.

Programming languages like C, C++, Java, etc. use complier

3. Interpreter:

This is the type of language which converts program written in high level language (source program)
into machine level language (object program).
It converts one statement at a time so its debugging can be easier and less time consuming.

Its program execution is slower than that of compiler.

Most of the new programming language use interpreter which allocate less memory space.

Programs like BASIC, C#, Php, etc. use interpreter for conversion.

Difference between compiler and interpreter:


S.n Compiler Interpreter
It translates the whole program into object It translates one line or a single statement of a program
1
code at a time. into object code at a time.

It finds out the error after compiling the It finds out the error after translating a line of the
2
complete program. program at a time.

3 The translating process is incredibly faster. The translating process is slower.

Compiler based program is difficult to code


4 Interpreter based program is easy to code and debug.
and debug.

It is usually a large program and requires larger It is usually a smaller program and requires less
5
memory space. memory space.

6 For e.g.: C, C++, java, FORTAN etc. For e.g.: BASIC. C#, PHP etc.

 Error (BUG):

There may be several errors inside a program which stops program from being executed. Thus, an error in a
program is known as a bug. This type of error in a program may arise by not following proper rules given by
the programming language due to poor problem analysis or maybe due to hardware failure. Error in the
program may five ambiguous (not accepted/false) result. The process of removing error from a computer
program is known as debugging. There are three types of error:

1. Syntax error:
 The error which may arise due to not following proper rules or format given by the programming
language.
 Every programming language have their own vocabulary, punctuation and structure.
Programmers need to follow every detail while programming.
 This type of error can be detected by language processor such as compilers and interpreter.
 For e.g. In C, every statement should end with semi-colon at the end of the statement then the
errors encounter is syntax error.

2. Logical error:
 Logic refers to idea or concept used to solve a specific problem.
 The error that is encountered due to poorly developed logic is called logical error.
 This type of error is not detected by language processor.
 For example: In order to calculate simple interest, we use the formula I =(P*T*R)/100, if we write
above mentioned formula, as I=P*T*R, then the error encounter is logical error.

3. Runtime error:

 When a program is running or executing, it is said to be runtime.


 The error that are encounters/found while program is being executed is known as runtime error.
 It is also not detected by language translator.
 For example: if insufficient memory space, peripheral device not turning on.
Program Design Tools

To facilitate a computer to solve problems effectively, clear and to the point instructions must be
provided to it. A programmer must provide clear instruction to perform task and he must have a plan to
solve particular problem using programming tools like algorithm, flowchart and pseudo code.

 Algorithm
An algorithm is the step wise logical instructions written in any human understandable language to solve
particular problem in a finite amount of time. It is written in simple English language. Some of the basic
rules to write algorithm are as follows:
 All the instructions of algorithm should be simple.
 The logic of each step must be clear.
 There should be finite number of steps for solving problems.
Advantages of Algorithm
 It is a step-wise representation of a solution to a given problem
 It easy to understand because it is not dependent on any programming language
 It uses a definite procedure.
 Every step in an algorithm has its own logical sequence so it is easy to debug.
 It is easier for programmer to convert it into an actual program
Disadvantages of Algorithm
 Writing algorithm takes a long time.
 It is not a computer program; it is rather a concept of how a program should be.
Algorithm to calculate sum of two numbers STEP 1: Start
STEP 2: Accept the first number A STEP 3: Accept the second number B STEP 4: Add A and B, and
store in SUM STEP 5: Display the value of SUM STEP 6: Stop

 Flowchart
Flowchart is a pictorial representation of stepwise solution of a problem which helps programmer in
developing the program logic and serve as documentation for future reference. It uses different boxes linked
by the arrows. The process of drawing flowchart is flowcharting. Basically there are two types of flowchart
like systems flowchart and program flowchart.
System Flowchart
System Flowchart is a way of displaying how data flows in a system and how decisions are made to control
events. System flow charts are very similar to data flow charts. Data flow charts do not include decisions,
they just show the path that data takes, where it is held, processed, and then output. Symbols are used to
illustrate flow of data which are listed below:
Symbol Meaning Symbol Meaning
Input/output Manual operation

Paper document Magnetic tape

Online display Direct access storage


device
Online input Flowline

Punched card Telecommunications


link

Process Predefined process

Terminal Decision

Figure 5.10: System Flowchart

Program Flowchart
Program Flowchart is a diagrammatic representation of sequence of logical steps of a program. Flowcharts
use simple geometric shapes to depict processes and arrows to show relationships and process/data flow:
Symbol Symbol Name Purpose
Used at the beginning and end of the
Start/Stop algorithm to show start and end of the
program.
Process Indicates processes like mathematical
operations.

Input/Output Used for denoting program inputs and outputs.

Decision Stands for decision statements in a program,


where answer is usually Yes or No.

Arrow Shows relationships between different shapes.

On-page Connects two or more parts of a flowchart,


Connector which are on the same page.

Off-page Connects two of a flowchart which are spread


Connector over different pages.

Figure 5.11: Program Flowchart


Advantages of a Flowchart
 Easy to understand a graphical representation
 It is a convenient aid for writing computer instructions.
 It becomes easier to review the steps and make corrections, if necessary.
 Comparison of different methods of solving a problem becomes very easy.
Disadvantages of a Flowchart
 Drawing a flowchart for large and complex problems is time-consuming and boring.
 Consists of symbols, changes or modifications will need a new flowchart to be drawn.
 No set standards specifying the details of the data that should be shown in a flowchart.

Figure 5.12: Flowchart to calculate the sum of two numbers

 Pseudo code
Pseudo code is an informal high-level representation of the actual code that shows how an algorithm or a
computer program works in plain English. Since it has no specific syntax, it is easy to read and write, and
programmers can comfortably communicate ideas and concepts, even if they are working on different
programming languages.
Advantages of Pseudo code
 Can be writing, modify and implement easily on a word processor
 Clarify algorithms in many cases.
 Provide additional level at which inspection can be performed.
 Increases product reliability and decreases overall costs.
Disadvantages of Pseudo code
 It's not visual
 Create an additional level of documentation to maintain.
 Introduce error possibilities in translating to code.
 Require tool to extract pseudo code and facilitate drawing flowcharts.
 There is no accepted standard, so it varies widely from company to company
Pseudo code to display result on the basis of grade. Start
Input grade
If grade >= 60 Print "passed"
else
Print "failed" Stop
5.1.2 Absolute Binary, BCD, ASCII and Unicode
In computer system, only binary numbers 0 and 1are used where 0 represents low signal and 1
represent high voltage. Binary codes (notation) are used to represent data for user convenience. Different
standard codes are used in computer system like Absolute Binary, BCD, ASCII and Unicode.

 Absolute Binary
In normal mathematics we used plus (+) and minus (-) sign to represent numeric value but in binary number
system we use 1 and 0 for positive and negative value respectively. The binary value of 25 is equal to
11001. So in 8- bit absolute binary +25 is represent with 111001 where as -25 is represent with 011001.
 BCD
BCD (Binary Coded Decimal) is a process for converting decimal numbers into their binary equivalents
where each decimal digit is represented by a group of 4 binary digits or bits and binary coded decimal
numbers stop at 9 binary (1001) 2. BCD for decimal 9 is (1001)2 where as BCD for 22 is (0010 0010)2.

 ASCII
ASCII (American Standard Code for Information Interchange) is a 7-bit character code which represents
128 unique characters. Extra non-English characters, graphics symbols and mathematical symbols uses 8
bits, which gives them 128 additional characters. ASCII code for 1 is 49, 2 is 50 whereas A is 65 and B is
66.

 Unicode
Unicode is a universal character encoding standardwas designed to support characters from all languages
around the world. Unicode supports up to 4 bytes for each character which can support roughly 1,000,000
characters.

5.2 C Programming Language


C programming is a general-purpose, procedural, imperative computer programming language
developed at the Bell Telephone Laboratories in 1972 by Dennis M. Ritchie to develop the UNIX operating
system. C is the most widely used computer language. It was initially used for system development work,
particularly the programs that make-up the operating system.
5.2.1 Introduction and Feature of C Language

Introduction
C is a general-purpose programming language that is extremely popular, simple and flexible. It is
machine-independent, structured programming language which is used extensively in various applications.
In 1967, Martin Richards develop a new computer programming language was announced called as BCPL
(Basic Combined Programming Language) especially for writing system software.
A great scientist Dennis Ritchie develops a new programming language called 'C' at the Bell
Laboratories in 1972.C' is a powerful programming language which is strongly associated with the UNIX
operating system. Even most of the UNIX operating system is coded in 'C'. Initially 'C' programming was
limited to the UNIX
operating system, but as it started spreading around the world, it became commercial, and many compilers
were released for cross-platform systems.
Feature of C Language
C is a general-purpose programming language that is extremely popular, simple and flexible. It
becomes popular because of some basic features, which are listed below:
 Portability refers to the usability of the same code in different environments.
 Modularity/Structured Language is a feature which allows the program to be splintered (broken) into
smaller units (module) and run individually with the help of functions.
 Simple and Efficient, syntax and code of C programming is easy to comprehend and can be used to design
applications that were previously designed by assembly language.
 Speed, is comparatively faster than other programming languages like Java or Python
 Popular, is one of the most widely used languages in the development of operating and embedded systems.
 Existence of Libraries comprises of its library which has a wide range of built-in functions. Even the user-
defined functions can be added to the C library.
 Dynamism, supports the feature of DMA (Dynamic Memory Allocation), which helps in the utilization and
management of memory by using some predefined functions in the C library such as malloc(), calloc(),
free() and realloc().
 Case Sensitive, treats lowercase and uppercase characters differently.
5.2.2 Structure of C Program

Several building blocks called function are used in C programming language where each function can
perform specific job independently. Structure of C program is listed below:
Comments
It is simply a information about the program which inform flow of program to programmer. There are two
types of comment as following:
Single line comment, which if followed by two forward slash Example:
//Information
Multiple line comment, which is enclosed between pair of forward slash and asterisk sign. Example: /*
Information 1
Information 2
Information 3 */
Header File
Header file is a file that contains function declaration and macro definition for C in-built library functions.
When we include header files in our C program using “#include <filename.h>” command, all C code of the
header files are included in C program. Example: #include<stdio.h>
Global Declaration
Those variables declared outside of main program to use in different function are called global variables.
main()
This function is the main part of the program and also called body of the program. Every code or instruction
are written in main( ) function in C programming.
Declaration
It is also called initialization part where a local variable are declared and can be used inside that particular
function only.
Executable Part
All the blocks of statement like input, process and output statement of a body are mention in executable
parts.
User define function
These are the function which can be defined by the user to fulfill their requirement. It can be define
before as well as after the main function.
Function header
They are the header or prototype of the function. Function prototype should be define to declared user define
function.
Example of Structure of Program:
//Program to find the product of two numbers // Comments
#include<stdio.h>
#include<conio.h> //Header File
int pro(int, int); //Function prototype
int p; //Global Declaration
void main( ) //main function
{
int a,b; //Declaration part
printf(“Enter any two number :”); scanf(“%d %d”,&a,&b);
p=pro(a,b); //Executable part
printf(“Product = %d”,p); getch( );
}
Int pro(int x,int y) //User define function
{
int z;
z=x*y; //Body of user define_function
return(z);
}
Compilation Process
Process of translating source code written in high level to low level machine code is called as Compilation.
The compilation is done by special software known as compiler. The compiler checks source code for any
syntactical or structural errors and generates object code with extension .obj (in Windows) or
.o (in Linux) if source code is error free. C compilation is broken to four stages which are listed below:
Figure 5.13: Compilation Process

Pre-processing
Compilation begins with pre-processing of source file which is small software that accepts C source file and
performs following tasks like remove comments from the source code, macro expansion and expansion of
included header files. It inserts contents of header files to source code file. Pre-processor generated file is
larger than the original source file.
Compilation
Compiler accepts temporary pre-processed <file-name>.i file generated by the pre-processor and performs
following tasks like check program for syntax errors, translate the file into intermediate code and optimize
the translated code for better performance. After compiling it generates an intermediate code in assembly
language as <file-name.s> file.
Assembling
Assembler accepts the compiled source code (compilation.s) and translates to low level machine code. After
successful assembling it generates <file- name.o> (in Linux) or <[Link]> (in Windows) file known as
object file. This file is encoded in machine language and cannot be viewed using text editors.
Linking
Linker performs the final task of compilation process which accepts the intermediate file <file-name.o>
generated by the assembler. It links all the function calls with their original definition. Which means the
function printf() gets linked to its original [Link] generates the final executable file (.exe in
windows).
5.2.3 C Preprocessor and Header Files

C Preprocessor
It is just a text substitution tool which instructs the compiler to do require pre- processing before the
actual compilation. It is not a part of the compiler, but is a separate step in the compilation process.
All preprocessor commands begin with a hash symbol (#). It must be the first nonblank character, and
for readability, a preprocessor directive should begin in the first column. The following section lists down
all the important preprocessor directives:

[Link]. Directive & Description

#define
1
Substitutes a preprocessor macro.

#include
2
Inserts a particular header from another file.

#if
3
Tests if a compile time condition is true.

#else
4
The alternative for #if.
Table 5.4: C Preprocessor

Header Files
Header files are those file having extension “.h” which holds the definitions of various functions and
their associated variables that needs to be imported into your program with the help of pre-processor
#include statement. There are lots header files found in C program some of commonly used are as follows;
 #include<stdio.h>: Standard Input Output header file which deals with basic input/output function like
scanf( ) and printf( ).
 #include<conio.h>: CONsole Input Output header file which deals console controlling function like clrscr(
) and getch( ).
 #include<string.h>: It includes string manipulating function. So this header file should be included to
program to use string function like strlen( ), strcpy ( ), strlwr( ) etc.
 #include<math.h>: This header file should be included to the program to use mathematical function like
sqrt( ), pow( ) etc.
5.2.4 Character set used in C

A set of characters used to construct words, statements, etc. is called character set which include
alphabets, digits, and special symbols. Statements are constructed using words and these words are
constructed using characters from C character set. C language character set contains the following set of
characters.
Alphabets
C language supports all the alphabets from the English language. Lower and upper case letters
together support 52 alphabets.
lower case letters - a to z
UPPER CASE LETTERS - A to Z
Digits
C language supports 10 digits which are used to construct numerical values in C language.
Digits - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
Special Symbols
C language supports a rich set of special symbols that include symbols to perform mathematical
operations, to check conditions, white spaces, backspaces, and other special symbols.
Special Symbols - ~ @ # $ % ^ & * ( ) _ - + = { } [ ] ; : ' " / ? . > , < \ | tab newline space NULL
backspace etc.,
5.2.5 Use of Comments
A comment is a explanation or annotation in the source code of a computer program. They are added
with the purpose of making the source code easier for humans to understand, and are generally ignored by
compilers and interpreters. Comment can be written in two forms:
 Single line comment, follows by two forward slash Example: //Information
 Multiple line comment, which is enclosed between pair of forward slash and asterisk sign. Example:
/*Information 1
Information 2
Information 3 */
5.2.6 Identifiers, Keywords and Tokens
Tokens
Tokens are the smallest elements of a program, which are meaningful to the compiler. The
following are the types of tokens:
 Keywords
 Identifiers
 Constant
 Strings
 Operators, etc
Keywords
Keywords have fixed meanings, and the meaning cannot be changed. They act as a building block of a
'C' program. There are a total of 32 keywords in 'C'. Keywords are written in lowercase letters.
auto double int struct
break else long switch
case enum register typedef
char extern return union
const short float unsigned
continue for signed void
default goto sizeof volatile
do if static while
Table 5.5: C Keywords
Identifiers
An identifier is a name assigned to an element used in a program like name of a variable, function, etc.
Identifiers are the user-defined names consisting of 'C' standard character set. Each identifier must have a
unique name. The following rules must be followed for identifiers:
 The first character must always be an alphabet or an underscore.
 It should be formed using only letters, numbers, or underscore.
 A keyword cannot be used as an identifier.
 It should not contain any whitespace character.
 The name must be meaningful.
5.2.7 Basic Data Types in C

A data type is a data storage format that can contain a specific type or range of values. When a
program store data in variables, each variable must be assigned a specific data type.

Primary data type Secondary data type

Figure 5.13: Categorize of Data type

Basically data types are categorized into two types:


 Primary Data Type
These are fundamental data types. These are also called predefined data types which are already
defined by the C program. Some of predefine data types are as follows:
Variable Type Keyword Bytes Required Range
Character Char 1 -128 to 127
Unsigned character Unsigned char 1 0 to 255
Integer Int 2 - 32768 to 32767
Short Integer Short int 2 -32768 TO 32767
Long Integer Long int 4 - 2147483648 to 2147438647
Unsigned Integer Unsigned int 2 0 to 65535
Unsigned Short integer Unsigned short int 2 0 to 65535
Unsigned Long Integer Unsigned long int 4 0 to 4294967295
Float Float 4 1.2E-38 to
Double Double 8 2.2E-308 to
Long Double Long double 10 3.4E-4932 to 1.1E+4932
Table 5.6: Primary Data Type

 Secondary Data Type


These are derived data types which are created from the primary data types integers, characters and
floating data types. Array, Structure, Pointer etc. are the example of secondary data types.
5.2.8 Constants and Variables

Constants
Constants (literals) are also like normal variables, only difference is, their values cannot be modified
by the program once they are defined. They are fixed values within a program and can be of any types like
integer, float, octal, hexadecimal, character with some range where integers are too big to fit into an int will
be taken as long. Constants refer to fixed values may belonging to any of the data type.
Constant Type Data Type Data Type (Example)
Integer constants
- Decimal Integer Constant int 53, 762, -478
- Octal Integer Constant int 0576, 0676, 026
- Hexadecimal Integer Constant int 0x2, 0xDAF,

Floating point constants float 10.45, 435.457, 6.0, -13,25


Character constants char „A‟, „B‟, „C‟
String constants char “ABCD”, “Hai”
Symbolic Constant #define PI 3.14, name “College”
\a Audible Alert (Bell)
\b Backspace
\n New Line
Escape Sequence Constant
\r Carriage Return
\t Horizontal Tab
\v Vertical Tab
Table 5.7: Constants in C

Variables
Variable is a name of location in a memory where a program can manipulate the data which is used to
hold numeric as well as character value of the variable. Variable may get change in the program which
might belong to any of the data type like int, float, char etc. Few rules should consider while declaring
variables:
 They can be declared with digits, letters.
 Variable name must begin with letter or underscore.
 Variables are case sensitive
 No special symbols are allowed other than underscore. Examples: sum, height, _value
Variables Declaration and Initialization
Variables must be declared before they are used in the C program. C variables, abc, Abc and ABC are
all different because of case sensitive.
Declaration and initialization of variable in can be done using following syntax: Syntax:
data_type variable_name=constant (literal); Example:
int a=10;
float x=43.25; char p=‟w‟;
5.2.9 Type of Specifiers

Format specifier is a way to tell the compiler what type of data is in a variable during taking input
using scanf() or printing using printf(). Each format specifier starts with a percentage (%) sign and followed
with specific character.
Format Specifier Meaning
%c Single character
%s String value
%d Integer (decimal) value
%f Floating point without exponent
%e Floating point with exponent
%i Signed decimal integer
%ld Long integer
Table 5.8: Type of Specifier

5.2.10 Simple and Compound Statement

A statement is a instruction given to the computer to take a specific action, such as display to the
screen, or collect input. The bodies of C functions (including the main function) are made up of statements.
Basically there are two types of statement which are listed below:
 Simple statements: - Those statements which do not contain other statements. Each statement is terminates
by semicolon. None of the statement has relation with each other.
Example:
a=5; b=6;
z=x+y;
 Compound statements:- Those statements which have other statements inside them. All statements are
enclosed by pair of curly braces {}, which have relation with each other.
Example:
{
l=5; b=7;
area=l*b;
}
5.2.11 Operators and Expressions
An operator is a symbol which tells the compiler to perform a certain mathematical or logical
manipulation of data and variables. C language supports a rich set of built-in operators.
 Arithmetic Operators
 Relational Operators
 Assignment Operators
 Logical Operators
 Unary Operators
 Conditional Operators
Arithmetic Operators
Operators which perform mathematical operations such as addition, subtraction, multiplication,
division etc on numerical values (constants and variables) are arithmetic operators.
Operator Meaning of Operator
+ addition or unary plus
- subtraction or unary minus
* Multiplication
/ Division
% remainder after division (modulo division)
Table 5.9: Arithmetic Operators

Relational Operators
Those operators checks the relationship between two operands are relational operators. If the
relation is true, it returns 1; if the relation is false, it returns value 0.

Operator Meaning of Operator Example


== Equal to 5 == 3 is evaluated to 0
> Greater than 5 > 3 is evaluated to 1
< Less than 5 < 3 is evaluated to 0
!= Not equal to 5 != 3 is evaluated to 1
>= Greater than or equal to 5 >= 3 is evaluated to 1
<= Less than or equal to 5 <= 3 is evaluated to 0
Table 5.10: Relational Operators
Assignment Operators
Operator used for assigning a value to a variable is called assignment operator.
Equal to (=) is the most common assignment operator.

Operator Example Same as


= a=b a=b
+= a += b a = a+b
-= a -= b a = a-b
*= a *= b a = a*b
/= a /= b a = a/b
%= a %= b a = a%b
Table 5.11: Assignment Operators

Logical Operators
Logical operators are commonly used in decision making which returns either 0 or 1 depending upon
expression‟s results true or false.

Operator Meaning Example


If c = 5 and d = 2 then, expression ((c==5) &&
&& Logical AND
(d>5)) equals to 0.

If c = 5 and d = 2 then, expression ((c==5) ||


|| Logical OR
(d>5)) equals to 1.

! Logical NOT If c = 5 then, expression !(c==5) equals to 0.


Table 5.12: Logical Operators
Unary Operators
Special operators which operate upon one operand only are called unary operators or monadic
operators. Increment (++) increased its operand by 1whereas decrement (--) decrease the value of operands
by one.
++ Operands (prefix)  First increment then implement Operands ++ (postfix)  First implement then
increment
-- Operands (prefix)  First decrement then implement Operands -- (postfix)  First implement then
decrement
Conditional Operators
Conditional operator, known as ternary operator, is similar to the if-else statement as it does follow the
same algorithm as of if-else statement but the conditional operator takes less space and helps to write the if-
else statements in the shortest way possible. It uses two operator question mark (?) and colon (:) separately.
Syntax:
(condition)?statement1:statement2
Example:
Result = (marks>=40) ? ”Pass”: ”Fail”
Here in given example if marks are greater or equal to 40 then the value Pass will store to result otherwise
Fail will store.
Special Operators
The Special Operators are used for special functions in C programs. Some of the Special Operators
available in C language are as follows:
 Comma Operators
 Size of Operators
Comma Operators
Sometimes we assign multiple values to a variable using comma; in that case comma is known as
operator. Here the expressions are evaluated in left to right order.
Example:
Sum=(a=3,b=5,a+b);
Here, first 3 is assigned to variable „a‟ and then 5 is assigned to variable „b‟ and finally 8 is assigned to
variable „Sum‟.
Size of Operator
The size of operator is a compile-time unary operator which is used to compute the size of its operand
and returns the size of a variable. It can be applied to any data type, float type, pointer type variables.
Example:
//Using variable names as input
printf("The size of int is: %d\n", sizeof(x)); printf("The size of char is %d\n", sizeof(y));
//Using datatype as input
printf("The size of float is: %d\n", sizeof(float));
Precedence and Associativity
Operator precedence determines which operator is performed first in an expression with more than one
operator with different precedence where as associativity is used when two operators of same precedence appear
in an expression. Associativity can be either Left to Right or Right to Left.

Category Operator Associativity


Postfix () [] -> . ++ - - Left to right
Unary + - ! ~ ++ - - (type)* & sizeof Right to left
Multiplicative */% Left to right
Additive +- Left to right
Bitwise Shift <<>> Left to right
Relational <<= >>= Left to right
Equality == != Left to right
Bitwise AND & Left to right
Bitwise XOR ^ Left to right
Bitwise OR | Left to right
Logical AND && Left to right
Logical OR || Left to right
Conditional ?: Right to left
= += -= *= /= %=>>= <<= &=
Assignment Right to left
^= |=
Comma , Left to right
Table 5.13: Precedence and Associativity
Expression
Expression is a combination of operators, constants and variables which may consist of one or more
operands, and zero or more operators to produce value. Operands are values, whereas operators are symbols
that represent particular actions. Here in x + 5, x and 5 are operands, + is an operator and x+5 is expression.
Normal algebraic equation can be differing from C expression and some of them are listed below:
Algebraic Equation C Expression
(a+b) (p+q) (a+b) * (p+q)
ab/c A*b/c
2x2+2x+1 2*x*x+2*x+1
Table 5.14: Expression

5.2.12 Input / Output (I/O) Function

The “core” of C does not include any Input/Output (I/O) functionality which is common for the
language core to be agnostic of I/O. In the case of C, Input/Output is provided to us by the standard library
via a set of functions defined in the stdio.h header file. C library provides us various input /output (I/O)
function like printf(), scanf(), sscanf(), fgets(), fprintf(), getch(), getchar() and putchar() etc. Among them
printf() and scanf() are the most commonly used input / output function.
printf()
printf() is one of most common function used in C programming. Simple string can be displayed without
inserting any format to printf().
Example:
printf("Hello World");
While printing the value of a variable one need to add a special character, a placeholder, which changes
depending on the type of the variable. For example we use %d for a integers.
Example:
int age = 37;
printf("My age is %d", age);
Here, everything inside double quotes are termed as message except %d (format specifier) which represents
the types of data to call and age is a variable which hold any data identifies by format specifier.
scanf( )
scanf() is the most commonly used input function of C library included in stdio.h header file which is used
to get a value from the user running the program. The function scanf() have 2 arguments inside it: the format
specifier and the address of the variable:
Example:
scanf("%d", &age);
Here, %d is format specifier which indicates the data types and &age indicates the address of variable
“age”.
Program 1: Find the square of a number.
#include<stdio.h> #include<conio.h> void main()
{
int num,sqr; printf("Enter any no: "); scanf("%d",&num); sqr=num*num;
printf("Square of %d = %d",num,sqr); getch();
}
Program 2: Find area of triangle. #include<stdio.h> #include<conio.h>
void main()
{
float b=0,h,a=0;
printf("Enter the base of triangle\t"); scanf("%f",&b);
printf("Enter height of triangle\t"); scanf("%f”,&h);
a=0.5*b*h;
printf("The Area of triangle is %.2f",a); getch();
}
getchar( ) and putchar()
The function getchar() reads single character from the standard input and store to the variables which is not
capable to hold multiple character.
The function putchar() is used to display or output a single character stored in variable to the terminal.
Example:
#include <stdio.h> #include <conio.h> void main ()
{
char c;
printf("Enter character: "); c = getchar();
printf("Character entered: "); putchar(c);
getch();
}
gets() and puts()
The function gets() reads string (multiple characters) from the standard input and store to the variables.
The function puts() is used to display or output a string (multiple characters) stored in variable to the
terminal.
Example: #include <stdio.h>
#include <string.h> int main()
{
char str[10];
printf("Enter your string\n");
gets(str); //read words entered by the user printf("Your string is : \n");
puts(str); //display the word getch();
}
Program 3: Find the cube of a number.
#include<stdio.h> #include<conio.h> void main()
{
int l,c;
printf("\n enter the length of cube: "); scanf("%d",&l);
c=l*l*l;
printf("\n Volume of cube = %d",c); getch();
}
Program 4: Calculate the simple interest.
#include<conio.h> #include<stdio.h> void main()
{
int p,t,a; float r,s;
printf("\n Enter Principal, Time and Rate"); scanf("%d%d%f",&p,&t,&r); s=(p*t*r)/100;
a=s+p;
printf("\n Simple Interest is %f \n Net Amount is %d ",s,a); getch();
}
Program 5: Convert seconds in Hour, Minute and Second.
#include <conio.h> #include <stdio.h> void main()
{
int s,m,h,hh,ss; printf("\n Enter time in
seconds");
scanf("%d",&s); h=s/3600; hh=s%3600; m=hh/60; ss=hh%60;
printf("\n %d seconds is \n %d hours %d minutes %d seconds",s,h,m,ss); getch();
}
5.2.13 Selection Control Statement

Selection control structures branch the flow of program based on decision. It is also called an "If-Then-
Else" structure which allows one set of statements to be executed if a condition is true and another set of
actions to be executed if a condition is false. It can be categorized into two types;
 Conditional Statement
 Switch Case Statement
Conditional Statements are used to make decisions based on the conditions. The process is called
decision making if some condition are put for a block of statements, the execution flow may change based
on the result evaluated by the condition. And can be used in different form:
 if statement
 if else statement
 if else if statement
 nested if statement
 if statement
This is the conditional structure where the block of statement enclose between pair of curly braces are
executed if the condition is true. There are no optional statements if the condition is false.
Syntax:
fase
if (condition)
{
Statement;
} Figure 5.14: if statement
Program 6: Check if the given number is even.
#include<stdio.h> #include<stdlib.h> void main()
{
int a;
printf("Enter a number: "); scanf("%d",&a); if(a%2==0)
{
printf("%d is even number.",a);
}
getch();
}
Program 7: Check if the given number is positive.
#include<stdio.h> #include<conio.h> void main()
{
int a;
printf("Enter a number : "); scanf("%d",&a);
if(a>0)
{
printf("%d is positive number.",a);
}
getch();
}
 if else statement
This is the conditional structure where the block of statement written inside if part is executed if the
condition is true otherwise statement written inside else part is executed false.
Syntax:

Figure 5.15: if else statement

if (condition)
{
Statement 1;
}
else
{
Statement 2;
}
Program 8: Check if the given number is even or odd.
#include<stdio.h> #include<stdlib.h> void main()
{
int a;
printf("Enter a number: "); scanf("%d",&a);
if(a%2==0)
{
printf("%d is even number.",a);
}
else
{
printf(""%d is odd number.",a);
}
getch();
}
Program 9: Check if the given number is positive or negative.
#include<stdio.h> #include<conio.h> void main()
{
int a;
printf("Enter a number : "); scanf("%d",&a);
if(a>0)
{
printf("%d is positive number.",a);
}
else
{
printf("%d is negative number.",a);
}
getch();
}
 if else if statement
if statements are executed from the top down where user can decide among multiple options. As soon as one
of the conditions controlling the if is true, the statement associated with that if is executed, and the rest else-
if ladder is bypassed. If none of the conditions are true, then the final else statement will be executed.
Syntax:
if (condition1)
{
Statement1;
}
else if (condition 2)
{
Statement2;
}
else if (condition 3)
{
Statement3;
Figure 5.16: if else if statement
}
else (condition)
{
Statement;
}
Program 10: Check smallest among three numbers.
#include<stdio.h> #include<conio.h> void main()
{
int a,b,c;
printf("Enter any 3 numbers: ");
scanf("%d%d%d",&a,&b,&c); if(a<b&&a<c)
printf("The smallest no is: %d",a); else if(b<a&&b<c)
printf("The smallest no is: %d",b); else
printf("The smallest no is: %d",c); getch();
}
Program 11: Check given numbers is positive, negative or zero.
#include<stdio.h> #include<conio.h> void main()
{
int a;
printf("Enter a number\t"); scanf("%d",&a);
if(a>0)
{
printf("%d is positive number.",a);
}
else if(a<0)
{
printf("%d is negative number.",a);
}
else
{
printf("%d is not a number.",a);
}
getch();
}
Nested if else
A nested if is statement that is the target of another if statement where one if statement is placed inside
another if statement. After satisfying outer condition then only inner if condition will checked otherwise else
part of outer if is executed.
Syntax;
if (condition1)
{
if(condition2)
{
Statement 1;
}
else
{
Statement 2;
}
Figure 5.17: Nested if else
}
else
{
Statement;
}
Program 12: Find the largest among 3 no. using nested if statement.
#include<stdio.h> #include<conio.h>
void main()
{
int a,b,c;
printf("\n enter any three no."); scanf("%d%d%d",&a,&b,&c);
if(a>b)
{
if(a>c)
{
printf("\n %d is largest ",a);
}
else
{
printf("\n %d is largest",c);
}
}
else if(b>a)
{
if(b>c)
{
printf("\n %d is largest",b);
}
}
getch();
}
Program 13: Check given numbers is positive, negative and number should not be zero.
#include<stdio.h> #include<conio.h> void main()
{
int a;
printf("Enter a number\t"); scanf("%d",&a);
if(a!=0)
{
if(a>0)
{
printf("%d is positive number.",a);
}
else
{
printf("%d is negative number.",a);
}
}
else
{
printf(" You Entered %d. Please enter any other number.",a);
}
getch();
}
Switch Case Statement
Switch statement, called menu based statement, tests the value of a variable and compares with multiple
cases. Once the case is matched then block of statements associated with that particular case is executed.
Otherwise, the default statement is executed, and the control goes out of the switch block.
Syntax:
switch( variable)
{
case value-1:
Statement1; break;
case value-2:
Statement2; break;
case value-3:
Statement3; break;
default:
Figure 5.18: Switch Case Statement
Statement;
}
Program 14: Menu driven program to enter a 2 no. and calculate following:
1=Sum 2=Difference 3=Product #include<stdio.h> #include<conio.h> void main()
{
int a,b,c,ch;
printf("\n Enter any two no: "); scanf("%d %d",&a,&b);
printf("\n Sum= 1\n Difference= 2\n Product= 3"); printf("\n enter choice your from 1 to 3\n");
scanf("%d",&ch);
switch(ch)
{
case 1:
c=a+b;
printf("\n Sum = %d",c); break;
case 2:
c=a-b;
printf("\n Difference = %d",c); break;
case 3:
c=a*b;
printf("\n Product = %d",c); break;
default:
printf("\n Enter choice from 1 - 4,try again");
}
getch();
}
Program 15: Menu driven program to display the name of the days of a week according to the
number entered.
#include<stdio.h> #include<conio.h> void main()
{
int ch;
printf("\n Enter your choice from 1 - 7\n"); scanf("%d”,&ch);
switch(ch)
{
case 1: printf("Sunday"); break;
case 2: printf("Monday"); break;
case 3: printf("Tuesday"); break;
case 4: printf("Wednesday"); break;
case 5: printf("Thursday"); break;
case 6:
printf("Friday"); break;
case 7: printf("Saturday"); break;
default:
printf("Invalid Choice, Enter from 1 - 7");
}
getch();
}
5.2.14 Iteration Control Statement

Iteration (looping) is the repetition of same task until the condition is satisfied. Here, group of same
statements will execute until the given condition will true, once the condition became false then program
will be terminated. If the condition of loop is always true the program will execute infinite times, such loop
is called infinite loop. Basically there are three types of loop like while loop, do while loop and for loop.
Each loop has mainly three components,
Initialization - It is the starting point of loop Condition - It is the ending point of loop
Counter - Increment / Decrement (flow of program)

 While Loop
While loop also called entry-controlled loop where a condition is checked before processing a body of the
loop and if found true then only the body of a loop is executed and same process is executed until the
condition becomes false. Once the condition becomes false, the control goes out of the loop. If the condition
is not true, then the body of a loop will not be executed, not even once. False
Condition ?
Figure 5.19: while loop
True
body

incrementation
Syntax:
initialization; while(condition)
{
statement; counter;
}
Program 16:Display 3 6 12 to 5th term using while loop.
#include<stdio.h> #include<conio.h> void main()
{
int a=3,i=1; while(i<=5)
{
printf("%d \t",a);
a=a*2;
i++;
}
getch();
}
Program 17: program to reverse a given no. using while loop.
#include<stdio.h> #include<conio.h> void main()
{
int n,temp,s=0,rem;
printf("\n Enter any number: ");
scanf("%d",&n); temp=n; while(n>0)
{
rem=n%10; s=s*10+rem; n=n/10;
}
printf("Reverse of %d = %d",temp,s); getch();
}

 do, while loop


Body of the loop will execute at least once even if the condition is false such operation can be achieved by
using a do-while loop. In the do-while loop, condition will check after the execution of the body. If the
condition is true, then it will again execute the body of a loop otherwise control is transferred out
of the loop. Syntax: start

initialization; do
{
statement; counter; Condition
If condition TRUE If condition FALSE
}while(condition);

Figure 5.20: do, while loop

Program 18: Display square series of number using do while loop.


#include<stdio.h> #include<conio.h> void main()
{
int i=5; do
{

printf("%d \t",i*i); i--;


}while(i>=1);
getch();
}
Program 19: Fibonacci series 0 1 1 2 3 5 8 13 21 34 using do while loop.
#include<stdio.h> #include<conio.h> void main()
{
int i=1,b=1,c=0,d=0; do
{
printf("%d\t",c); d=b+c;
b=c; c=d; i++;
}while(i<=5);
getch();
}
while do-while
Statement(s) is executed at least
Condition is checked first then
once, thereafter condition is
statement(s) is executed.
checked.
It might occur statement(s) is executed At least once the statement(s) is
zero times, If condition is false. executed.
No semicolon at the end of while. Semicolon at the end of while.
while(condition) while(condition);
If there is a single statement, brackets are
Brackets are always required.
not required.
Variable in condition is initialized before Variable may be initialized before
the execution of loop. or within the loop.
do-while loop is exit controlled
while loop is entry controlled loop.
loop.
initialization; while(condition) initialization; do
{ {
statement(s); statement(s);
} }while(condition);

Table 5.15: Difference between while loop and do while loop


for loop
A for loop is a commonly used loop structure in 'C' programming which is also called entry controlled loop
and condition will check at the beginning of the program. Initial value of for loop is performed only once.
All three expressions are written in a single line separated with semi colon. It stops for loop when the
condition is false.
Syntax;
for Loop Body
for (initialization; condition; counter )
Figure 5.21: for loopExpression
update
{
statements;
}
Program 20: Multiplication table of a given number
#include<stdio.h> #include<conio.h> void main()
{
int i,a,b;
printf("Enter a number: "); scanf ("%d",&a); for(i=1;i<=10;i++)
{
b=a*i;
printf("%d x %d = %d \n",a,i,b);
}
getch();
}
Program 21: Calculate and display sum of no. from 1 to 10.
#include<stdio.h> #include<conio.h> void main()
{
int s=0,i; for(i=1;i<=10;i++)
{
s=s+i;
}
printf("\n sum of no. from 1 to 10 = %d ",s); getch();
}
Nested loop

Figure 5.22: Nested loop

Loop within a loop where inner loop is written within the body of an outer one is called nested loop. How
this works is that the first pass of the outer loop triggers the inner loop, which executes to completion. Loops
can also be nested where there is an outer loop and an inner loop. For the each iteration of the outer loop, the
inner loop repeats its entire cycle.
Syntax;
for (initialization; condition; counter)
{
for (initialization; condition; counter)
{
Statement of inner loop;
}
Statement of outer loop;
}
Program 22: Display following pattern.
1
12
123
1234
#include<stdio.h> #include<conio.h>
void main()
{
int i,j; for(i=1;i<=4;i++)
{
for(j=1;j<=i;j++)
{
printf("%d",j);
}
printf("\n");
}
getch();
}
Program 23: Multiplication table from 1 to 2. #include<stdio.h>
#include<conio.h> void main()
{
int i,j,s=0; for(i=1;i<=2;i++)
{
for(j=1;j<=10;j++)
{
s=i*j;
printf("%d * %d = %d\n",i,j,s);
}
printf("\n***************\n"); printf("\n");
}
getch();
}
5.2.15 Array

Data structure which store fixed-size sequential data elements of the same type. Array is a collection of
homogeneous (same) types of data. Instead of declaring individual variables, such as number_0, number_1,
..., and number_50, you declare one array variable named numbers and use numbers[0], numbers[1], and ...,
numbers[50] to represent individual variables. A specific element in an array is accessed by an index.
It is a collection of data items of the same type, accessed using a common name. All arrays consist of
contiguous memory locations. The lowest address corresponds to the first element and the highest address to
the last element.
Properties/characteristics of an Array
 It is a derived data type defined using basic data types like int, char, float
 Elements are stored in contiguous memory blocks in primary memory.
 Name represents its base address whose address is the address of the first element of the array.
 Index starts with 0 and ends with N-1. Here, N stands for the number of elements.
 Only constants and literal values (an integer value like 5, 10, 12,...) can be assigned the number of elements
in an array.
Advantages of Array
 It is easy to store the data of same data types with same size.
 It allows us to store known number of elements in it.
 It allocates memory in contiguous memory locations for its elements.
 Iterating the array using their index is faster compared to any other methods like linked list etc.
 It allows storing the elements in any dimensional array – supports multidimensional array.
Disadvantages of Array
 It allows us to enter only fixed number of elements into it.
 We cannot alter the size of the array once array is declared.
 Inserting and deleting the records from the array would be costly.
 It does not verify the indexes (subscript) while compiling the array.
 Run time errors occur rather than identifying them at compile time.
Types of Array
Arrays can have categorized into two types and are as follows:
 One dimensional (1-D) arrays
One dimensional array also called linear array used to store list of values of same data type. It is used to
store a row of values and data is stored in linear form. Subscript will determine the size of array and only
one subscript will present in one dimensional array.
Syntax:
data_type array_name [size of array];
Example:
int roll_num [60] ;
In the above example,it reserves 60 continuous memory locations of 2 bytes each with the name roll_num
and tells the compiler to allow only integer values.
We use the following general syntax for declaring and initializing a single/one dimensional array with
size and initial values.
Syntax:
datatype arrayName [ size ] = {value1, value2, ...} ; Example:
into marks [5] = { 89, 90, 76, 78, 86 } ;
The value inside the bracket is the size of array where as marks[0] is element and 0 is the starting point of
array.
marks[0] marks[1] marks[2] marks[3] marks[4]
89 90 76 78 86
index 0 index 1 index 2 index 3 index 4
Table 5.16: One dimensional (1-D) arrays

The value of array can be assigned as follows: marks[0] = 89;


marks[1] = 90;
marks[2] = 76;
marks[3] = 78;
marks[4] = 86;
Program 24: Enter array elements and display them.
#include<stdio.h> #include<conio.h> void main()
{
int a[5],i;
printf("\n Enter any five numbers for array:\n");
for(i=0;i<5;i++)
{
scanf("%d",&a[i]);
}
printf("\n You have entered following elements\n"); for(i=0;i<5;i++)
{
printf("%d\t",a[i]);
}
getch();
}
Program 25: Enter 5 integers and display their sum.
#include<stdio.h> #include<conio.h> void main()
{
int n[5],i,s=0;
printf("\n Enter any five no: ");
for(i=0;i<5;i++)
{
scanf("%d",&n[i]); s=s+n[i];
}
printf("\n Sum of five no. is: %d",s); getch();
}
Program 26: Enter n number and arrange them in ascending order.
#include<stdio.h> void main()
{
int i,j,a,n[10],t;
printf("enter How many elements.\nDo you want to enter: "); scanf("%d",&a);
for(i=0;i<a;i++)
{
printf("Element %d = ",i+1); scanf("%d",&n[i]);
}
t=n[0];
for(i=0;i<a-1;i++)
{
for(j=0+i;j<a;j++)
{
if(n[i]>n[j])
{
t=n[i]; n[i]=n[j]; n[j]=t;
}
}
}
printf("\n Elements in ascending order are; \n");
{
for(i=0;i<a;i++)
{
printf("%d \t",n[i]);
}
}
}
 Multi Dimensional Arrays
An array of arrays which has multiple subscripts is called as multi dimensional array which stores data and
elements in the form of rows and column. Total number of elements can be determined by the product of
rows and column. Multi dimensional array can be of two dimensional array or three dimensional array or
four dimensional array or more...
The 2-D most commonly used arrays used to store data in the form of table which is used to create
mathematical matrices.
Syntax:
data_type array_name[size of row][size of column]; Example:
int matrix[3][3];
int matrix[3][3]={150,200,100,67,95,65,55,275,75};
In this example, we created a 2D array of 3 by 3 (three rows and three columns). The array stores in memory
and looks like this table.
Matrix Column 0 Column 1 Column 2
Row 0 150 200 100

Row 1 67 95 65

Row 2 55 275 75
Table 5.17: Two Dimensional arrays

Which actually is as follows:


int matrix[3][3]={150,200,100,67,95,65,55,275,75};
int matrix[0][0]=150; int matrix[0][1]=200; int matrix[0][2]=100; int matrix[1][0]=67;
int matrix[1][1]=95; int matrix[1][2]=65; int matrix[2][0]=55; int matrix[2][1]=275; int matrix[2][2]=75;
Program 27: Enter2*2 matrix and display it.
#include<stdio.h> #include<conio.h> void main()
{
int n[2][2],i,j;
printf("\n Enter elements for 2 x 2 matrix: "); for(i=0;i<2;i++)
{
printf("\n Enter the elements of row %d .\n",i+1); for(j=0;j<2;j++)
{
scanf("%d",&n[i][j]);
}
}
printf(" Elements of 2 X 2 Matrix are:\n"); for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
printf("%d \t",n[i][j]);
}
printf("\n");
}
getch();
}
Program 28: Display the sum of two matrix.
#include<stdio.h> #include<conio.h> void main()
{
int i,j,p,q,m,n,a[5][5],b[5][5],s[10][10];
printf("\n Enter size of matrix A\n"); scanf("%d%d",&p,&q);
printf("\n Enter size of matrix B\n"); scanf("%d%d",&m,&n);
printf("\n Enter matrix A element\n"); for(i=0;i<p;i++)
{
for(j=0;j<q;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("\n Enter matrix B element\n"); for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf("%d",&b[i][j]);
}
}
printf("\nSum of matrix are: \n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
s[i][j]=a[i][j]+b[i][j];
printf("%d\t",s[i][j]);
}
printf("\n");
}
getch();
}
Program 29: Sum of two matrixes after checking possibilities of addition
#include<stdio.h> #include<conio.h> void main()
{
int i,j,p,q,m,n,a[5][5],b[5][5],s[10][10];
printf("\n Enter size of matrix A\n"); scanf("%d%d",&p,&q);
printf("\n Enter size of matrix B\n"); scanf("%d%d",&m,&n);
if(p==m && q==n)
{
printf("\n Enter matrix A element\n"); for(i=0;i<p;i++)
{
for(j=0;j<q;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("\n Enter matrix B element\n"); for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf("%d",&b[i][j]);
}
}
printf("\nSum of matrix are: \n"); for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
s[i][j]=a[i][j]+b[i][j];
printf("%d\t",s[i][j]);
}
printf("\n");
}
}
else
printf("\nAddition is not possible.\nSize of both matrix should be same."); getch();
}
Program 30: Display the difference of two matrixes.
#include<conio.h> void main()
{
int i,j,m,n,x[10][10],y[10][10],z[10][10];
printf("\n Enter the row and column size of matrix \n"); scanf("%d%d",&m,&n);
printf("\n Enter the elements of matrix A:\n"); for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf("%d",&x[i][j]);
}
}
printf("\n Enter the elements of matrix B:\n"); for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf("%d",&y[i][j]);
}
}
printf("\n");
printf("\nAfter subtraction matrix is:\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
z[i][j]=x[i][j]-y[i][j];
printf("%d\t ",z[i][j]);
}
printf("\n");
}
}
5.2.16 String

Strings are actually one-dimensional array or a sequence of characters, digits and symbol which
always terminated by a null character '\0'. Thus a null-terminated string contains the characters that comprise
the string followed by a null.
Syntax:
data_type string_name[size of string];
Example:
char str[15];
Here, char is the data_type which store 15 characters to the variable „str‟. String can be initialization as
follow:
char str[15]={„H‟,‟e‟,‟l‟,‟l‟,‟o‟,‟ „,‟W‟,‟o‟,‟r‟,‟l‟,‟d‟};
char str[15]=”Hello World”;
Each character is termed as element of the array named str and stored in the memory as follows;
„H‟ „e‟ „l‟ „l‟ „o‟ „„ „W‟ „o‟ „r‟ „l‟ „d‟ „\n‟
Table 5.18: Array of string

An array of strings is a 2-D array of characters. Just like we can create a 2-D array of int, float etc; we can
also create a 2-D array of character or array of strings. Here is how we can declare a 2-D array of characters.
Syntax:
char string_name[max][size];
Example:
char name[3][10];
char name[3][10]={“Madan”,”Rajkumar”,”Sita”};
In above initialization first subscript of the array 3 denotes the number of strings in the array and the second
subscript 10 denotes the maximum length of the string. It will allocate 30 bytes (3*10) of memory because
each character occupies 1 byte of data.
Program 31: To demonstrate array of string.
#include<stdio.h> void main()
{
int i;
char name[3][10]={“Nikef”,”Kritika”,”Meena”}; for(i=0;i<=3;i++)
{
printf(“%s\t”,name[i]);
}
}
String Manipulation Function
String handling library provides useful functions which can be used for string manipulations. All these string
handling functions are defined in the header file „string.h‟. So every time we use this string handling
functions „string.h‟ header file must be included. Some of the major string handling functions used is
mentioned below:
strlen() function
This function is used to find the length of any string. Syntax:
l=strlen(str);
In above example „str‟ is a string whose length will store to the integer variable „l’
Program 32: To find the length of string.
#include<stdio.h> #include<conio.h> #include<string.h> void main()
{
int l;
char str[20];
printf("Enter any string: "); scanf(“%s”,str); l=strlen(str);
printf("\n Length of %s is: %d",str,l); getch();
}
strrev() function
This function is used to reverse the given string. Syntax:
strrev(str);
Program 33: To reverse the given of string.
#include<stdio.h> #include<conio.h> #include<string.h> void main()
{
char str[20];
printf("Enter any string: "); scanf("%s",str);
printf("The reverse is %s: ",strrev(str)); getch();
}
strlwr() function
This function is used to convert all character of a string to lower case. Syntax:
strlwr(str);
Program 34: To convert the given of string into lower case.
#include<stdio.h> #include<conio.h> #include<string.h> void main()
{
char str[20];
printf("Enter string in upper Case: "); gets(str);
printf("\nThe string in Lowercase is: %s",strlwr(str)); getch();
}
strupr() function
This function is used to convert all character of a string to upper case. Syntax:
strupr(str);
Program 35: To convert the given of string into upper case.
#include<stdio.h> #include<conio.h> #include<string.h> void main()
{
char str[20];
printf("Enter string in lower Case: "); gets(str);
printf("\nThe string in Uppercase is: %s",strupr(str)); getch();
}
strcat() function
This function is used to join (concatenate) two strings into one. Syntax:
strcat(str1,st2);
Program 36: To combine two given strings.
#include<stdio.h> #include<conio.h> #include<string.h> void main()
{
char str1[20],str2[20];
printf("\n Enter first string: "); gets(str1);
printf("\n Enter second string: "); gets(str2);
printf("\n The combined string is: %s",strcat(str1,str2)); getch();
}
strcpy() function
This function is used to copy one string to another string. Syntax:
strcpy(str2,str1);
Here, the value of string „str1‟ will store to the string „str2‟. Program 37: To copy one string to another
string. #include <stdio.h>
#include<string.h> void main()
{
Computer Science 317

char str1[20],str2[20]; printf("Enter First string: "); gets(str1);


printf("Enter Second string: "); gets(str2);
printf("\nAfter copying.. Second string becomes %s",strcpy(str2,str1));
}
strcmp() function
This function is used to compare the length between two strings and store the value to integer variable.
Syntax:
l=strcmp(str1,st2);
Here, the value of „l‟ should be zero, positive or negative. Program 38: To compare the length of two
strings. #include<stdio.h>
#include<string.h> void main()
{
int l;
char str1[20],str2[20]; printf("\n Enter first
string: ");
gets(str1);
printf("\n Enter second string: "); gets(str2);
l=strcmp(str1,str2); if(l==0)
printf("\n Both String are same”); else if(l>0)
printf("\n %s Comes after %s”,str1,str2);
else
printf("\n %s Comes before %s”,str1,str2);
}

Approved by Curriculum Development Centre


Computer Science 318
Points to Remember

 Programming Language
A programming language is a platform which translates human language into machine language and vice
versa using different programs like C, C++, C#, Java, python, etc.
 High Level Language
Computer programs are written in programming languages nearly human languages and are called high level
languages which are groups of programming languages that introduced significant enhancements to second
generation languages
 Runtime Error
Runtime error refers to an error that takes place while executing a program and occurs only during the
execution of the program. It is quite common that the computer becomes noticeably slow prior to the
appearance of a runtime error.
 Control Structure
Control Structures are just a way to analyzes and chooses the flow of programs in which direction a program
flows based on certain parameters or conditions.
 Unicode
Unicode is a universal character encoding standardwas designed to support characters from all languages
around the world which supports up to 4 bytes for each character which can support roughly 1,000,000
characters.
 Preprocessor
Preprocessor commands begin with a hash symbol (#). It must be the first nonblank character, and for
readability, a preprocessor directive should begin in the first column of a program.
 Header Files
Header files are those file having extension “.h” which holds the definitions of various functions and their
associated variables that needs to be imported into your program with the help of pre-processor #include
statement.

Approved by Curriculum Development Centre


 Tokens
Tokens are the smallest elements of a program, which are meaningful to the compiler like Keywords,
Identifiers, Constant, Strings and Operators etc.
 Compound Statement Computer Science 319
Compound statements are those statements which have other statements inside them. All statements are
enclosed by pair of curly braces {}, which have relation with each other.
 Operators
An operator is a symbol which tells the compiler to perform a certain mathematical or logical manipulation
of data and variables.
 Array
Array is a collection of data items of the same type, accessed using a common name. All arrays consist of
contiguous memory locations. The lowest address corresponds to the first element and the highest address to
the last element.
Exercise 5
Multiple Choice Questions

1. The step by step procedure for solving a problem…


a. programming b. algorithm
c. planning d. flowchart
2. Finding and solving errors in the source code is…
a. desk checking b. debugging
c. decoding d. testing
3. ……language is not an object oriented programming language…
a. visual basic b. C
c. c++ d. java
4. Communication between user and the computer is…
a. programming language b. software
c. syntax d. english language
5. Who invented C Language.?
a. Charles Babbage b. Grahambel
c. Dennis Ritchie d. Steve Jobs

Approved by Curriculum Development Centre


6. C Language is a successor to which language.?
a. FORTRAN b. D Language
c. BASIC d. B Language
7. C is type of programming language.?
a. Object Oriented b. Procedural Computer Science 320

c. Bit level language d. Functional


8. What is the output of this statement "printf("%d", (a++))"?
a. The value of (a + 1) b. The current value of a
c. Error message d. Garbage
9. Which one of the following is a loop construct that will always be executed once?
a. for b. while
c. switch d. do while
10. How many characters can a string hold when declared as follows? char name[20]:
a. 1 8 b. 19
c. 20 d. None of these
11. The #include <stdio.h> is a .
a. Inclusion directive b. File inclusion directive
c. Preprocessor directive d. None of the above
12. Does C language support object-oriented approach?
a. Yes b. No
13. Which are the fundamental data types in C?
a. char b. int
c. float d. All of the above
14. What is the name of "&" operator in C?
a. Ampersand b. And
c. Address of d. None of the above
15. When the condition of if statement is false, the flow of code will .
a. go into the if block
b. Exit the program
c. Continue the code after skipping the if block
d. None of these

Approved by Curriculum Development Centre


Answer Key

1. (b) 2. (b) 3. (b) 4. (a) 5. (c)


6. (d) 7. (b) 8. (b) 9. (d) 10. (c)
11. (c) 12. (b) 13. (d) 14. (c) 15. (c)
Computer Science 321
Short Answer Questions:
1. What is programming language? List some programming languages.
2. Differentiate between flowchart and algorithms.
3. Explain the difference between syntax and semantics.
4. Differentiate between local and global variables.
5. Explain any two string handling functions with example.
Long Answer Questions:
1. What are the program design tools? Describe different types of program design tools with merits and
demerits.
2. Briefly explain the term Assembler, Compiler and Interpreter.
3. Explain different types of programming errors in programming languages.
4. What are the different control structures available for program design? Briefly explain with example and
flowchart.
5. Draw a flowchart to test condition „if-then-else‟ in program design process.
6. Draw a flowchart to show „Do-While‟ loop.
7. Differentiate between logical error and syntax error with examples.
8. What is program testing and debugging?
9. Write short note on Pseudo code.
10. What are header files? Explain the structure of C program.
11. Define the terms Identifiers, keywords and tokens.
12. Explain any four basic input output functions.
13. Differentiate between if-else and if-else-if control statement.
14. Differentiate between while loop and do-while loop.
15. Explain array in C programming with an example.
16. Define String? Explain different String Handling functions with example.

Approved by Curriculum Development Centre


Assignment 5
1. Differentiate between program flowchart and system flowchart with the help of proper symbol and diagram.
2. WAP to input three number and print sum and average using C program.
3. WAP to calculate and print Simple Interest (SI) and net amount (A)
Computer Science 322
4. WAP to calculate sum of two distances and the distance should be measured in feet and inch.
5. WAP to convert temperature from Centigrade (C) to Fahrenheit (F).
6. WAP to enter days and convert it to Days, Months and days.
7. WAP to check if the given number it even
8. WAP to check if the given number is Positive or Negative.
9. WAP to display smallest among five positive numbers.
10. WAP to calculate area of circle, area of square and are of sphere using switch case.
11. WAP to display and calculate sum of all natural numbers up to “N”.
12. WAP to display multiplication table of any given number.
13. WAP to check if the given number is prime or not?
14. WAP to transpose given matrix.
15. WAP to enter age of 50 students and display the number of students having age in between 18 to 23.
16. WAP to check if the given string is palindrome or not?
17. Write a program to sort the name of „n‟ numbers of students in alphabetical order using C program.
18. Define an array? Write a program to find largest and smallest number among „n‟ numbers in an array.


Approved by Curriculum Development Centre

You might also like