0% found this document useful (0 votes)
38 views

Unit 1 Elements of Programming

A programming language allows programmers to communicate with computers. It consists of instructions that perform specific tasks. There are low-level languages like machine language and assembly language that are close to binary and run directly on processors. High-level languages like Python, Java and C++ are easier for humans to read and write but require compilers to translate to machine language. To create an executable program, source code is compiled to assembly code then linked with libraries and loaded into memory by the operating system. Flowcharts provide a graphical representation of algorithms, which are step-by-step methods to solve problems written in plain language.

Uploaded by

Yytr Uuu
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
38 views

Unit 1 Elements of Programming

A programming language allows programmers to communicate with computers. It consists of instructions that perform specific tasks. There are low-level languages like machine language and assembly language that are close to binary and run directly on processors. High-level languages like Python, Java and C++ are easier for humans to read and write but require compilers to translate to machine language. To create an executable program, source code is compiled to assembly code then linked with libraries and loaded into memory by the operating system. Flowcharts provide a graphical representation of algorithms, which are step-by-step methods to solve problems written in plain language.

Uploaded by

Yytr Uuu
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 46

Pre - Programming Techniques

Programming Language

As we know, to communicate with a person, we need a specific language,


similarly to communicate with computers, programmers also need a
language called Programming language.
Before learning the programming language, let's understand what language
is?

What is Language?

Language is a mode of communication that is used to share ideas,


opinions with each other. For example, if we want to teach someone, we
need a language that is understandable by both communicators.

What is a Programming Language?

A programming language is a computer language that is used by


programmers (developers) to communicate with computers. It is a set of
instructions written in any specific language ( C, C++, Java, Python) to
perform a specific task.
A programming language is mainly used to develop desktop applications,
websites, and mobile applications.

Types of programming language

1. Low-level programming language

Low-level language is machine-dependent (0s and 1s) programming


language. The processor runs low- level programs directly without the
need of a compiler or interpreter, so the programs written in low-level
language can be run very fast.
Low-level language is further divided into two parts -
i. Machine Language
Machine language is a type of low-level programming language. It is also
called machine code or object code. Machine language is easier to read
because it is normally displayed in binary or hexadecimal form (base 16)
form. It does not require a translator to convert the programs because
computers directly understand the machine language programs.
The advantage of machine language is that it helps the programmer to
execute the programs faster than the high-level programming language.
ii. Assembly Language
Assembly language (ASM) is also a type of low-level programming
language that is designed for specific processors. It represents the set of
instructions in a symbolic and human-understandable form. It uses an
assembler to convert the assembly language to machine language.
The advantage of assembly language is that it requires less memory and
less execution time to execute a program.

2. High-level programming language

High-level programming language (HLL) is designed for developing


user-friendly software programs and websites. This programming
language requires a compiler or interpreter to translate the program into
machine language (execute the program).
The main advantage of a high-level language is that it is easy to read,
write, and maintain.
High-level programming language includes Python, Java, JavaScript, PHP,
C#, C++, Objective C, Cobol, Perl, Pascal, LISP, FORTRAN, and Swift
programming language.
A high-level language is further divided into three parts -
i. Procedural Oriented programming language
Procedural Oriented Programming (POP) language is derived from
structured programming and based upon the procedure call concept. It
divides a program into small procedures called routines or functions.
Procedural Oriented programming language is used by a software
programmer to create a program that can be accomplished by using a
programming editor like IDE, Adobe Dreamweaver, or Microsoft Visual
Studio.
The advantage of POP language is that it helps programmers to easily
track the program flow and code can be reused in different parts of the
program.

The advantage of POP language is that it helps programmers to easily


track the program flow and code can be reused in different parts of the
program.

Example: C, FORTRAN, Basic, Pascal, etc.

ii. Object-Oriented Programming language


