Topic outline
- General
- Course Outline
Course Outline
This course is an introduction to structured computer programming. Students will study algorithms and top-down design, and will implement algorithms in a procedural programming language. Lab exercises and programming assignments will emphasize scientific and numerical applications. This course has been designed with the following objectives in mind: (1) To provide the understanding of structured programming Principles (2) To use structured programming principles in problem solving by transferring the model-based problem into computer based solution (3) To enhance communication and social skills through group project
- Structured Programming - OverviewThis topic
Structured Programming - Overview
Introduction to Computer Program
Before getting into computer programming, let us first understand computer programs and what they do.
A computer program is a sequence of instructions written using a Computer Programming Language to perform a specified task by the computer.
The two important terms that we have used in the above definition are −
- Sequence of instructions
- Computer Programming Language
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
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.
Introduction to Computer Programming
If you understood what a computer program is, then we will say: the act of writing computer programs is called computer programming.
As we mentioned earlier, there are hundreds of programming languages, which can be used to write computer programs and following are a few of them −
- Java
- C
- C++
- Python
- PHP
- Perl
- Ruby
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.
Computer Programmer
Someone who can write computer programs or in other words, someone who can do computer programming is called a Computer Programmer.
Based on computer programming language expertise, we can name a computer programmers as follows −
- C Programmer
- C++ Programmer
- Java Programmer
- Python Programmer
- PHP Programmer
- Perl Programmer
- Ruby Programmer
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 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.
Exercise 1: Try out these simple exercises to get you ready
- Write a program that asks the user for a number
n
and gives them the possibility to choose between computing the sum and computing the product of 1,…,n
. - Write a program that prints a multiplication table for numbers up to 12.
- Write a program that prints all prime numbers. (Note: if your programming language does not support arbitrary size numbers, printing all primes up to the largest number you can easily represent is fine too.)
- Write a guessing game where the user has to guess a secret number. After every guess the program tells the user whether their number was too large or too small. At the end the number of tries needed should be printed. It counts only as one try if they input the same number multiple times consecutively.
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
- 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
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.
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.
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 −
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.
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.
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.
Computer Programming - Basic Syntax
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.
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.
#include <stdio.h> 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.
Program Entry Point
For now, just forget about the #include <stdio.h> statement, but keep a note that you have to put this statement at the top of a C program.
Every C program starts with main(), which is called the main function, and then it is followed by a left curly brace. The rest of the program instruction is written in between and finally a right curly brace ends the program.
The coding part inside these two curly braces is called the program body. The left curly brace can be in the same line as main(){ or in the next line like it has been mentioned in the above program.
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.
Some of the programming languages use the word sub-routine instead of function, but their functionality is more or less the same.
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.
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 −
Whitespace Explanation Representation New Line To create a new line \n Tab To create a tab. \t Space To create a space. empty space 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() { /* printf() function to write Hello, World! */ printf( "Hello, World!" ); }
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
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!
We will learn identifiers and keywords in next few chapters.
Program Explanation
Let us understand how the above C program works. First of all, the above program is converted into a binary format using C compiler. So let’s put this code in test.c file and compile it as follows −
$gcc test.c -o demo
If there is any grammatical error (Syntax errors in computer terminologies), then we fix it before converting it into binary format. If everything goes fine, then it produces a binary file called demo. Finally, we execute the produced binary demo as follows −
$./demo
which produces the following result −
Hello, World!
Here, when we execute the binary a.out file, the computer enters inside the program starting from main() and encounters a printf() statement. Keep a note that the line inside /*....*/ is a comment and it is filtered at the time of compilation. So printf() function instructs the computer to print the given line at the computer screen. Finally, it encounters a right curly brace which indicates the end of main() function and exits the program.
Syntax Error
If you do not follow the rules defined by the programing language, then at the time of compilation, you will get syntax errors and the program will not be compiled. From syntax point of view, even a single dot or comma or a single semicolon matters and you should take care of such small syntax as well. In the following example, we have skipped a semicolon, let's try to compile the program −
#include <stdio.h> 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.
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!
Hello World Program in Python
Following is the equivalent program written in Python. This program will also produce the same result Hello, World!.
# print function to write Hello, World! */ print "Hello, World!"
which produces the following result −
Hello, World!
Hope you noted that for C and Java examples, first we are compiling the programs and then executing the produced binaries, but in Python program, we are directly executing it. As we explained in the previous chapter, Python is an interpreted language and it does not need an intermediate step called compilation.
Python does not require a semicolon (;) to terminate a statement, rather a new line always means termination of the statement.
- Module 2: Understanding Datatype, Variables, Keywords and Operators
Module 2: Understanding Datatype, Variables, Keywords and Operators
Computer Programming - Data Types
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
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.
C and Java Data Types
C and Java support almost the same set of data types, though Java supports additional data types. For now, we are taking a few common data types supported by both the programming languages −
Type Keyword Value range which can be represented by this data type Character char -128 to 127 or 0 to 255 Number int -32,768 to 32,767 or -2,147,483,648 to 2,147,483,647 Small Number short -32,768 to 32,767 Long Number long -2,147,483,648 to 2,147,483,647 Decimal Number float 1.2E-38 to 3.4E+38 till 6 decimal places 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.
Python Data Types
Python has five standard data types but this programming language does not make use of any keyword to specify a particular data type, rather Python is intelligent enough to understand a given data type automatically.
- Numbers
- String
- List
- Tuple
- Dictionary
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
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.
Creating variables
Creating variables is also called declaring variables in C programming. Different programming languages have different ways of creating variables inside a program. For example, C programming has the following simple way of creating variables −
#include <stdio.h> 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; /* variable to store float value */ float b;
You can create variables of similar type by putting them in a single line but separated by comma as follows −
#include <stdio.h> int main() { int a, b; }
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.
Store Values in Variables
You have seen how we created variables in the previous section. Now, let's store some values in those variables −
#include <stdio.h> 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.
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.
Access stored values in variables
If we do not use the stored values in the variables, then there is no point in creating variables and storing values in them. We know that the above program has two variables a and b and they store the values 10 and 20, respectively. So let's try to print the values stored in these two variables. Following is a C program, which prints the values stored in its variables −
#include <stdio.h> int main() { int a; int b; a = 10; b = 20; printf( "Value of a = %d\n", a ); printf( "Value of b = %d\n", b ); }
When the above program is executed, it produces the following result −
Value of a = 10 Value of b = 20
You must have seen printf() function in the previous chapter where we had used it to print "Hello, World!". This time, we are using it to print the values of variables. We are making use of %d, which will be replaced with the values of the given variable in printf() statements. We can print both the values using a single printf() statement as follows −
#include <stdio.h> int main() { int a; int b; a = 10; b = 20; printf( "Value of a = %d and value of b = %d\n", a, b ); }
When the above program is executed, it produces the following result −
Value of a = 10 and value of b = 20
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.
Variables in Java
Following is the equivalent program written in Java programming language. This program will create two variables a and b and very similar to C programming, it will assign 10 and 20 in these variables and finally print the values of the two variables in two ways −
public class DemoJava { public static void main(String []args) { int a; int b; a = 10; b = 20; System.out.println("Value of a = " + a); System.out.println("Value of b = " + b); System.out.println("Value of a = " + a + " and value of b = " + b); } }
When the above program is executed, it produces the following result −
Value of a = 10 Value of b = 20 Value of a = 10 and value of b = 20
Variables in Python
Following is the equivalent program written in Python. This program will create two variables a and b and at the same time, assign 10 and 20 in those variables.
Python does not want you to specify the data type at the time of variable creation and there is no need to create variables in advance.
a = 10 b = 20 print "Value of a = ", a print "Value of b = ", b print "Value of a = ", a, " and value of b = ", b
When the above program is executed, it produces the following result −
Value of a = 10 Value of b = 20 Value of a = 10 and value of b = 20
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; printf( "Value of a = %d and value of b = %d\n", a, b ); }
When the above program is executed, it produces the following result −
Value of a = 10 and value of b = 20
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; printf( "Value of float = %d\n", float); }
When you compile the above program, it produces the following error −
main.c: In function 'main': main.c:5:8: error: two or more data types in declaration specifiers int float; ......
Let's now give a proper name to our integer variable, then the above program should compile and execute successfully −
#include <stdio.h> int main() { int count; count = 10; printf( "Value of count = %d\n", count); }
C Programming Reserved Keywords
Here is a table having almost all the keywords supported by C Programming language −
auto else long switch break enum register typedef case extern return union char float short unsigned const for signed void continue goto sizeof volatile default if static while do int struct _Packed double Java Programming Reserved Keywords
Here is a table having almost all the keywords supported by Java Programming language −
abstract assert boolean break byte case catch char class const continue default do double else enum extends final finally float for goto if implements import instanceof int interface long native new package private protected public return short static strictfp super switch synchronized this throw throws transient try void volatile while Python Programming Reserved Keywords
Here is a table having almost all the keywords supported by Python Programming language −
and exec not assert finally or break for pass class from print continue global raise def if return del import try elif in while else is with except lambda yield 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.
Computer Programming - Operators
An operator in a programming language is a symbol that tells the compiler or interpreter to perform specific mathematical, relational or logical operation and produce final result. This chapter will explain the concept of operators and it will take you through the important arithmetic and relational operators available in C, Java, and Python.Arithmetic Operators
Computer programs are widely used for mathematical calculations. We can write a computer program which can do simple calculation like adding two numbers (2 + 3) and we can also write a program, which can solve a complex equation like P(x) = x4 + 7x3 - 5x + 9. If you have been even a poor student, you must be aware that in first expression 2 and 3 are operands and + is an operator. Similar concepts exist in Computer Programming.
Take a look at the following two examples −
2 + 3 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 −
Operator Description Example + Adds two operands A + B will give 30 - Subtracts second operand from the first A - B will give -10 * Multiplies both operands A * B will give 200 / Divides numerator by de-numerator B / A will give 2 % This gives remainder of an integer division B % A will give 0 Following is a simple example of C Programming to understand the above mathematical operators −
#include <stdio.h> int main() { int a, b, c; a = 10; b = 20; c = a + b; printf( "Value of c = %d\n", c); 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
Relational Operators
Consider a situation where we create two variables and assign them some values as follows −
A = 20 B = 10
Here, it is obvious that variable A is greater than B in values. So, we need the help of some symbols to write such expressions which are called relational expressions. If we use C programming language, then it will be written as follows −
(A > B)
Here, we used a symbol > and it is called a relational operator and in their simplest form, they produce Boolean results which means the result will be either true or false. Similarly, a programming language provides various relational operators. The following table lists down a few of the important relational operators available in C programming language. Assume variable A holds 10 and variable B holds 20, then −
Operator Description Example == Checks if the values of two operands are equal or not, if yes then condition becomes true. (A == B) is not true. != Checks if the values of two operands are equal or not, if values are not equal then condition becomes true. (A != B) is true. > Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true. (A > B) is not true. < Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true. (A < B) is true. >= Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true. (A >= B) is not true. <= Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true. (A <= B) is 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; /* Here we check whether a is equal to 10 or not */ if( a == 10 ) { /* if a is equal to 10 then this body will be executed */ printf( "a is equal to 10\n"); } /* Here we check whether b is equal to 10 or not */ if( b == 10 ) { /* if b is equal to 10 then this body will be executed */ printf( "b is equal to 10\n"); } /* Here we check if a is less b than or not */ if( a < b ) { /* if a is less than b then this body will be executed */ printf( "a is less than b\n"); } /* Here we check whether a and b are not equal */ if( a != b ) { /* if a is not equal to b then this body will be executed */ printf( "a is not equal to b\n"); } }
When the above program is executed, it produces the following result −
a is equal to 10 a is less than b a is not equal to b
Logical Operators
Logical operators are very important in any programming language and they help us take decisions based on certain conditions. Suppose we want to combine the result of two conditions, then logical AND and OR logical operators help us in producing the final result.
The following table shows all the logical operators supported by the C language. Assume variable A holds 1 and variable B holds 0, then −
Operator Description Example && Called Logical AND operator. If both the operands are non-zero, then condition becomes true. (A && B) is false. || Called Logical OR Operator. If any of the two operands is non-zero, then condition becomes true. (A || B) is true. ! Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false. !(A && B) is true. 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 ) { printf("This will never print because condition is false\n" ); } if ( a || b ) { printf("This will be printed print because condition is true\n" ); } if ( !(a && b) ) { printf("This will be printed print because condition is true\n" ); } }
When you compile and execute the above program, it produces the following result −
This will be printed print because condition is true This will be printed print because condition is true
Operators in Java
Following is the equivalent program written in Java. C programming and Java provide almost identical set of operators and conditional statements. This program will create two variables a and b, very similar to C programming, then we assign 10 and 20 in these variables and finally, we will use different arithmetic and relational operators −
You can try to execute the following program to see the output, which must be identical to the result generated by the above example.
public class DemoJava { public static void main(String []args) { int a, b, c; 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 ) { System.out.println("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 = 2 Value of c = 0 a is equal to 10
Operators in Python
Following is the equivalent program written in Python. This program will create two variables a and b and at the same time, assign 10 and 20 in those variables. Fortunately, C programming and Python programming languages provide almost identical set of operators. This program will create two variables a and b, very similar to C programming, then we assign 10 and 20 in these variables and finally, we will use different arithmetic and relational operators.
You can try to execute the following program to see the output, which must be identical to the result generated by the above example.
a = 10 b = 20 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
- Module 3: Structured Programming
Module 3: Structured Programming
Structured programming (sometimes known as modular programming) is a programming paradigm that facilitates the creation of programs with readable code and reusable components. All modern programming languages support structured programming, but the mechanisms of support, like the syntax of the programming languages, varies.
Graphical representation of the three basic patterns — sequence, selection, and repetition — using NS diagrams (blue) and flow charts (green).Where modules or elements of code can be reused from a library, it may also be possible to build structured code using modules written in different languages, as long as they can obey a common module interface or application program interface (API) specification. However, when modules are reused, it's possible to compromise data security and governance, so it's important to define and enforce a privacy policy controlling the use of modules that bring with them implicit data access rights.
Structured programming encourages dividing an application program into a hierarchy of modules or autonomous elements, which may, in turn, contain other such elements. Within each element, code may be further structured using blocks of related logic designed to improve readability and maintainability. These may include case, which tests a variable against a set of values; Repeat, while and for, which construct loops that continue until a condition is met. In all structured programming languages, an unconditional transfer of control, or goto statement, is deprecated and sometimes not even available.
Difference between structured and unstructured programming languages
A structured programming language facilitates or enforces structured programming practices. These practices can also be supported with unstructured languages, but that will require specific steps in program design and implementation. Structured programming practices thus date to the emergence of structured programming languages.
The theoretical basis for structured programming goes back to the 1950s, with the emergence of the ALGOL 58 and 60 languages. Up to then, code clarity was reduced by the need to build condition/action tests by having programmers write linked tests and actions explicitly (using the goto statement or its equivalent), resulting in what was often called spaghetti code. ALGOL included block structure, where an element of code included a condition and an action.
Modular programming, which is today seen as synonymous with structured programming, emerged a decade later as it became clear that reuse of common code could improve developer productivity. In modular programming, a program is divided into semi-independent modules, each of which are called when needed. Purists argue that modular programming requires actual independence of modules, but most development teams consider any program that divides logic into separate elements, even if those elements exist within the same program, as modular.
Modern programming languages are universally capable of producing structured code. Similarly, they're also capable of producing code fairly described as unstructured if used incorrectly. Some would say that an unstructured programming language contains goto statements and, thus, does not require a "call" to a separate module, which then returns when complete, but that definition is unnecessarily restrictive. It's better to say that the mechanisms for enforcing structure vary by language, with some languages demanding structure and other accepting less-structured code.
Types of structured programming
Structured programming can be divided into three categories, including:
Procedural programming. Defines modules as "procedures" or "functions" that are called with a set of parameters to perform a task. A procedural language will begin a process, which is then given data. It is also the most common category and has recently been subdivided into the following:
- Service-oriented programming simply defines reusable modules as "services" with advertised interfaces.
- Microservice programming focuses on creating modules that do not store data internally, and so are scalable and resilient in cloud deployment.
- Functional programming, technically, means that modules are written from functions, and that these functions' outputs are derived only from their inputs. Designed for serverless computing, the definition of functional programming has since expanded to be largely synonymous with microservices.
Object-oriented programming (OOP). Defines a program as a set of objects or resources to which commands are sent. An object-oriented language will define a data resource and send it to process commands. For example, the procedural programmer might say "Print(object)" while the OOP programmer might say "Tell Object to Print".
Model-based programming. The most common example of this is database query languages. In database programming, units of code are associated with steps in database access and update or run when those steps occur. The database and database access structure will determine the structure of the code. Another example of a model-based structure is Reverse Polish Notation (RPN), a math-problem structure that lends itself to efficient solving of complex expressions. Quantum computing, just now emerging, is another example of model-based structured programming; the quantum computer demands a specific model to organize steps, and the language simply provides it.
Components of structured programming
At the high level, structured programs consist of a structural hierarchy starting with the main process and decomposing downward to lower levels as the logic dictates. These lower structures are the modules of the program, and modules may contain both calls to other (lower-level) modules and blocks representing structured condition/action combinations. All of this can be combined into a single module or unit of code, or broken down into multiple modules, resident in libraries.
Modules can be classified as "procedures" or "functions." A procedure is a unit of code that performs a specific task, usually referencing a common data structure available to the program at large. Much of the data operated on by procedures is external. A function is a unit of code that operates on specific inputs and returns a result when called.
Structured programs and modules typically have a header file or section that describes the modules or libraries referenced and the structure of the parameters and module interface. In some programming languages, the interface description is abstracted into a separate file, which is then implemented by one or more other units of code.
Advantages of structured programming
The primary advantages of structured programming are:
- It encourages top-down implementation, which improves both readability and maintainability of code.
- It promotes code reuse, since even internal modules can be extracted and made independent, residents in libraries, described in directories and referenced by many other applications.
- It's widely agreed that development time and code quality are improved through structured programming.
These advantages are normally seen as compelling, even decisive, and nearly all modern software development employs structured programming.
Disadvantages of structured programming
The biggest disadvantage of structured programming is a reduction in execution efficiency, followed by greater memory usage. Both these problems arise from the introduction of calls to a module or process, which then returns to the caller when it's done. System parameters and system resources are saved on a stack (a queue organized as LIFO, or last-in-first-out) and popped when needed. The more program logic is decomposed, meaning the more modules are involved, the greater the overhead associated with the module interface. All structured programming languages are at risk to "over-structuring" and loss of efficiency.
Structured programming can also be applied incorrectly if the type of structure selected isn't right for the task at hand. The best-known example is the solving of math problems. RPL is an efficient way to state and solve a math problem because it eliminates the need to explicitly state execution order and eliminates recursion in code. However, if that problem were to be posed in structured programming procedural or object form, the resulting code would be much less efficient than the RPL version.
- Module 4: Program Constructs
- Continuous Assessment Test ( CAT)
- PRACTICAL ASSIGNMENT
- END OF SESMESTER FINAL EXAMINATION