Understanding Programming Languages
Understanding Programming Languages
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.
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:
Disadvantage:
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.
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.
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:
Disadvantage:
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:
Disadvantage:
Advantage:
Disadvantage:
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.
2. Compiler:
These language processors help to convert program written in high level language (source program)
into machine level program (object program).
It is the largest method of translating a program in which debugging is complex and time consuming.
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.
Most of the new programming language use interpreter which allocate less memory space.
Programs like BASIC, C#, Php, etc. use interpreter for conversion.
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.
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:
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
Terminal Decision
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.
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.
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:
#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.
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,
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
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.
Logical Operators
Logical operators are commonly used in decision making which returns either 0 or 1 depending upon
expression‟s results true or false.
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:
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();
}
initialization; do
{
statement; counter; Condition
If condition TRUE If condition FALSE
}while(condition);
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
Row 1 67 95 65
Row 2 55 275 75
Table 5.17: Two Dimensional arrays
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
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.