Object-Oriented Programming (OOP) language is based upon the objects.
In this programming language, programs are divided into small parts
called objects. It is used to implement real-world entities like inheritance,
polymorphism, abstraction, etc in the program to make the program
reusable, efficient, and easy-to-use.
The main advantage of object-oriented programming is that OOP is faster
and easier to execute, maintain, modify, as well as debug.

Note: Object-Oriented Programming language follows a bottom-up


approach.

Example: C++, Java, Python, C#, etc.


POP OOP

iii. Natural language


Natural language is a part of human languages such as English, Russian,
German, and Japanese. It is used by machines to understand, manipulate,
and interpret human's language. It is used by developers to perform tasks
such as Translation, Automatic Summarization, Named Entity Recognition
(NER), Relationship Extraction, and Topic Segmentation.
The main advantage of natural language is that it helps users to ask
questions in any subject and directly respond within seconds.
3. Middle-level programming language

Middle-level programming language lies between the low-level


programming language and the high-level programming language. It is
also known as the Intermediate Programming Language and
Pseudo-Language.
A middle-level programming language's advantages are that it supports
the features of high-level programming, it is a user-friendly language, and
closely related to machine language and human language.
Example: C, C++, language

Compiler, Linker, Assembler and Loader

1. Introduction

We'll study the roles of the compiler, linker, assembler, and loader modules
in a typical process of generating an executable.

2. Executable Generation

A computer program is a sequence of statements in a programming


language that instructs the CPU to achieve a particular result.
To execute our program, we convert the source code to machine code. So,
first, we compile the code to an intermediate level and then convert it to
assembly-level code. Then, we link this assembly code with other external
libraries or components it uses. Finally, we load it in memory and execute
the code:
Let’s now dive into each component in the process.

3. Compiler

A compiler is a specialised system tool that translates a program written


in a specific programming language into the assembly language code.
The assembly language code is specific to each machine and is governed
by the CPU of the machine.
The compiler takes a source-code file as input and carries out various
transformations on it to output the corresponding assembly code file.
Internally,
1.The compiler reads the whole source code in a single pass before
starting its work.
2.Then, it creates language tokens from each line of code and verifies the
program conforms to the semantic rules of the programming language’s
grammar.
3.Afterward, it generates assembly code.
4.Most compilers perform multiple iterations before producing an output
file.
4. Assembler

The assembler Enters the Arena after the compiler has played its part. The
assembler translates our assembly code to the machine code and then
stores the result in an object file. This file contains the binary
representation of our program.
Moving further, the assembler gives a memory location to each object
and instruction in our code. The memory location can be physical as well
as virtual. A virtual location is an offset that is relative to the base address
of the first instruction.

5. Linker

Next, we move to the linker module. The linker spawns to action after the
assembler has done its job. The linker combines all external programs
(such as libraries and other shared components) with our program to
create a final executable. At the end of the linking step, we get the
executable for our program.
So, the linker takes all object files as input, resolves all memory references,
and finally merges these object files to make an executable file.
Thus, there are two prime tasks of the linker. The first is to probe and find
referenced modules or methods, or variables in our program. And the
second is to determine and resolve the absolute memory location where
these codes need to be loaded.

6. Loader

The loader is a specialised operating system module that comes last in the
picture. It loads the final executable code into memory.
Afterward, it creates the program and data stack. Then, it initialises various
registers and finally gives control to the CPU so that it can start executing
the code.
Limitations and Features
1.Machine Level Language
2. High Level Language
Tools and Techniques of Problem Analysis
Algorithm Development and Flowchart
Algorithms and flowcharts both are used when creating new programs. An
algorithm is a step-by-step analysis of the process, whereas the flowchart
explains the steps in a graphical manner.

Algorithm

Before solving a problem, one should know what to do, how to do it, and
what types of steps should be taken. So, an algorithm is a step-by-step
method for solving a problem. An algorithm refers to a set of instructions
that define the execution of work to get the expected results.

Generally, the algorithms are written in natural language or in plain English


language. We can represent algorithms via flowcharts, pseudo code, and
others.

Sometimes algorithms are difficult to understand, and it is also difficult to


