Introduction To Computer Programming
Introduction To Computer Programming
Introduction To Computer Programming
COURSE DESCRIPTION
Learning Outcomes
Upon successful completion of this course, the student should be able to:
i) Discuss the concepts and principles of procedural programming language
ii) Apply basic problem solving techniques
iii) Analyze problems and implement basic algorithms for their solution.
iv) Demonstrate the ability in testing and debugging programs
Course Description
Computer Programming Overview: Computer, Computer Program, Computer Programming,
Computer Programmer Programming paradigms, Program development cycle. Computer
Programming basics: Programming Environment: Text Editor, Compiler, Interpreter; Computer
Programming basic syntax: Program entry point, functions, comments, whitespaces, semicolons,
program explanation, expression; Data types: C and Python data types; Variables and variable
scope: Local and global, Initializing local and global variables, constant/literal variables,
variables in C and Python; Operators in C and Python: Arithmetic, Comparison/Relational,
Logical Operators; Reserved/Keywords in C and Python. Control Structures in C and Python:
Decision making, Looping Control structures; Numbers and Characters in C and Python; Arrays:
Creating, initializing, accessing array in C, Collections in Python: Lists, Tuples, Sets,
Dictionaries) in python. Data Structures: Defining a Structure, Accessing Structure Members
Strings: Basic string concepts, strings in C and Python; Functions in C and Python: Introduction
to modules and modularity, defining and calling functions, Function Arguments, Call by
Value ,Call by Pointer , Call by Reference, functions in Python. File I/O: Computer files, file
input/output, file operation modes, opening, closing, reading and writing a file, file I/O in
1
python. Algorithm: flow charts, pseudo code. Problem solving strategies: top-down and bottom-
up decomposition. Good programming practices: style and conventions. Libraries, testing and
debugging programs. Use languages such as C, Python etc.
Teaching Methodologies
Lectures, practical and tutorial sessions in Computer Laboratory, individual and group
assignments, exercises and project work
Course Assessment
30% Continuous Assessment (Tests 10%, Assignment 10%, Practical 10%)
70% End of Semester Examination.
Course Textbooks
1. Kernighan, B. W (2003). The Practice of Programming Addison-Wesley, ISBN 459- 0677005
2. Xavier C (2008). Introduction to Computers and Basic programming. New Age International
Publishers, ISBN 978-81-224-2123-1
3. Harold Abelson, Gerald Jay Sussman, Julie Sussman (1996). Structure and Interpretation of
Computer Programs (MIT Electrical Engineering and Computer Science) ISBN 978- 567954
Reference Textbooks
1. H.M. Deitel and P.J. Deitel (1994). C: How to Program, 2nd Edition. Prentice Hall, ISBN 341-
7600455
2. Bjarne Stroustrup (2008). Programming: Principles and Practice Using C++ Prentice Hall
ISBN 341-6780027
3. B.Kernighan's .D.M. Ritchie's (1988). C Programming Language, 2nd Edition, ISBN 345-
895840
Course Journals
1. Acta Informatica ISSN 0001-5903
2. Advances in Computational Mathematics ISSN 1019-7168
3. Advances in data Analysis and Classification ISSN1 1862-5347
4. Annals Of software Engineering ISSN 1022-7091
Reference Journals
1. Journal of computer science and Technology ISSN 1000-9000
2. Journal of Science and Technology ISSN 1860-4749
3. Central European Journal Of Computer Science ISSN 1896-1533
4. Cluster computing ISSN 1386-7857
2
COURSE OUTLINE
NO Topic
1 Overview
o General Introduction
o History of programming.
o An overview of programming languages.
Fortran, Algol, Cobol, lisp, Basic, CPL, B, BCPL, C,
C++,
Simula and JAVA
Query Languages
Report Generators
Application generators
Language translators
Assemblers
Compilers
Interpreters
Introduction to programming concepts
o Program
o Programming
o Programmer
Good programming practices: Styles and Conventions.
Program Development cycle
Characteristics of programming languages
o Generality, expressivity, portability
Integrated Development Environment (IDE)
2 Programming errors and Debugging
5
1.3 Uses of Computer Programs...........................................................................................13
1.4 Computer Programmer....................................................................................................13
1.5 Algorithm........................................................................................................................14
2 Computer Programming - Basics...........................................................................................24
3 Computer Programming - Environment.................................................................................26
3.1 Text Editor......................................................................................................................27
3.2 Compiler?........................................................................................................................28
3.3 Interpreter........................................................................................................................29
3.4 Online Compilation.........................................................................................................30
4 Computer Programming - Basic Syntax.................................................................................30
4.1 Hello World Program in C..............................................................................................31
4.1.1 Program Entry Point....................................................................................................31
4.1.2 Functions.....................................................................................................................32
4.1.3 Comments....................................................................................................................32
4.1.4 Whitespaces.................................................................................................................32
4.1.5 Semicolons..................................................................................................................33
4.1.6 Program Explanation...................................................................................................34
4.2 Syntax Error....................................................................................................................35
4.3 Hello World Program in Java..........................................................................................35
4.4 Hello World Program in Python.....................................................................................36
5 Computer Programming - Data Types...................................................................................36
5.1 C and Java Data Types....................................................................................................37
5.2 Python Data Types..........................................................................................................38
6 Computer Programming - Variables......................................................................................39
6.1 Creating variables...........................................................................................................39
6.2 Store Values in Variables................................................................................................40
6.3 Access stored values in variables....................................................................................41
6
6.4 Variables in Java.............................................................................................................42
6.5 Variables in Python.........................................................................................................43
7 Computer Programming - Keywords.....................................................................................45
7.1 C Programming Reserved Keywords..............................................................................46
7.2 Java Programming Reserved Keywords.........................................................................47
7.3 Python Programming Reserved Keywords.....................................................................47
8 Computer Programming - Operators......................................................................................48
8.1 Arithmetic Operators.......................................................................................................49
8.2 Relational Operators.......................................................................................................51
8.3 Logical Operators............................................................................................................53
8.4 Operators in Java.............................................................................................................55
8.5 Operators in Python........................................................................................................56
9 Decision Statements...............................................................................................................57
9.1 if...else statement.............................................................................................................61
9.2 if...elseif...else statement.................................................................................................64
9.3 The Switch Statement.....................................................................................................65
9.4 Decisions in Java.............................................................................................................67
9.5 Decisions in Python........................................................................................................68
10 Computer Programming - Loops............................................................................................68
10.1 The while Loop...............................................................................................................71
10.2 The do...while Loop........................................................................................................73
10.3 The break statement........................................................................................................74
10.4 The continue statement...................................................................................................75
10.5 Loops in Java..................................................................................................................77
10.6 Loops in Python..............................................................................................................77
11 Computer Programming - Numbers.......................................................................................78
11.1 Math Operations on Numbers.........................................................................................79
7
11.2 Numbers in Java..............................................................................................................82
11.3 Numbers in Python..........................................................................................................83
12 Computer Programming - Characters.....................................................................................84
12.1 Escape Sequences...........................................................................................................85
12.2 Characters in Java...........................................................................................................87
12.3 Characters in Python.......................................................................................................88
13 Computer Programming - Arrays...........................................................................................88
13.1 Create Arrays..................................................................................................................90
13.2 Initializing Arrays...........................................................................................................90
13.3 Accessing Array Elements..............................................................................................91
13.4 Arrays in Java..................................................................................................................92
13.5 Arrays (Lists) in Python..................................................................................................93
14 Computer Programming - Strings..........................................................................................93
14.1 Basic String Concepts.....................................................................................................96
14.2 Strings in Java.................................................................................................................97
14.3 Strings in Python.............................................................................................................97
15 Computer Programming - Functions......................................................................................98
15.1 Defining a Function......................................................................................................100
15.2 Calling a Function.........................................................................................................100
15.3 Functions in Java...........................................................................................................101
15.4 Functions in Python......................................................................................................102
Computer Programming - File I/O..............................................................................................103
15.5 Computer Files..............................................................................................................103
15.6 File Input/Output...........................................................................................................104
15.7 File Operation Modes....................................................................................................104
15.8 Opening Files................................................................................................................105
15.9 Closing a File................................................................................................................106
8
15.10 Writing a File.............................................................................................................106
15.11 Reading a File............................................................................................................107
15.12 File I/O in Java..........................................................................................................108
15.13 File I/O in Python......................................................................................................109
16 Computer Programming - Summary....................................................................................113
Computer programming is the act of writing computer programs, which are a sequence of
instructions written using a Computer Programming Language to perform a specified task by
the computer.
Computer Programming is fun and easy to learn provided you adopt a proper approach. This
tutorial attempts to cover the basics of computer programming using a simple and practical
approach for the benefit of novice learners.
Audience
This tutorial has been prepared for the beginners who are willing to learn computer
programming but they are unable to learn it due to lack of proper guidance. We are confident
that after completing this tutorial, you will be at a level where you can code in C Programming
language and will have a basic understanding of Java and Python programming languages as
well from where you can continue further.
If you are completely new to Computer Programming, then we recommend you to read this
tutorial twice or even thrice. First reading will not give you much idea, but during your second
reading, you will start grasping most of the concepts and you will enjoy writing computer
programs.
Prerequisites
We do not expect much from you as prerequisites; however, we assume that you have some
amount of exposure to computers and its peripherals like keyboard, mouse, screen, printer, etc.
1 Basic Concepts of Programming
Program
Programming languages
Programmer
Software
Computer vs Human beings
Definitions:
9
PROGRAM: Is a set of step by step instructions written in a language that the computer can
interpret and understand. They are used to guide a computer to perform a task (simple or
complex).
Programming Problem: - A task that requires a program to be written.
Programming language: - This is a program with a special role i.e. it enables us to come up
with other programs. Has instructions that enable us to write programs or modify an existing
program. C, C++, JAVA, PHP, JSP, C#, JAVASCRIPT ETC
They have features of language
Grammar : SYNTAX
Vocabulary
Interpretation/ meaning: SEMANTICS
Programming: - This is the art of formulating a set of instructions to enable the computer to
perform certain tasks.
Software: - A program that has been debugged, tested, documented and ready to be used.
1. Computer Programming - Overview
To understand these terms, consider a situation when someone asks you about how to go to a
nearby KFC. What exactly do you do to tell him the way to go to KFC?
You will use Human Language to tell the way to go to KFC, something as follows −
First go straight, after half kilometer, take left from the red light and then drive around one
kilometer and you will find KFC at the right.
Here, you have used English Language to give several steps to be taken to reach KFC. If they
are followed in the following sequence, then you will reach KFC −
1. Go straight
2. Drive half kilometer
3. Take left
4. Drive around one kilometer
5. Search for KFC at your right side
10
Now, try to map the situation with a computer program. The above sequence of instructions is
actually a Human Program written in English Language, which instructs on how to reach
KFC from a given starting point. This same sequence could have been given in Spanish, Hindi,
Arabic, or any other human language, provided the person seeking direction knows any of these
languages.
Now, let's go back and try to understand a computer program, which is a sequence of
instructions written in a Computer Language to perform a specified task by the computer.
Following is a simple program written in Python programming Language −
print "Hello, World!"
The above computer program instructs the computer to print "Hello, World!" on the computer
screen.
A computer program is also called a computer software, which can range from two
lines to millions of lines of instructions.
Computer program instructions are also called program source code and computer
programming is also called program coding.
A computer without a computer program is just a dump box; it is programs that make
computers active.
As we have developed so many languages to communicate among ourselves, computer
scientists have developed several computer-programming languages to provide instructions to
the computer (i.e., to write computer programs). We will see several computer programming
languages in the subsequent chapters.
11
1.3 Uses of Computer Programs
Today computer programs are being used in almost every field, household, agriculture, medical,
entertainment, defense, communication, etc. Listed below are a few applications of computer
programs −
MS Word, MS Excel, Adobe Photoshop, Internet Explorer, Chrome, etc., are examples
of computer programs.
Computer programs are being used to develop graphics and special effects in movie
making.
Computer programs are being used to perform Ultrasounds, X-Rays, and other medical
examinations.
Computer programs are being used in our mobile phones for SMS, Chat, and voice
communication.
1.5 Algorithm
From programming point of view, an algorithm is a step-by-step procedure to resolve any
problem. An algorithm is an effective method expressed as a finite set of well-defined
instructions.
Thus, a computer programmer lists down all the steps required to resolve a problem before
writing the actual code. Following is a simple example of an algorithm to find out the largest
number from a given list of numbers −
1. Get a list of numbers L1, L2, L3....LN
2. Assume L1 is the largest, Largest = L1
3. Take next number Li from the list and do the following
12
4. If Largest is less than Li
5. Largest = Li
6. If Li is last number from the list then
7. Print value stored in Largest and come out
8. Else repeat same process starting from step 3
The above algorithm has been written in a crude way to help beginners understand the concept.
You will come across more standardized ways of writing computer algorithms as you move on
to advanced levels of computer programming.
PROGRAM/SOFTWARE LIFE CYCLE (STAGES OF PROGRAM DEVELOPMENT)
The process of developing a program generally involves six stages which are referred to as the
program development life cycle and shown below:
1. Requirements specification: States the purpose/function of the program. Understand the
problem or task: A program to compute the area of a rectangle. It involves the definition of
inputs, transformation, outputs and treatment of exceptional situations.
2. Program design: This is where the programmer identifies the processing tasks required and
the precise order in which they are to be carried out, that is the algorithm from which the
computer program will be produced. The design process takes little or no account of the
programming language to be used.
3. Coding the program: Involves converting the design specification (the algorithm) into
actual computer instructions in the computer language to be used. If sufficient care has been
taken at the design stage, coding is an almost mechanical process for an experienced
programmer since most of the hard work of analyzing the problem and breaking it into a
sequence of small, simple steps has already been done during the design stage.
4. Testing and Debugging: Debugging is the detection and correction of errors that may exist
in the program. The only way of completely confident that a program will behave as
expected, under all circumstances that conceivably arise, is to test the program thoroughly
before implementing it. Program testing includes creating test data designed to produce
predictable output.
5. Documentation: Having written and debugged the program. It must be documented. There
are two main types of documentation.
a) User Guide: These are guides that are intended to help the user to use/operate the
program with minimal or no guidance
b) Technical manuals: These are intended for the system analysts/programmers to enable
maintenance and modification of the program design and code.
6. Implementation/Operation: At this stage, the system designers will actually install the new
system, create data files and train people to use the new system. A common practice is to run
the new system in parallel with the old system to ensure that if something goes wrong, the
business doesn't come to a grinding halt. After a number of parallel runs, the old system will
be abandoned and the new system will be fully be operational. At this point the system goes
13
into the final stage off monitoring and review (or evaluation) where the performance of the
system is evaluated with reference to the initial requirements.
7. Maintenance and Evaluation:
a) Use Meaningful names: When coming up with the names for variables or constants,
use names that hint what the variable or constant holds e.g. balance, tax, tax_rate, etc.
instead of using letters like a,b,c.
b) Use Comments: Use comments at the module level to explain the purpose of the
module and within the code to explain complicated algorithms or highlight error prone
sections.
/* rhrhhhrjr ffjfjf
ddldldl fflflflf
kdlll fl;g;g;g;g */
c) Use Indentation: Lay your code neatly and make proper use of indentation to reflect
the logic structure of the code.
#include<stdio.h>
14
main()
{
float length,width,area;
length=42.345;
width=31.344;
area=length*width;
printf("The area = %f\n",area);
}
#include<stdio.h>
main()
{
float length,width,area;
length=42.345;
width=31.344;
area=length*width;
printf("The area = %f\n",area);
}
6. SIMPLICITY: The clarity and accuracy of a program are usually enhanced by keeping
things simple.
7. EFFICIENCY: Efficiency is concerned with execution speed and efficient memory
utilization.
8. GENERALITY: Generality. A program should be as general as possible, within reasonable
limits. We may design a program to read in the values of certain key parameters rather that
placing fixed values into the program.
15
Good programming practice
1. Apply the computer problem solving steps:
#include<stdio.h>
#include<math.h>
main()
{
float number;
float answer;//This is the declaration of variables
Causes
a) Missing semicolon to terminate a statement
b) Misspelled reserved word
c) A reserved word consisting of a capital letter.
d) { without corresponding } or ( without corresponding )
e) " without corresponding "
f) Use of wrong expressions float x; area=l*w; Error: l*w=area;
g) Use of undeclared identifiers
h) Failure to include the appropriate header file.
float x,y,z;
a=23;
Causes
a) Division by zero
b) Computing the square root of a negative number
c) Endless loops
Causes
a) Wrong formula
b) Failure to initialize variables
c) Testing wrong conditions in loops
17
4. LINKING ERROR: The computer is not able to get the intermediate programs required by
the program.
#include<stdio.h>
main()
{
18
float num1,num2,sum;
sum=num1+num2;
printf("%f\n",sum);
printf("The answer = %f\n",sum);
printf("The sum of %f and %f is %f\n",num1,num2,result);
printf("%f is the sum of %f and %f\n",result,num1,num2);
ggggggggg */
19
2) Line spacing: Leaving empty lines between sections of codes so as to visibly distinguish
among the individual sections.
3) Indenting code
4) Use of meaningful identifiers
#include<iostream>
#include<math.h>
using namespace std;
main()
{
float number,result;
cout<<"Enter the number: ";
cin>>number;
result=sqrt(number);
cout<<"The number = "<<number<<endl;
cout<<"The result = "<<result<<endl;
}
We assume you are well aware of English Language, which is a well-known Human Interface
Language. English has a predefined grammar, which needs to be followed to write English
statements in a correct way. Likewise, most of the Human Interface Languages (Hindi, English,
Spanish, French, etc.) are made of several elements like verbs, nouns, adjectives, adverbs,
propositions, and conjunctions, etc.
Similar to Human Interface Languages, Computer Programming Languages are also made of
several elements. We will take you through the basics of those elements and make you
comfortable to use them in various programming languages. These basic elements include −
Programming Environment
Basic Syntax
Data Types
Variables
Keywords
20
Basic Operators
Decision Making
Loops
Numbers
Characters
Arrays
Strings
Functions
File I/O
We will explain all these elements in subsequent chapters with examples using different
programming languages. First, we will try to understand the meaning of all these terms in
general and then, we will see how these terms can be used in different programming languages.
This tutorial has been designed to give you an idea about the following most popular
programming languages −
C Programming
Java Programming
Python Programming
A major part of the tutorial has been explained by taking C as programming language and then
we have shown how similar concepts work in Java and Python. So after completion of this
tutorial, you will be quite familiar with these popular programming languages.
21
3 Computer Programming - Environment
Though Environment Setup is not an element of any Programming Language, it is the first step
to be followed before setting on to write a program.
When we say Environment Setup, it simply implies a base on top of which we can do our
programming. Thus, we need to have the required software setup, i.e., installation on our PC
which will be used to write computer programs, compile, and execute them. For example, if you
need to browse Internet, then you need the following setup on your machine −
A working Internet connection to connect to the Internet
A Web browser such as Internet Explorer, Chrome, Safari, etc.
If you are a PC user, then you will recognize the following screenshot, which we have taken
from the Internet Explorer while browsing tutorialspoint.com.
22
Similarly, you will need the following setup to start with programming using any programming
language.
A text editor to create computer programs.
A compiler to compile the programs into binary format.
An interpreter to execute the programs directly.
In case you don’t have sufficient exposure to computers, you will not be able to set up either of
these software. So, we suggest you take the help from any technical person around you to set up
the programming environment on your machine from where you can start. But for you, it is
important to understand what these items are.
23
You can use this software to type your computer program and save it in a file at any location.
You can download and install other good editors like Notepad++, which is freely available.
If you are a Mac user, then you will have TextEdit or you can install some other commercial
editor like BBEdit to start with.
3.2 Compiler
You write your computer program using your favorite programming language and save it in a
text file called the program file.
Now let us try to get a little more detail on how the computer understands a program written by
you using a programming language. Actually, the computer cannot understand your program
directly given in the text format, so we need to convert this program in a binary format, which
can be understood by the computer.
The conversion from text program to binary file is done by another software called Compiler
and this process of conversion from text formatted program to binary format file is called
program compilation. Finally, you can execute binary file to perform the programmed task.
We are not going into the details of a compiler and the different phases of compilation.
The following flow diagram gives an illustration of the process −
24
So, if you are going to write your program in any such language, which needs compilation like
C, C++, Java and Pascal, etc., then you will need to install their compilers before you start
programming.
3.3 Interpreter
We just discussed about compilers and the compilation process. Compilers are required in case
you are going to write your program in a programming language that needs to be compiled into
binary format before its execution.
There are other programming languages such as Python, PHP, and Perl, which do not need any
compilation into binary format, rather an interpreter can be used to read such programs line by
line and execute them directly without any further conversion.
25
So, if you are going to write your programs in PHP, Python, Perl, Ruby, etc., then you will need
to install their interpreters before you start programming.
Let’s start with a little coding, which will really make you a computer programmer. We are
going to write a single-line computer program to write Hello, World! on your screen. Let’s see
how it can be written using different programming languages.
26
4.1 Hello World Program in C
Try the following example using our online compiler option available
at www.compileonline.com.
For most of the examples given in this tutorial, you will find a Try it option in our website code
sections at the top right corner that will take you to the online compiler.
Try to change the content inside printf(), i.e., type anything in place of Hello World! and then
check its result. It just prints whatever you keep inside the two double quotes.
int main()
{
/* printf() function to write Hello, World! */
printf( "Hello, World!" );
}
which produces the following result −
Hello, World!
This little Hello World program will help us understand various basic concepts related to C
Programming.
4.1.2 Functions
Functions are small units of programs and they are used to carry out a specific task. For
example, the above program makes use of two functions: main() and printf(). Here, the
function main() provides the entry point for the program execution and the other function
printf() is being used to print an information on the computer screen.
You can write your own functions which we will see in a separate chapter, but C programming
itself provides various built-in functions like main(), printf(), etc., which we can use in our
programs based on our requirement.
27
Some of the programming languages use the word sub-routine instead of function, but their
functionality is more or less the same.
4.1.3 Comments
A C program can have statements enclosed inside// /*.....*/. Such statements are called
comments and these comments are used to make the programs user friendly and easy to
understand. The good thing about comments is that they are completely ignored by compilers
and interpreters. So you can use whatever language you want to write your comments.
4.1.4 Whitespaces
When we write a program using any programming language, we use various printable
characters to prepare programming statements. These printable characters are a, b, c,......z, A, B,
C,.....Z, 1, 2, 3,...... 0, !, @, #, $, %, ^, &, *, (, ), -, _, +, =, \, |, {, }, [, ], :, ;, <, >, ?, /, \, ~. `. ", '.
Hope I'm not missing any printable characters from your keyboard.
Apart from these characters, there are some characters which we use very frequently but they
are invisible in your program and these characters are spaces, tabs (\t), new lines(\n). These
characters are called whitespaces.
These three important whitespace characters are common in all the programming languages and
they remain invisible in your text document −
A line containing only whitespace, possibly with a comment, is known as a blank line, and a C
compiler totally ignores it. Whitespace is the term used in C to describe blanks, tabs, newline
characters, and comments. So you can write printf("Hello, World!" ); as shown below. Here
all the created spaces around "Hello, World!" are useless and the compiler will ignore them at
the time of compilation.
#include <stdio.h>
int main() {
}
28
which produces the following result −
Hello, World!
If we make all these whitespace characters visible, then the above program will look like this
and you will not be able to compile it −
#include <stdio.h>\n
\n
int main()\n
{
\n
\t/* printf() function to write Hello, World! */
\n
\tprintf(\t"Hello, World!"\t);\n
\n
}\n
4.1.5 Semicolons
Every individual statement in a C Program must be ended with a semicolon (;), for example, if
you want to write "Hello, World!" twice, then it will be written as follows −
#include <stdio.h>
int main() {
/* printf() function to write Hello, World! */
printf( "Hello, World!\n" );
printf( "Hello, World!" );
}
This program will produce the following result −
Hello, World!
Hello, World!
Here, we are using a new line character \n in the first printf() function to create a new line. Let
us see what happens if we do not use this new line character −
#include <stdio.h>
int main() {
/* printf() function to write Hello, World! */
printf( "Hello, World!" );
printf( "Hello, World!" );
}
This program will produce the following result −
Hello, World! Hello, World!
29
We will learn identifiers and keywords in next few chapters.
main() {
printf("Hello, World!")
}
This program will produce the following result −
main.c: In function 'main':
main.c:7:1: error: expected ';' before '}' token
}
^
So the bottom-line is that if you are not following proper syntax defined by the programming
language in your program, then you will get syntax errors. Before attempting another
compilation, you will need to fix them and then proceed.
30
4.3 Hello World Program in Java
Following is the equivalent program written in Java. This program will also produce the same
result Hello, World!.
public class HelloWorld {
public static void main(String []args) {
/* println() function to write Hello, World! */
System.out.println("Hello, World!");
}
}
which produces the following result −
Hello, World!
Let's discuss about a very simple but very important concept available in almost all the
programming languages which is called data types. As its name indicates, a data type
represents a type of the data which you can process using your computer program. It can be
numeric, alphanumeric, decimal, etc.
Let’s keep Computer Programming aside for a while and take an easy example of adding two
whole numbers 10 & 20, which can be done simply as follows −
10 + 20
Let's take another problem where we want to add two decimal numbers 10.50 & 20.50, which
will be written as follows −
10.50 + 20.50
31
The two examples are straightforward. Now let's take another example where we want to record
student information in a notebook. Here we would like to record the following information −
Name:
Class:
Section:
Age:
Sex:
Now, let's put one student record as per the given requirement −
Name: Zara Ali
Class: 6th
Section: J
Age: 13
Sex: F
The first example dealt with whole numbers, the second example added two decimal numbers,
whereas the third example is dealing with a mix of different data. Let's put it as follows −
Student name "Zara Ali" is a sequence of characters which is also called a string.
Student class "6th" has been represented by a mix of whole number and a string of two
characters. Such a mix is called alphanumeric.
Student section has been represented by a single character which is 'J'.
Student age has been represented by a whole number which is 13.
Student sex has been represented by a single character which is 'F'.
This way, we realized that in our day-to-day life, we deal with different types of data such as
strings, characters, whole numbers (integers), and decimal numbers (floating point numbers).
Similarly, when we write a computer program to process different types of data, we need to
specify its type clearly; otherwise the computer does not understand how different operations
can be performed on that given data. Different programming languages use different keywords
to specify different data types. For example, C and Java programming languages use int to
specify integer data, whereas char specifies a character data type.
Subsequent chapters will show you how to use different data types in different situations. For
now, let's check the important data types available in C, Java, and Python and the keywords we
will use to specify those data types.
32
this data type
These data types are called primitive data types and you can use these data types to build more
complex data types, which are called user-defined data type, for example a string will be a
sequence of characters.
short int x;
long int y;
signed long int y;
unsigned long int a;
signed int x;
unsigned int x;
33
Here, Number specifies all types of numbers including decimal numbers and string represents a
sequence of characters with a length of 1 or more characters. For now, let's proceed with these
two data types and skip List, Tuple, and Dictionary, which are advanced data types in Python.
6 Computer Programming - Variables
Variables are the names you give to computer memory locations which are used to store values
in a computer program.
For example, assume you want to store two values 10 and 20 in your program and at a later
stage, you want to use these two values. Let's see how you will do it. Here are the following
three simple steps −
Create variables with appropriate names.
Store your values in those two variables.
Retrieve and use the stored values from the variables.
int main() {
int a;
int b;
}
The above program creates two variables to reserve two memory locations with names a and b.
We created these variables using int keyword to specify variable data type which means we
want to store integer values in these two variables. Similarly, you can create variables to
store long, float, char or any other data type. For example −
/* variable to store long value */
long a;
int main() {
int a, b;
}
34
Listed below are the key points about variables that you need to keep in mind −
A variable name can hold a single type of value. For example, if variable a has been
defined int type, then it can store only integer.
C programming language requires a variable creation, i.e., declaration before its usage in
your program. You cannot use a variable name in your program without creating it,
though programming language like Python allows you to use a variable name without
creating it.
You can use a variable name only once inside your program. For example, if a
variable a has been defined to store an integer value, then you cannot define a again to
store any other type of value.
There are programming languages like Python, PHP, Perl, etc., which do not want you to
specify data type at the time of creating variables. So you can store integer, float, or long
without specifying their data type.
You can give any name to a variable like age, sex, salary, year1990 or anything else you
like to give, but most of the programming languages allow to use only limited characters
in their variables names. For now, we will suggest to use only a....z, A....Z, 0....9 in your
variable names and start their names using alphabets only instead of digits.
Almost none of the programming languages allow to start their variable names with a
digit, so 1990year will not be a valid variable name whereas year1990 or ye1990ar are
valid variable names.
Every programming language provides more rules related to variables and you will learn them
when you will go in further detail of that programming language.
int main() {
int a;
int b;
a = 10;
b = 20;
}
The above program has two additional statements where we are storing 10 in variable a and 20
is being stored in variable b. Almost all the programming languages have similar way of storing
values in variable where we keep variable name in the left hand side of an equal sign = and
whatever value we want to store in the variable, we keep that value in the right hand side.
35
Now, we have completed two steps, first we created two variables and then we stored required
values in those variables. Now variable a has value 10 and variable b has value 20. In other
words we can say, when above program is executed, the memory location named a will hold 10
and memory location b will hold 20.
int main() {
int a;
int b;
a = 10;
b = 20;
int main() {
int a;
int b;
a = 10;
b = 20;
36
If you want to use float variable in C programming, then you will have to use %f instead
of %d, and if you want to print a character value, then you will have to use %c. Similarly,
different data types can be printed using different % and characters.
a = 10;
b = 20;
37
You can use the following syntax in C and Java programming to declare variables and assign
values at the same time −
#include <stdio.h>
int main() {
int a = 10;
int b = 20;
7.1.1.1 A symbolic constant is a name given to some numeric constant, or a character constant
#define PI 3.141592
#define GOLDENRATIO 1.6
#define MAX 500
38
Here PI, GOLDENRATIO, SIZE are symbolic constants.
Note: symbolic constants names are written in uppercase by convention, but it is not required.
Literals are the constant values assigned to the constant variables. We can say that
the literals represent the fixed values that cannot be modified. It also contains memory but does
not have references as variables. For example, const int =10; is a constant integer expression in
which 10 is an integer literal.
8 Computer Programming - Keywords
So far, we have covered two important concepts called variables and their data types. We
discussed how to use int, long, and float to specify different data types. We also learnt how to
name the variables to store different values.
Though this chapter is not required separately because reserved keywords are a part of basic
programming syntax, we kept it separate to explain it right after data types and variables to
make it easy to understand.
Like int, long, and float, there are many other keywords supported by C programming language
which we will use for different purpose. Different programming languages provide different set
of reserved keywords, but there is one important & common rule in all the programming
languages that we cannot use a reserved keyword to name our variables, which means we
cannot name our variable like int or float rather these keywords can only be used to specify a
variable data type.
For example, if you will try to use any reserved keyword for the purpose of variable name, then
you will get a syntax error.
#include <stdio.h>
int main() {
int float;
float = 10;
int main() {
int count;
count = 10;
double
int float;
40
class const continue default
volatile while
assert finally or
def if return
41
del import try
elif in while
else is with
We know you cannot memorize all these keywords, but we have listed them down for your
reference purpose and to explain the concept of reserved keywords. So just be careful while
giving a name to your variable, you should not use any reserved keyword for that programming
language.
P(x) = x4 + 7x3 - 5x + 9.
These two statements are called arithmetic expressions in a programming language
and plus, minus used in these expressions are called arithmetic operators and the values used in
these expressions like 2, 3 and x, etc., are called operands. In their simplest form, such
expressions produce numerical results.
Similarly, a programming language provides various arithmetic operators. The following table
lists down a few of the important arithmetic operators available in C programming language.
Assume variable A holds 10 and variable B holds 20, then −
42
Operator Description Example
int main() {
int a, b, c;
a = 10;
b = 20;
lvalue and rvalue
c = a + b;
c=10+20;
printf( "Value of c = %d\n", c);
43
c = a - b;
printf( "Value of c = %d\n", c);
c = a * b;
printf( "Value of c = %d\n", c);
c = b / a;
printf( "Value of c = %d\n", c);
c = b % a;
printf( "Value of c = %d\n", c);
}
When the above program is executed, it produces the following result −
Value of c = 30
Value of c = -10
Value of c = 200
Value of c = 2
Value of c = 0
44
condition becomes true.
> Checks if the value of left operand is greater (A > B) is not true.
than the value of right operand, if yes then
condition becomes true.
Here, we will show you one example of C Programming which makes use of if conditional
statement. Though this statement will be discussed later in a separate chapter, but in short, we
use if statement to check a condition and if the condition is true, then the body of if
statement is executed, otherwise the body of if statement is skipped.
#include <stdio.h>
int main() {
int a, b;
a = 10;
b = 20;
46
Try the following example to understand all the logical operators available in C programming
language −
#include <stdio.h>
int main()
{
int a = 1;
int b = 0;
if ( a&& b ) {
True(1) 1 0
False(0) 0 0
True(1) 1 1
False(0) 1 0
avg=78;
if(avg>=70 && avg<=100)
printf(“You qualify to do medicine”);
When you compile and execute the above program, it produces the following result −
47
This will be printed print because condition is true
This will be printed print because condition is true
a = 10;
b = 20;
c = a + b;
System.out.println("Value of c = " + c );
c = a - b;
System.out.println("Value of c = " + c );
c = a * b;
System.out.println("Value of c = " + c );
c = b / a;
System.out.println("Value of c = " + c );
c = b % a;
System.out.println("Value of c = " + c );
if( a == 10 ) {
48
a is equal to 10
c=a+b
print "Value of c = ", c
c=a-b
print "Value of c = ", c
c=a*b
print "Value of c = ", c
c=a/b
print "Value of c = ", c
c=a%b
print "Value of c = ", c
if( a == 10 ):
print "a is equal to 10"
When the above program is executed, it produces the following result −
Value of c = 30
Value of c = -10
Value of c = 200
Value of c = 0
Value of c = 10
a is equal to 10
10 Decision Statements
Decision making is critical to computer programming. There will be many situations when you
will be given two or more options and you will have to select an option based on the given
conditions.
49
Sequence
#include <stdio.h>
int main() {
int a;
int b;
a = 10;
b = 20;
For example, we want to print a remark about a student based on his secured marks. Following
is the situation −
Assume given marks are x for a student:
If given marks are less than 95 and more than 30, then
Student is average
Now, the question is how to write a programming code to handle such situations. Almost all the
programming languages provide conditional statements that work based on the following flow
diagram −
50
if(condition)
{
conditional code to execute (if the condition true)
}
#include <stdio.h>
int main() {
int a;
int b;
a = 10;
b = 20;
if(a>b)
{
printf( "%d is bigger than %d\n", a,b );
}
}
51
Let's write a C program with the help of if conditional statements to convert the above given
situation into a programming code –
Write a program that will check whether a student has passed exams. Assume the pass
mark is 40.
#include <stdio.h>
int main() {
int marks ;
printf(“Enter the marks obtained: ”);
scanf(“%d”,&marks);
if( marks >= 40) {
#include <stdio.h>
int main() {
int x = 45;
53
#include <stdio.h>
int main() {
int a;
int b;
a = 10;
b = 20;
if(a>b)
{
printf( "%d is bigger than %d\n", a,b );
}
else
{
printf( "%d is smaller than %d\n", a,b );
}
An if...else statement is useful when we have to take a decision out of two options. For example,
if a student secures more marks than 95, then the student is brilliant, otherwise no such situation
can be coded, as follows –
Write a program that will check whether a student has passed or failed exams. Assume the
pass mark is 40.
#include <stdio.h>
int main() {
int marks ;
printf(“Enter the marks obtained: ”);
scanf(“%d”,&marks);
if( marks >= 40) {
}
}
54
#include <stdio.h>
int main() {
int x = 45;
55
Now with the help of if...elseif...else statement, the very first program can be coded as follows −
#include <stdio.h>
int main() {
int x = 45;
default :
statement(s);
}
The expression used in a switch statement must give an integer value, which will be compared
for equality with different cases given. Wherever an expression value matches with a case
value, the body of that case will be executed and finally, the switch will be terminated using
a break statement. If no break statements are provided, then the computer continues executing
other statements available below to the matched case. If none of the cases matches, then the
default case body is executed.
The above syntax can be represented in the form of a flow diagram as shown below −
56
Now, let's consider another example where we want to write the equivalent English word for a
given number. Then, it can be coded as follows –
#include <stdio.h>
int main() {
int x = 2;
switch( x ){
case 1 :
printf( "One\n");
break;
case 2 :
printf( "Two\n");
break;
case 3 :
printf( "Three\n");
break;
case 4 :
printf( "Four\n");
57
break;
default :
printf( "None of the above...\n");
}
}
When the above program is executed, it produces the following result −
Two
if x > 95:
58
print "Student is brilliant"
elif x < 30:
print "Student is poor"
elif x < 95 and x > 30:
print "Student is average"
Let's consider a situation when you want to print Hello, World! five times. Here is a simple C
program to do the same −
#include <stdio.h>
int main() {
printf( "Hello, World!\n");
printf( "Hello, World!\n");
printf( "Hello, World!\n");
printf( "Hello, World!\n");
printf( "Hello, World!\n");
}
#include <stdio.h>
int main() {
printf( "Hello, World!\n");
printf( "Hello, World!\n");
printf( "Hello, World!\n");
printf( "Hello, World!\n");
printf( "Hello, World!\n");
printf( "Hello, World!\n");
printf( "Hello, World!\n");
printf( "Hello, World!\n");
printf( "Hello, World!\n");
printf( "Hello, World!\n");
int main() {
int i = 0;
while ( i < 5 ) {
printf( "Hello, World!\n");
i = i + 1;
}
}
When the above program is executed, it produces the following result −
Hello, World!
Hello, World!
Hello, World!
Hello, World!
Hello, World!
The above program makes use of a while loop, which is being used to execute a set of
programming statements enclosed within {....}. Here, the computer first checks whether the
given condition, i.e., variable "a" is less than 5 or not and if it finds the condition is true, then
the loop body is entered to execute the given statements. Here, we have the following two
statements in the loop body −
First statement is printf() function, which prints Hello World!
Second statement is i = i + 1, which is used to increase the value of variable i
After executing all the statements given in the loop body, the computer goes back to while( i <
5) and the given condition, (i < 5), is checked again, and the loop is executed again if the
condition holds true. This process repeats till the given condition remains true which means
variable "a" has a value less than 5.
60
To conclude, a loop statement allows us to execute a statement or group of statements multiple
times. Given below is the general form of a loop statement in most of the programming
languages −
This tutorial has been designed to present programming's basic concepts to non-programmers,
so let's discuss the two most important loops available in C programming language. Once you
are clear about these two loops, then you can pick-up C programming tutorial or a reference
book and check other loops available in C and the way they work.
61
The following important points are to be noted about a while loop −
A while loop starts with a keyword while followed by a condition enclosed in ( ).
Further to the while() statement, you will have the body of the loop enclosed in curly
braces {...}.
A while loop body can have one or more lines of source code to be executed repeatedly.
If the body of a while loop has just one line, then its optional to use curly braces {...}.
A while loop keeps executing its body till a given condition holds true. As soon as the
condition becomes false, the while loop comes out and continues executing from the
immediate next statement after the while loop body.
A condition is usually a relational statement, which is evaluated to either true or false. A
value equal to zero is treated as false and any non-zero value works like true.
If you will write the above example using do...while loop, then Hello, World will produce the
same result −
#include <stdio.h>
int main() {
int i = 0;
do {
printf( "Hello, World!\n");
i = i + 1;
}
while ( i < 5 );
}
When the above program is executed, it produces the following result −
Hello, World!
Hello, World!
Hello, World!
Hello, World!
Hello, World!
63
11.3 The break statement
When the break statement is encountered inside a loop, the loop is immediately terminated and
the program control resumes at the next statement following the loop. The syntax for
a break statement in C is as follows −
break;
A break statement can be represented in the form of a flow diagram as shown below −
Following is a variant of the above program, but it will come out after printing Hello World!
only three times −
#include <stdio.h>
int main() {
int i = 0;
do {
printf( "Hello, World!\n");
i = i + 1;
if( i == 3 ) {
break;
}
}
while ( i < 5 );
}
When the above program is executed, it produces the following result −
64
Hello, World!
Hello, World!
Hello, World!
Following is a variant of the above program, but it will skip printing when the variable has a
value equal to 3 −
#include <stdio.h>
int main() {
int i = 0;
do {
if( i == 3 ) {
i = i + 1;
continue;
}
printf( "Hello, World!\n");
i = i + 1;
}
65
while ( i < 5 );
}
When the above program is executed, it produces the following result −
Hello, World!
Hello, World!
Hello, World!
Hello, World!
while ( i < 5 ) {
System.out.println("Hello, World!");
i = i + 1;
}
}
}
The break and continue statements in Java programming work quite the same way as they
work in C programming.
Every programming language provides support for manipulating different types of numbers
such as simple whole integers and floating point numbers. C, Java, and Python categorize these
numbers in several categories based on their nature.
Let's go back and check the data types chapter, where we listed down the core data types related
to numbers −
These data types are called primitive data types and you can use these data types to build more
data types, which are called user-defined data types.
We have seen various mathematical and logical operations on numbers during a discussion on
operators. So we know how to add numbers, subtract numbers, divide numbers, etc.
First let's see how to print various types of numbers available in C programming language −
#include <stdio.h>
int main() {
short s;
int i;
67
long l;
float f;
double d;
s = 10;
i = 1000;
l = 1000000;
f = 230.47;
d = 30949.374;
1 double cos(double);
This function takes an angle (as a double) and returns the cosine.
2 double sin(double);
This function takes an angle (as a double) and returns the sine.
3 double tan(double);
68
This function takes an angle (as a double) and returns the tangent.
4 double log(double);
This function takes a number and returns the natural log of that
number.
7 double sqrt(double);
You pass this function a number and it returns its square root.
8 int abs(int);
This function returns the absolute value of an integer that is passed
to it.
9 double fabs(double);
This function returns the absolute value of any decimal number
passed to it.
10 double floor(double);
Finds the integer which is less than or equal to the argument passed
to it.
69
int main() {
short s;
int i;
long l;
float f;
double d;
s = 10;
i = 1000;
l = 1000000L;
f = 230.47f;
d = 30949.374;
If it was easy to work with numbers in computer programming, it would be even easier to work
with characters. Characters are simple alphabets like a, b, c, d...., A, B, C, D,....., but with an
exception. In computer programming, any single digit number like 0, 1, 2,....and special
characters like $, %, +, -.... etc., are also treated as characters and to assign them in a character
type variable, you simply need to put them inside single quotes. For example, the following
statement defines a character type variable ch and we assign a value 'a' to it −
char ch = 'a';
Here, ch is a variable of character type which can hold a character of the implementation's
character set and 'a' is called a character literal or a character constant. Not only a, b, c,.... but
when any number like 1, 2, 3.... or any special character like !, @, #, #, $,.... is kept inside single
quotes, then they will be treated as a character literal and can be assigned to a variable of
character type, so the following is a valid statement −
char ch = '1';
A character data type consumes 8 bits of memory which means you can store anything in a
character whose ASCII value lies in between -127 to 127, so it can hold any of the 256 different
values. A character data type can store any of the characters available on your keyboard
including special characters like !, @, #, #, $, %, ^, &, *, (, ), _, +, {, }, etc.
Note that you can keep only a single alphabet or a single digit number inside single quotes and
more than one alphabets or digits are not allowed inside single quotes. So the following
statements are invalid in C programming −
char ch1 = 'ab';
char ch2 = '10';
72
Given below is a simple example, which shows how to define, assign, and print characters in C
Programming language −
#include <stdio.h>
int main() {
char ch1;
char ch2;
char ch3;
char ch4;
ch1 = 'a';
ch2 = '1';
ch3 = '$';
ch4 = '+';
73
\t Inserts a tab in the text at this point.
The following example shows how the compiler interprets an escape sequence in a print
statement −
#include <stdio.h>
int main() {
char ch1;
char ch2;
char ch3;
char ch4;
ch1 = '\t';
ch2 = '\n';
printf( "Test for tabspace %c and a newline %c will start here", ch1, ch2);
}
When the above program is executed, it produces the following result −
Test for tabspace and a newline
will start here
74
You can try to execute the following program to see the output, which must be identical to the
result generated by the above C example.
public class DemoJava {
public static void main(String []args) {
char ch1;
char ch2;
char ch3;
char ch4;
ch1 = 'a';
ch2 = '1';
ch3 = '$';
ch4 = '+';
Consider a situation where we need to store five integer numbers. If we use programming's
simple variable and data type concepts, then we need five variables of int data type and the
program will be as follows −
#include <stdio.h>
int main() {
int number1;
int number2;
int number3;
int number4;
int number5;
number1 = 10;
number2 = 20;
number3 = 30;
number4 = 40;
number5 = 50;
76
Instead of declaring individual variables, such as number1, number2, ..., number99, you just
declare one array variable number of integer type and use number1[0], number1[1], and ...,
number1[99] to represent individual variables. Here, 0, 1, 2, .....99 are index associated
with var variable and they are being used to represent individual elements available in the array.
All arrays consist of contiguous memory locations. The lowest address corresponds to the first
element and the highest address to the last element.
int main () {
int number[10]; /* number is an array of 10 integers */
int i = 0;
return 0;
}
When the above code is compiled and executed, it produces the following result −
number[0] = 100
number[1] = 101
number[2] = 102
number[3] = 103
number[4] = 104
78
number[5] = 105
number[6] = 106
number[7] = 107
number[8] = 108
number[9] = 109
while( i < 10 ) {
number[ i ] = i + 100;
i = i + 1;
}
i = 0;
while( i < 10 ) {
System.out.format( "number[%d] = %d\n", i, number[i] );
i = i + 1;
}
}
}
When the above program is executed, it produces the following result −
number[0] = 100
number[1] = 101
number[2] = 102
number[3] = 103
number[4] = 104
number[5] = 105
number[6] = 106
number[7] = 107
number[8] = 108
number[9] = 109
79
14.5 Arrays (Lists) in Python
Python does not have a concept of Array, instead Python provides another data structure
called list, which provides similar functionality as arrays in any other language.
Following is the equivalent program written in Python −
# Following defines an empty list.
number = []
i=0
i=0
while i < 10:
# Accessing elements from the list
print "number[", i, "] = ", number[ i ]
i=i+1
When the above program is executed, it produces the following result −
number[ 0 ] = 100
number[ 1 ] = 101
number[ 2 ] = 102
number[ 3 ] = 103
number[ 4 ] = 104
number[ 5 ] = 105
number[ 6 ] = 106
number[ 7 ] = 107
number[ 8 ] = 108
number[ 9 ] = 109
15 Computer Programming - Strings
During our discussion about characters, we learnt that character data type deals with a single
character and you can assign any character from your keyboard to a character type variable.
Now, let's move a little bit ahead and consider a situation where we need to store more than one
character in a variable. We have seen that C programming does not allow to store more than one
character in a character type variable. So the following statements are invalid in C programming
and produce syntax errors −
char ch1 = 'ab';
char ch2 = '10';
We have also seen how to use the concept of arrays to store more than one value of similar data
type in a variable. Here is the syntax to store and print five numbers in an array of int type −
80
#include <stdio.h>
main() {
int number[5] = {10, 20, 30, 40, 50};
int i = 0;
while( i < 5 ) {
printf("number[%d] = %d\n", i, number[i] );
i = i + 1;
}
}
When the above code is compiled and executed, it produces the following result −
number[0] = 10
number[1] = 20
number[2] = 30
number[3] = 40
number[4] = 50
Now, let's define an array of five characters in the same way as we did for numbers and try to
print them −
#include <stdio.h>
main() {
char ch[5] = {'H', 'e', 'l', 'l', 'o'};
int i = 0;
while( i < 5 ) {
printf("ch[%d] = %c\n", i, ch[i] );
i = i + 1;
}
}
Here, we used %c to print character value. When the above code is compiled and executed, it
produces the following result −
ch[0] = H
ch[1] = e
ch[2] = l
ch[3] = l
ch[4] = o
If you are done with the above example, then I think you understood how strings work in C
programming, because strings in C are represented as arrays of characters. C programming
simplified the assignment and printing of strings. Let's check the same example once again with
a simplified syntax −
#include <stdio.h>
81
main() {
char ch[5] = "Hello";
int i = 0;
Although it's not visible from the above examples, a C program internally assigns null
character '\0' as the last character of every string. It indicates the end of the string and it means
if you want to store a 5 character string in an array, then you must define an array size of 6 as a
good practice, though C does not complain about it.
If the above code is compiled and executed, it produces the following result −
String = Hello
ch[0] = H
ch[1] = e
ch[2] = l
ch[3] = l
ch[4] = o
82
Strings in C are represented as arrays of characters.
We can constitute a string in C programming by assigning character by character into an
array of characters.
We can constitute a string in C programming by assigning a complete string enclosed in
double quote.
We can print a string character by character using an array subscript or a complete string
by using an array name without subscript.
The last character of every string is a null character, i.e., ‘\0’.
Most of the programming languages provide built-in functions to manipulate strings, i.e.,
you can concatenate strings, you can search from a string, you can extract sub-strings
from a string, etc. For more, you can check our detailed tutorial on C programming or
any other programming language.
83
print "var1 = ", var1
print "var2 = ", var2
When the above program is executed, it produces the following result −
var1 = Hello World!
var2 = Python Programming
Python does not support character type; these are treated as strings of length one, thus also
considered a substring.
To access substrings, use the square brackets for slicing along with the index or indices to
obtain your substring. Take a look at the following code segment −
var1 = 'Hello World!'
var2 = "Python Programming"
A function is a block of organized, reusable code that is used to perform a single, related action.
Functions provide better modularity for your application and a high degree of code reusing. You
have already seen various functions like printf() and main(). These are called built-in functions
provided by the language itself, but we can write our own functions as well and this tutorial will
teach you how to write and use those functions in C programming language.
Good thing about functions is that they are famous with several names. Different programming
languages name them differently, for example, functions, methods, sub-routines, procedures,
etc. If you come across any such terminology, then just imagine about the same concept, which
we are going to discuss in this tutorial.
Let's start with a program where we will define two arrays of numbers and then from each
array, we will find the biggest number. Given below are the steps to find out the maximum
number from a given set of numbers −
1. Get a list of numbers L1, L2, L3....LN
2. Assume L1 is the largest, Set max = L1
3. Take next number Li from the list and do the following
4. If max is less than Li
5. Set max = Li
6. If Li is last number from the list then
7. Print value stored in max and come out
8. Else prepeat same process starting from step 3
84
Let's translate the above program in C programming language −
#include <stdio.h>
int main() {
int set1[5] = {10, 20, 30, 40, 50};
int set2[5] = {101, 201, 301, 401, 501};
int i, max;
85
16.1 Defining a Function
The general form of a function definition in C programming language is as follows −
return_type function_name( parameter list ) {
body of the function
return [expression];
}
A function definition in C programming consists of a function header and a function body. Here
are all the parts of a function −
Return Type − A function may return a value. The return_type is the data type of the
value the function returns. Some functions perform the desired operations without
returning a value. In this case, the return_type is the keyword void.
Function Name − This is the actual name of the function. The function name and the
parameter list together constitute the function signature.
Parameter List − A parameter is like a placeholder. When a function is invoked, you
pass a value as a parameter. This value is referred to as the actual parameter or
argument. The parameter list refers to the type, order, and number of the parameters of a
function. Parameters are optional; that is, a function may contain no parameters.
Function Body − The function body contains a collection of statements that defines
what the function does.
max = set[0];
i = 1;
while( i < 5 ) {
if( max < set[i] ) {
max = set[i];
}
i = i + 1;
}
return max;
}
main() {
86
int set1[5] = {10, 20, 30, 40, 50};
int set2[5] = {101, 201, 301, 401, 501};
int max;
while( i < 5 ) {
if( max < set[i] ) {
max = set[i];
87
}
i = i + 1;
}
return max;
}
}
When the above program is executed, it produces the following result −
Max in first set = 50
Max in second set = 501
return [expression]
Using this syntax of function in Python, the above example can be written as follows −
def getMax( set ):
max = set[0]
i=1
while( i < 5 ):
if( max < set[i] ):
max = set[i]
i=i+1
return max
1 r
Opens an existing text file for reading purpose.
2 w
Opens a text file for writing. If it does not exist, then a new file is
created. Here, your program will start writing content from the
beginning of the file.
3 a
Opens a text file for writing in appending mode. If it does not exist,
then a new file is created. Here, your program will start appending
content in the existing file content.
4 r+
Opens a text file for reading and writing both.
5 w+
Opens a text file for both reading and writing. It first truncates the file
to zero length, if it exists; otherwise creates the file if it does not
exist.
6 a+
Opens a text file for both reading and writing. It creates a file, if it
does not exist. The reading will start from the beginning, but writing
90
can only be appended.
int main() {
FILE *fp;
fp = fopen("/tmp/test.txt", "w+");
fprintf(fp, "This is testing for fprintf...\n");
fputs("This is testing for fputs...\n", fp);
fclose(fp);
}
When the above code is compiled and executed, it creates a new file test.txt in /tmp directory
and writes two lines using two different functions. Let us read this file in the next section.
main() {
FILE *fp;
char buff[255];
fp = fopen("/tmp/test.txt", "r");
fscanf(fp, "%s", buff);
printf("1 : %s\n", buff );
// Create a File
file.createNewFile();
The algorithms are designed using two approaches that are the top-down and bottom-up
approach. In the top-down approach, the complex module is divided into submodules. On the
other hand, bottom-up approach begins with elementary modules and then combine them further.
94
The prior purpose of an algorithm is to operate the data comprised in the data structure. In other
words, an algorithm is used to perform the operations on the data inside the data structures.
A complicated algorithm is split into small parts called modules, and the process of splitting is
known as modularization. Modularization significantly reduces the complications of designing
an algorithm and make its process easier to design and implement. Modular programming is the
technique of designing and writing a program in the form of the functions where each function is
distinct from each other and works independently. The content in the functions are cohesive in
manner, and there exists a low coupling between the modules.
Comparison Chart
BASIS FOR
TOP-DOWN APPROACH BOTTOM-UP APPROACH
COMPARISON
Basic Breaks the massive problem into Solves the fundamental low-level
smaller subproblems. problem and integrates them into
a larger one.
The top-down approach basically divides a complex problem or algorithm into multiple smaller
parts (modules). These modules are further decomposed until the resulting module is the
fundamental program essentially be understood and cannot be further decomposed. After
achieving a certain level of modularity, the decomposition of modules is ceased. The top-down
approach is the stepwise process of breaking of the large program module into simpler and
95
smaller modules to organize and code program in an efficient way. The flow of control in this
approach is always in the downward direction. The top-down approach is implemented in the
“C” programming language by using functions.
Thus, the top-down method begins with abstract design and then sequentially this design is
refined to create more concrete levels until there is no requirement of additional refinement.
The bottom-up approach works in just opposite manner to the top-down approach. Initially, it
includes the designing of the most fundamental parts which are then combined to make the
higher level module. This integration of submodules and modules into the higher level module is
repeatedly performed until the required complete algorithm is obtained.
Bottom-up approach functions with layers of abstraction. The primary application of the bottom-
up approach is testing as each fundamental module is first tested before merging it to the bigger
one. The testing is accomplished using the certain low-level functions.
Top-down approach decomposes the large task into smaller subtasks whereas bottom-up
approach first chooses to solve the different fundamental parts of the task directly then
combine those parts into a whole program.
Each submodule is separately processed in a top-down approach. As against, bottom-up
approach implements the concept of the information hiding by examining the data to be
encapsulated.
The different modules in top-down approach don’t require much communication. On the
contrary, the bottom-up approach needs interaction between the separate fundamental
modules to combine them later.
Top-down approach can produce redundancy while bottom-up approach does not include
redundant information.
The procedural programming languages such as Fortran, COBOL and C follows a top-down
approach. In contrast, object-oriented programming languages like C++, Java, C#, Perl,
Python abides the bottom-up approach.
Bottom-up approach is priorly used in testing. Conversely, the top-down approach is utilized
in module documentation, test case creation, debugging, etcetera.
Conclusion
The top-down approach and bottom-up approach are the algorithm design methods where top-
down is a conventional approach which decomposes the system from high-level specification to
96
low-level specification. On the other hand, the bottom-up approach is more efficient and works
in an inverse manner where the primitive components are designed at first then proceeded to the
higher level.
The top-down approach emphasizes on the isolation of the submodules (signifies the low
coupling between the modules) while ignores the identification of communication and reusability
concept. While in the bottom-up approach, information hiding and reusability are the prominent
factors.
We appreciate your patience for going through this tutorial. We have tried to keep it concise but
as this subject contains several topics, we have shown a few examples in detail.
If you have not understood any of the concepts, then we recommend to go through the tutorial
once again and once you are comfortable with the concepts explained in this tutorial, you can
proceed further.
There are many other subjects related to computer programming which we did not cover
intentionally to avoid any confusion, but we are sure those concepts will not be difficult for you
to understand as long as you make yourself comfortable with the concepts explained in this
tutorial.
At tutorialspoint, we have put lots of effort to prepare comprehensive tutorials on C, Java, and
Python programming languages and we strongly recommend you to start either of them, after
having completed this tutorial.
97