show looping and branching using an algorithm. Apart from programming
languages or programs, the algorithm can be designed for any problem, as
it is a step-by-step solution of a program.

Advantages of algorithm

○ Algorithms are easy to write.

○ There is a use of human-readable techniques to understand logic.

○ For big problems, algorithms can be written with moderate steps.

Disadvantages of algorithm

○ Algorithms are difficult to debug.

○ It is hard to show branches and loops using an algorithm.

○ Jumping (or goto statements) makes the algorithm hard to trace the
problems.
Now, let's see an example of an algorithm.

Example: Write an algorithm to print the numbers from 1 to 20.

Algorithm:

Step 1: Initialise a variable 'x' as 0,

Step 2: Increment the variable 'x' by 1,

Step 3: Print the variable 'x'

Step 4: If 'x' is less than 20, then go back to step 2. Otherwise, go to the
next step.

Step 5: Exit.

Flowchart In Programming

A flowchart is a diagrammatic representation of an algorithm. A flowchart


can be helpful for both writing programs and explaining the program to
others.

Symbols Used In Flowchart

Symbol Purpose Description

Flow line Indicates the flow of logic by


connecting symbols.

Terminal(Stop Represents the start and the end of a


/Start) flowchart.

Input/Output Used for input and output operation.


Processing Used for arithmetic operations and
data-manipulations.

Decision Used for decision making between two


or more alternatives.

On-page Used to join different flowline


Connector

Off-page Used to connect the flowchart portion


Connector on a different page.

Predefined Represents a group of statements


Process/Func performing one processing task.
tion

Example :
Examples
1)

2)
3)

4)
5)

6)
7)
8)

9)
10)

11)
12)

13)
14)

15)
16)

17)
18)

Difference Between Algorithm and Flowchart

On the basis of Algorithm Flowchart

Basic An algorithm is a The Flowchart is the most

step-by-step method for widely used graphical

solving some problem. An representation of an

algorithm refers to a set of algorithm and procedural

instructions that define the design workflows. It uses

execution of work to get the various symbols to show the

expected results. operations and decisions to

be followed in a program.

Comprehensibility Algorithms are hard to Flowchart is easy to

understand. understand.
Implementation There are no rules employed Predefined rules are

for algorithms. implemented for flowcharts.

Symbols used It uses plain text, which is It uses symbols such as

written in plain English parallelogram, rectangle,

language. diamond, etc.

Debugging Algorithms are easy to Flowcharts are hard to

debug. debug.

Nature Algorithms are the program's Flowcharts are the graphical

pseudocode. representation of logic.

Branching and In algorithms, it is easy to In Flowcharts, branching and

looping show branching and looping. looping are difficult to

represent.

Get Started With C

To start using C, you need two things:

● A text editor, like Notepad, to write C code


● A compiler, like GCC, to translate the C code into a language
that the computer will understand

There are many text editors and compilers to choose from. In


this tutorial, we will use an IDE (see below).
C Install IDE

An IDE (Integrated Development Environment) is used to edit


AND compile the code.

Popular IDE's include Code::Blocks, Eclipse, and Visual Studio.


These are all free, and they can be used to both edit and debug C
code.

Note: Web-based IDE's can work as well, but functionality is


limited.

We will use Code::Blocks in our tutorial, which we believe is a


good place to start.

C Syntax
Syntax

You have already seen the following code a couple of times in the
first chapters. Let's break it down to understand it better:

Example

#include <stdio.h>

int main() {

printf("Hello World!");

return 0;

}
Example explained

Line 1: #include <stdio.h> is a header file library that lets us


work with input and output functions, such as printf()

(used inline 4). Header files add functionality to C programs.

Don't worry if you don't understand how #include <stdio.h>


works. Just think of it as something that (almost) always appears in
your program.

Line 2: A blank line. C ignores white space. But we use it to


make the code more readable.

Line 3: Another thing that always appear in a C program, is


main(). This is called a function. Any code inside its curly
brackets {} will be executed.

Line 4: printf() is a function used to output/print text to the


screen. In our example it will output "Hello World!".

Note that: Every C statement ends with a semicolon ;

Note: The body of int main() could also been written as:
int main(){printf("Hello World!");return 0;}

Remember: The compiler ignores white spaces. However, multiple


lines makes the code more readable.

Line 5: return 0 ends the main() function.

Line 6: Do not forget to add the closing curly bracket } to


actually end the main function.
C Output (Print Text)
Output (Print Text)

To output values or print text in C, you can use the printf()


function:

Example

#include <stdio.h>

int main() {

printf("Hello World!");

return 0;

You can use as many printf() functions as you want. However,


note that it does not insert a new line at the end of the output:

Example

#include <stdio.h>

int main() {

printf("Hello World!");

printf("I am learning C.");

return 0;

}
C New Lines
New Lines

To insert a new line, you can use the \n character:

Example

#include <stdio.h>

int main() {

printf("Hello World!\n");

printf("I am learning C.");

return 0;

You can also output multiple lines with a single printf()


function. However, this could make the code harder to read:

Example

#include <stdio.h>

int main() {

printf("Hello World!\nI am learning C.\nAnd it is


awesome!");

return 0;

Tip: Two \n characters after each other will create a blank line:
Example

#include <stdio.h>

int main() {

printf("Hello World!\n\n");

printf("I am learning C.");

return 0;

What is \n exactly?

The newline character (\n) is called an escape sequence, and it


forces the cursor to change its position to the beginning of the
next line on the screen. This results in a new line.

Examples of other valid escape sequences are:

Escape Sequence Description

\t Creates a horizontal tab

\\ Inserts a backslash character (\)

\" Inserts a double quote character


C Comments
Comments in C

Comments can be used to explain code, and to make it more


readable. It can also be used to prevent execution when testing
alternative code.

Comments can be single-lined or multi-lined.

Single-line Comments

Single-line comments start with two forward slashes (//).

Any text between // and the end of the line is ignored by the
compiler (will not be executed).

This example uses a single-line comment before a line of code:

Example

// This is a comment

printf("Hello World!");

This example uses a single-line comment at the end of a line of


code:

Example

printf("Hello World!"); // This is a comment


C Multi-line Comments

Multi-line comments start with /* and ends with */.

Any text between /* and */ will be ignored by the compiler:

Example

/* The code below will print the words Hello World!

to the screen, and it is amazing */

printf("Hello World!");

Single or multi-line comments?

It is up to you which you want to use. Normally, we use // for


short comments, and /* */ for longer.

Good to know: Before version C99 (released in 1999), you could


only use multi-line comments in C.

What is a Character set?


● Like every other language, ‘C’ also has its own character set. A
program is a set of instructions that, when executed, generate an
output.
● The data that is processed by a program consists of various characters
and symbols. The output generated is also a combination of characters
and symbols.

A character set in ‘C’ is divided into,


● Letters
● Numbers
● Special characters
● White spaces (blank spaces)
A compiler always ignores the use of characters, but it is widely used for
formatting the data. Following is the character set in ‘C’ programming:
1) Letters
● Uppercase characters (A-Z)
● Lowercase characters (a-z)
2) Numbers
● All the digits from 0 to 9
3) White spaces
● Blank space
● New line
● Carriage return
● Horizontal tab
4) Special characters
● Special characters in ‘C’ are shown in the given table,
Special Character Description

, (comma) { (opening curly bracket)

. (period) } (closing curly bracket)

; (semi-colon) [ (left bracket)

: (colon) ] (right bracket)

? (question mark) ( (opening left parenthesis)

‘ (apostrophe) ) (closing right parenthesis)

” (double quotation mark) & (ampersand)

! (exclamation mark) ^ (caret)

|(vertical bar) + (addition)

/ (forward slash) – (subtraction)

\ (backward slash) * (multiplication)


~ (tilde) / (division)

_ (underscore) > (greater than or closing angle bracket)

$ (dollar sign) < (less than or opening angle bracket)

% (percentage sign) # (hash sign)

What is Token in C?
TOKEN is the smallest unit in a ‘C’ program. It is each and every word and
punctuation that you come across in your C program. The compiler breaks
a program into the smallest possible units (Tokens) and proceeds to the
various stages of the compilation. C Token is divided into six different
types, viz, Keywords, Operators, Strings, Constants, Special Characters,
and Identifiers.
Keywords and Identifiers
● In ‘C’ every word can be either a keyword or an identifier.
● Keywords have fixed meanings, and the meaning cannot be changed.
● They act as a building block of a ‘C’ program. There are a total of 32
keywords in ‘C’. Keywords are written in lowercase letters.

Following table represents the keywords in ‘C’-


Keywords in C Programming Language

auto double int struct

break else long switch

case enum register typedef

char extern return union

const short float unsigned

continue for signed void

default goto sizeof volatile

do if static while

● An identifier is nothing but a name assigned to an element in a


program. Example, name of a variable, function, etc.
● Identifiers in C language are the user-defined names consisting of ‘C’
standard character sets.
● As the name says, identifiers are used to identify a particular element
in a program. Each identifier must have a unique name.
● Following rules must be followed for identifiers:
1.The first character must always be an alphabet or an underscore.
2.It should be formed using only letters, numbers, or underscore.
3.A keyword cannot be used as an identifier.
4.It should not contain any whitespace character.
5.The name must be meaningful.

C Data Types
A variable in C must be a specified data type, and you must use a
format specifier inside the printf() function to display it:

Example

// Create variables

int myNum = 5; // Integer (whole number)

float myFloatNum = 5.99; // Floating point number

char myLetter = 'D'; // Character

// Print variables

printf("%d\n", myNum);

printf("%f\n", myFloatNum);

printf("%c\n", myLetter);
Basic Data Types
The data type specifies the size and type of information the
variable will store.

In this tutorial, we will focus on the most basic ones:

Data Size Description


Type

int 2 or 4 bytes Stores whole numbers, without decimals

float 4 bytes Stores fractional numbers, containing one


or more decimals. Sufficient for storing
6-7 decimal digits

double 8 bytes Stores fractional numbers, containing one


or more decimals. Sufficient for storing
15 decimal digits

char 1 byte Stores a single character/letter/number,


or ASCII values

Basic Format Specifiers


There are different format specifiers for each data type. Here are
some of them:

Format Data Type


Specifier

%d or %i int

%f float
%lf double

%c char

%s Used for strings (text), which you will learn more


about in a later chapter

Set Decimal Precision


You have probably already noticed that if you print a floating
point number, the output will show many digits after the decimal
point:

Example

float myFloatNum = 3.5;

double myDoubleNum = 19.99;

printf("%f\n", myFloatNum); // Outputs 3.500000

printf("%lf", myDoubleNum); // Outputs 19.990000

If you want to remove the extra zeros (set decimal precision),


you can use a dot (.) followed by a number that specifies how
many digits that should be shown after the decimal point:

Example

float myFloatNum = 3.5;


printf("%f\n", myFloatNum); // Default will show 6 digits
after the decimal point

printf("%.1f\n", myFloatNum); // Only show 1 digit

printf("%.2f\n", myFloatNum); // Only show 2 digits

printf("%.4f", myFloatNum); // Only show 4 digits

C Constants
If you don't want others (or yourself) to change existing variable
values, you can use the const keyword.

This will declare the variable as "constant", which means


unchangeable and read-only:

Example

const int myNum = 15; // myNum will always be 15

myNum = 10; // error: assignment of read-only variable


'myNum'

You should always declare the variable as constant when you


have values that are unlikely to change:

Example

const int minutesPerHour = 60;

const float PI = 3.14;

Notes On Constants

When you declare a constant variable, it must be assigned with a


value:
Example

Like this:

const int minutesPerHour = 60;

This however, will not work:

const int minutesPerHour;

minutesPerHour = 60; // error

Good Practice
Another thing about constant variables, is that it is considered
good practice to declare them with uppercase. It is not required,
but useful for code readability and common for C programmers:

Example

const int BIRTHYEAR = 1980;

C Variables
Variables are containers for storing data values, like numbers and
characters.

In C, there are different types of variables (defined with different


keywords), for example:

● int - stores integers (whole numbers), without decimals,


such as 123 or -123
● float - stores floating point numbers, with decimals, such as
19.99 or -19.99
● char - stores single characters, such as 'a' or 'B'. Char
values are surrounded by single quotes
Declaring (Creating) Variables

To create a variable, specify the type and assign it a value:

Syntax

type variableName = value;

Where type is one of C types (such as int), and variableName is


the name of the variable (such as x or myName). The equal sign
is used to assign a value to the variable.

So, to create a variable that should store a number, look at the


following example:

Example

Create a variable called myNum of type int and assign the value 15
to it:

int myNum = 15;

You can also declare a variable without assigning the value, and
assign the value later:

Example

// Declare a variable

int myNum;

// Assign a value to the variable

myNum = 15;
Output Variables

You learned from the output chapter that you can output
values/print text with the printf() function:

Example

printf("Hello World!");

Declare Multiple Variables

To declare more than one variable of the same type, use a


comma-separated list:

Example

int x = 5, y = 6, z = 50;

printf("%d", x + y + z);

Assign Same Values to Multiple Variables

You can also assign the same value to multiple variables of the
same type:

Example

int x, y, z;

x = y = z = 50;

printf("%d", x + y + z);
Real-Life Example

Often in our examples, we simplify variable names to match their


data type (myInt or myNum for int types, myChar for char
types etc). This is done to avoid confusion.

However, if you want a real-life example on how variables can be


used, take a look at the following, where we have made a
program that stores different data of a college student:

Example

// Student data

int studentID = 15;

int studentAge = 23;

float studentFee = 75.25;

char studentGrade = 'B';

// Print variables

printf("Student id: %d\n", studentID);

printf("Student age: %d\n", studentAge);

printf("Student fee: %f\n", studentFee);

printf("Student grade: %c", studentGrade);


C Type Conversion
Sometimes, you have to convert the value of one data type to
another type. This is known as type conversion.

For example, if you try to divide two integers, 5 by 2, you would


expect the result to be 2.5. But since we are working with
integers (and not floating-point values), the following example
will just output 2:

Example

int x = 5;

int y = 2;

int sum = 5 / 2;

printf("%d", sum); // Outputs 2

To get the right result, you need to know how type conversion
works.

There are two types of conversion in C:

● Implicit Conversion (automatically)


● Explicit Conversion (manually)

Implicit Conversion

Implicit conversion is done automatically by the compiler when


you assign a value of one type to another.

For example, if you assign an int value to a float type:


Example

// Automatic conversion: int to float

float myFloat = 9;

printf("%f", myFloat); // 9.000000

As you can see, the compiler automatically converts the int value
9 to a float value of 9.000000.

This can be risky, as you might lose control over specific values in
certain situations.

Especially if it was the other way around - the following example


automatically converts the float value 9.99 to an int value of 9:

Example

// Automatic conversion: float to int

int myInt = 9.99;

printf("%d", myInt); // 9

Explicit Conversion

Explicit conversion is done manually by placing the type in


parentheses () in front of the value.

Considering our problem from the example above, we can now


get the right result:
Example

// Manual conversion: int to float

float sum = (float) 5 / 2;

printf("%f", sum); // 2.500000

You can also place the type in front of a variable:

Example

int num1 = 5;

int num2 = 2;

float sum = (float) num1 / num2;

printf("%f", sum); // 2.500000

And since you learned about "decimal precision" in the previous


chapter, you could make the output even cleaner by removing
the extra zeros (if you like):

Example

int num1 = 5;

int num2 = 2;

float sum = (float) num1 / num2;

printf("%.1f", sum); // 2.5

You might also like