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

1_Introduction to Programming

Uploaded by

ndp260106
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

1_Introduction to Programming

Uploaded by

ndp260106
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 29

Unit 1 Introduction to programming

Programming:

It is the process of writing instructions, or code, to tell a computer how to perform a task.

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


communicate with computers, programmers also need a language is called Programming
language.

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.

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 as 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 etc….

A high-level language is further divided into two 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.

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 makes 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.

3. Middle-level programming language:

Middle-level programming language lies between the low-level programming language and
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

Algorithm and Flowchart:

Algorithm: A set of rules/instructions that step-by-step define how a work is to be executed in


order to get the expected results.

Flowchart:

A flowchart is a graphical representation of an algorithm.

Flowchart symbols:
Example 1:
Design a flowchart for adding two numbers entered by the user.
Example 2:
Draw a flowchart to calculate the average of two numbers.

Example 3:
Design a flowchart for the multiplication of three numbers entered by the user.
Example 4:
Design a flowchart for calculating the area of a rectangle.

Example 5:
Design a flowchart for calculating the Simple Interest according to the value entered by the user.
Example 6:
Design a flowchart for checking whether the number is positive or negative according to the
number entered by the user.

Example 7:
Design a flowchart for finding the largest among three numbers entered by the user.
Example 8:
Design a flowchart for calculating the profit and loss according to the value entered by the user.

Difference between algorithm and flowchart:

Sr Algorithm Flowchart
No.
1 An algorithm is a step-by-step procedure A flowchart is a diagram created with
to solve a problem. different shapes to show the flow of data.
2 The algorithm is complex to understand. A flowchart is easy to understand.
3 In the algorithm, plain text is used. In the flowchart, symbols/shapes are
used.
4 The algorithm is easy to debug. A flowchart is hard to debug.
5 The algorithm is difficult to construct. A flowchart is simple to construct.
6 The algorithm does not follow any rules. The flowchart follows rules to be
constructed.
7 The algorithm is the pseudo-code for the A flowchart is just a graphical
program. representation of that logic.
C Program Structure:

Documentation Section:

It consists of set of comment lines giving the name of the program, the author and other details.

Preprocessor Section / Link Section:

The C compiler comes with several library files, having ".h" as an extension. A ".h" file (called a
"header file") consists of one or more predefined functions (also called "library functions") to be
used in the C program.

The library functions must be loaded in any C program. The "#include" statement is used to
include a header file. It is a "preprocessor directive".

For example, printf() and scanf() functions are needed to perform console I/O operations. They
are defined in the stdio.h file. Hence, you invariably find #include <stdio.h> statement at the top
of any C program. Other important and frequently used header files
include string.h, math.h, stdlib.h, etc.

There are other preprocessor directives such as #define which is used to define constants and
macros and #ifdef for conditional definitions.
Definition Section:

It defines all symbolic constants.

Global Declaration Section:

This section consists of declaration of variables to be used across all the functions in a program.
Forward declarations of user-defined functions defined later in the program as well as user-
defined data types are also present in the global section.

main() Function:

A C program is a collection of one or more functions. There are two types of functions in a C
program: library functions and user-defined functions.

There must be at least one user-defined function in a C program, whose name must be main().
The main() function serves as the entry point of the program. When the program is run, the
compiler looks for the main() function.

Subroutines in a C Program:

There may be more than one user-defined functions in a C program. Programming best practices
require that the programming logic be broken down to independent and reusable functions in a
structured manner.

Depending on the requirements, a C program may have one or more user-defined functions,
which may be called from the main() function or any other user-defined function as well.

Compiling a C Program:
Data Types in C:
A data type specifies the type of data that a variable can store such as integer, floating, character,
etc.
There are the following data types in C language.

Types Data Types

Basic Data Type int, char, float, double

Derived Data Type array, pointer, structure, union

Enumeration Data Type enum

Void Data Type void

Basic Data Types:

The basic data types are integer-based and floating-point based. C language supports both signed
and unsigned literals.

The memory size of the basic data types may change according to 32 or 64-bit operating system.
Variables in C:

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

A variable is the name of the memory location. It is used to store information. Its value can be
altered and reused several times. It is a way to represent memory location through symbols so
that it can be easily identified.

Variables are key building elements of the C programming language used to store and modify
data in computer programs. A variable is a designated memory region that stores a specified data
type value. Each variable has a unique identifier, its name, and a data type describing the type
of data it may hold.

Syntax:
The syntax for defining a variable in C is as follows:

datatype variable_name;

Here,

o data_type: It represents the type of data the variable can hold.


o variable_name: It is the identifier for the variable, i.e., the name you give to the variable
to access its value later in the program.
o The variable name must follow specific rules, like starting with
a letter or underscore and consisting of letters, digits, and underscores.

Variable Initialization:
int count = 0;

The general rules for naming variables are:

 Names can contain letters, digits and underscores


 Names must begin with a letter or an underscore (_)
 Names are case-sensitive (myVar and myvar are different variables)
 Names cannot contain whitespaces or special characters like !, #, %, etc.
 Reserved words (such as int) cannot be used as names

Types of Variables in C:

There are many types of variables in c:

1. local variable
2. global variable
3. static variable

Local Variable:
A variable that is declared inside the function or block is called a local variable.

It must be declared at the start of the block.

void function1(){
int x=10;//local variable
}

Global Variable:
A variable that is declared outside the function or block is called a global variable. Any function
can change the value of the global variable. It is available to all the functions.

It must be declared at the start of the block.

int value=20;//global variable


void function1(){
int x=10;//local variable
}

Static Variable:
A variable that is declared with the static keyword is called static variable.

It retains its value between multiple function calls.

void function1(){
int x=10;//local variable
static int y=10;//static variable
x=x+1;
y=y+1;
printf("%d,%d",x,y);
}

If you call this function many times, the local variable will print the same value for each
function call, e.g, 11,11,11 and so on. But the static variable will print the incremented
value in each function call, e.g. 11, 12, 13 and so on.

printf() and scanf() in C:

The printf() and scanf() functions are used for input and output in C language. Both functions are
inbuilt library functions, defined in stdio.h (header file).

printf() function:

The printf() function is used for output. It prints the given statement to the console.

The syntax of printf() function is given below:

printf("format string",argument1, argument2, argument3…);

The format string can be %d (integer), %c (character), %s (string), %f (float) etc.

scanf() function:

The scanf() function is used for input. It reads the input data from the console.

scanf("format string", argument1, argument2, argument3…);

Format Specifiers in C:

The format specifier in C is used to tell the compiler about the type of data to be printed or
scanned in input and output operations.
They always start with a % symbol and are used in the formatted string in functions like
printf(), scanf, sprintf(), etc.
The C language provides a number of format specifiers that are associated with the different
data types such as %d for int, %c for char, etc.

List of Format Specifiers in C:


The below table contains the most commonly used format specifiers in C
Datatypes Control String / Format Specifier

signed char/ unsigned char %c

short signed int / signed int %d

short unsigned int / unsigned int %u

long signed int %ld

long unsigned int %lu

float %f

double %lf

long double %Lf

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:

int x = 5;
int y = 2;
int div = 5 / 2;

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

There are two types of conversion in C:

 Implicit Conversion (automatically)


 Explicit Conversion (manually)

1. Implicit Conversion:
 Implicit conversion is done automatically by the compiler when you assign a value of one
type to another.
 The type conversion is only performed to those data types where conversion is possible.
Type conversion is performed by a compiler. In type conversion, the destination data type
can’t be smaller than the source data type. Type conversion is done at compile time and it
is also called widening conversion because the destination data type can’t be smaller than
the source data type.

// Automatic conversion: int to float


float myFloat = 9;

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

2. Explicit Conversion:

Explicit conversion is done manually by placing the type in parentheses () in front of the value.

// Manual conversion: int to float


float sum = (float) 5 / 2;

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

Tokens in C:

A token in C can be defined as the smallest individual element of the C programming language
that is meaningful to the compiler. It is the basic component of a C program.

Types of Tokens in C:
The tokens of C language can be classified into six types based on the functions they are used
to perform. The types of C tokens are as follows:

1. Keywords
2. Identifiers
3. Constants
4. Strings
5. Special Symbols
6. Operators
1. C Token – Keywords:

C language supports many keywords which are given below:

The keywords are pre-defined or reserved words in a programming language. Each keyword is
meant to perform a specific function in a program.

auto double int struct


break else long switch
case enum register typedef
char extern return union
const float short unsigned
continue for signed void
default goto sizeof volatile
do if static while

2. C Token – Identifiers:
Identifiers are used as the general terminology for the naming of variables, functions, and
arrays.
Rules for Naming Identifiers:
Certain rules should be followed while naming c identifiers which are as follows:
 They must begin with a letter or underscore(_).
 They must consist of only letters, digits, or underscore. No other special character is
allowed.
 It should not be a keyword.
 It must not contain white space.
 It should be up to 31 characters long as only the first 31 characters are significant.

3. C Token – Constants:
The constants refer to the variables with fixed values. They are like normal variables but with
the difference that their values cannot be modified in the program once they are defined.
Constants may belong to any of the data types.

Examples of Constants in C
const int a = 20;

This will declare the variable as "constant", which means unchangeable and read-only:

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


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

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

const int minutesPerHour;


minutesPerHour = 60; // error

Correct:
const int minutesPerHour = 60;

4. C Token – Strings:
Strings are nothing but an array of characters ended with a null character (‘\0’). This null
character indicates the end of the string. Strings are always enclosed in double quotes.
Whereas, a character is enclosed in single quotes in C and C++.

Examples of String
char string[20] = {‘c’, ’ ’, ‘p’, ‘r’, ‘o’, ‘g’, ‘r’, ‘a’, ‘m’, ’m’, ‘i’, ‘n’, ‘g’, ‘\0’};
char string[20] = “c programming”;
char string [] = “c programming”;

5. C Token – Special Symbols


{}, [], # ,* , +, =……

7. C Token – Operators
Operators are used to perform operations on variables and values.
Depending on the number of operands that an operator can act upon, operators can be
classified as follows:

 Unary Operators: Those operators that require only a single operand to act upon are
known as unary operators. For Example increment and decrement operators
 Binary Operators: Those operators that require two operands to act upon are called binary
operators. Binary operators can further are classified into:
1. Arithmetic operators
2. Relational Operators
3. Logical Operators
4. Assignment Operators
5. Bitwise Operator
 Ternary Operator: The operator that requires three operands to act upon is called the
ternary operator. Conditional Operator (?) is also called the ternary operator.

Types of Operators in C:

C language provides a wide range of operators that can be classified into 6 types based on their
functionality:
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Bitwise Operators
5. Assignment Operators
6. Other Operators

1. Arithmetic Operations in C:
The arithmetic operators are used to perform arithmetic/mathematical operations on operands.
There are 9 arithmetic operators in C language:

S. No. Symbol Operator Description Syntax

1 + Plus Adds two numeric values. a+b

2 – Minus Subtracts right operand from left operand. a–b

3 * Multiply Multiply two numeric values. a*b

4 / Divide Divide two numeric values. a/b

Returns the remainder after diving the left operand with


5 % Modulus a%b
the right operand.

6 + Unary Plus Used to specify the positive values. +a

Unary
7 – Flips the sign of the value. -a
Minus

8 ++ Increment Increases the value of the operand by 1. a++

9 — Decrement Decreases the value of the operand by 1. a–

2. Relational Operators in C:
The relational operators in C are used for the comparison of the two operands. All these
operators are binary operators that return true or false values as the result of comparison.

These are a total of 6 relational operators in C:

S.
No. Symbol Operator Description Syntax

1 < Less Returns true if the left operand is less than the right a<b
S.
No. Symbol Operator Description Syntax

than operand. Else false

Greater Returns true if the left operand is greater than the right
> a>b
2 than operand. Else false

Less
Returns true if the left operand is less than or equal to the
<= than or a <= b
right operand. Else false
3 equal to

Greater
Returns true if the left operand is greater than or equal to
>= than or a >= b
right operand. Else false
4 equal to

5 == Equal to Returns true if both the operands are equal. a == b

Not
!= Returns true if both the operands are NOT equal. a != b
6 equal to

3. Logical Operator in C:

Logical Operators are used to combine two or more conditions/constraints or to complement


the evaluation of the original condition in consideration. The result of the operation of a logical
operator is a Boolean value either true or false.

S. No. Symbol Operator Description Syntax

1 && Logical AND Returns true if both the operands are true. a && b

Returns true if both or any of the operand


|| Logical OR a || b
2 is true.

3 ! Logical NOT Returns true if the operand is false. !a

4. Bitwise Operators in C:
The Bitwise operators are used to perform bit-level operations on the operands. The operators
are first converted to bit-level and then the calculation is performed on the operands.
Mathematical operations such as addition, subtraction, multiplication, etc. can be performed at
the bit level for faster processing.

There are 6 bitwise operators in C:


S. No. Symbol Operator Description Syntax

Performs bit-by-bit AND operation and


& Bitwise AND a&b
1 returns the result.

Performs bit-by-bit OR operation and


| Bitwise OR a|b
2 returns the result.

Performs bit-by-bit XOR operation and


^ Bitwise XOR a^b
3 returns the result.

Bitwise First Flips all the set and unset bits on the
~ ~a
4 Complement number.

Shifts the number in binary form by one


<< Bitwise Leftshift place in the operation and returns the a << b
5 result.

Shifts the number in binary form by one


Bitwise
>> place in the operation and returns the a >> b
Rightshilft
6 result.

5. Assignment Operators in C:
Assignment operators are used to assign value to a variable. The left side operand of the
assignment operator is a variable and the right side operand of the assignment operator is a
value. The value on the right side must be of the same data type as the variable on the left side
otherwise the compiler will raise an error.
The assignment operators can be combined with some other operators in C to provide multiple
operations using single operator. These operators are called compound operators.
In C, there are 11 assignment operators :

S. No. Symbol Operator Description Syntax

Simple Assign the value of the right operand to the


= a=b
1 Assignment left operand.

Plus and Add the right operand and left operand and
+= a += b
2 assign assign this value to the left operand.

Minus and Subtract the right operand and left operand


-= a -= b
3 assign and assign this value to the left operand.

Multiply and Multiply the right operand and left operand


*= a *= b
4 assign and assign this value to the left operand.
S. No. Symbol Operator Description Syntax

Divide and Divide the left operand with the right operand
/= a /= b
5 assign and assign this value to the left operand.

Assign the remainder in the division of left


Modulus and a %=
%= operand with the right operand to the left
assign b
6 operand.

AND and Performs bitwise AND and assigns this value


&= a &= b
7 assign to the left operand.

OR and Performs bitwise OR and assigns this value to


|= a |= b
8 assign the left operand.

XOR and Performs bitwise XOR and assigns this value


^= a ^= b
9 assign to the left operand.

Rightshift Performs bitwise Rightshift and assign this a >>=


>>=
10 and assign value to the left operand. b

Leftshift and Performs bitwise Leftshift and assign this a <<=


<<=
11 assign value to the left operand. b

6. Other Operators:

Apart from the above operators, there are some other operators available in C used to perform
some specific tasks. Some of them are discussed here:

1. sizeof Operator:

 sizeof is much used in the C programming language.


 It is a compile-time unary operator which can be used to compute the size of its operand.
 The result of sizeof is of the unsigned integral type which is usually denoted by size_t.
 Basically, the sizeof the operator is used to compute the size of the variable or datatype.

Syntax:

sizeof (operand)

2. Comma Operator ( , ):
 The comma operator (represented by the token) is a binary operator that evaluates its first
operand and discards the result, it then evaluates the second operand and returns this value
(and type).
 The comma operator has the lowest precedence of any C operator.
 Comma acts as both operator and separator.
Syntax:

operand1 , operand2

Conditional Operator ( ? : ):
 The conditional operator is the only ternary operator in C++.
 Here, Expression1 is the condition to be evaluated. If the condition(Expression1)
is True then we will execute and return the result of Expression2 otherwise if the
condition(Expression1) is false then we will execute and return the result of Expression3.
 We may replace the use of if..else statements with conditional operators.

Syntax:

operand1 ? operand2 : operand3;

dot (.) and arrow (->) Operators:


 Member operators are used to reference individual members of classes, structures, and
unions.
 The dot operator is applied to the actual object.
 The arrow operator is used with a pointer to an object.

Syntax

structure_variable . member;

and

structure_pointer -> member;

Cast Operator
 Casting operators convert one data type to another. For example, int(2.2000) would return 2.
 A cast is a special operator that forces one data type to be converted into another.
 The most general cast supported by most of the C compilers is as follows − [ (type)
expression ].

Syntax

(new_type) operand;

addressof (&) and Dereference (*) Operators

 Pointer operator & returns the address of a variable. For example &a; will give the actual
address of the variable.
 The pointer operator * is a pointer to a variable. For example *var; will pointer to a variable
var.
Operator Precedence and Associativity in C:

Operator precedence and associativity are rules that decide the order in which parts of an
expression are calculated. Precedence tells us which operators should be evaluated first, while
associativity determines the direction (left to right or right to left) in which operators with the
same precedence are evaluated.

Let’s take a look at an example:

#include <stdio.h>

int main() {
int a = 6, b = 3, c = 4;
int res;

// Precedence and associativity applied here


res = a + b * c / 2;

printf("%d", res);

return 0;
}
Operator Precedence and Associativity Table:

The following tables list the C operator precedence from highest to lowest and the associativity
for each of the operators:

Precedence Operator Description Associativity

() Parentheses (function call)


1 Left-to-Right
[] Array Subscript (Square Brackets)
Precedence Operator Description Associativity

. Dot Operator

-> Structure Pointer Operator

++ , — Postfix increment, decrement

++ / — Prefix increment, decrement

+/– Unary plus, minus

!,~ Logical NOT, Bitwise complement

2 (type) Cast Operator Right-to-Left

* Dereference Operator

& Addressof Operator

sizeof Determine size in bytes

3 *,/,% Multiplication, division, modulus Left-to-Right

4 +/- Addition, subtraction Left-to-Right

5 << , >> Bitwise shift left, Bitwise shift right Left-to-Right

< , <= Relational less than, less than or equal to


6 Left-to-Right
> , >= Relational greater than, greater than or equal to

7 == , != Relational is equal to, is not equal to Left-to-Right

8 & Bitwise AND Left-to-Right

9 ^ Bitwise exclusive OR Left-to-Right

10 | Bitwise inclusive OR Left-to-Right

11 && Logical AND Left-to-Right


Precedence Operator Description Associativity

12 || Logical OR Left-to-Right

13 ?: Ternary conditional Right-to-Left

= Assignment

+= , -= Addition, subtraction assignment

*= , /= Multiplication, division assignment


14 Right-to-Left
%= , &= Modulus, bitwise AND assignment

^= , |= Bitwise exclusive, inclusive OR assignment

<<=, >>= Bitwise shift left, right assignment

15 , comma (expression separator) Left-to-Right

Storage Classes in C:

C Storage Classes are used to describe the features of a variable/function. These features
basically include the scope, visibility, and lifetime which help us to trace the existence of a
particular variable during the runtime of a program.
C language uses 4 storage classes, namely:
1. auto:

This is the default storage class for all the variables declared inside a function or a block.
Hence, the keyword auto is rarely used while writing programs in C language. Auto variables
can be only accessed within the block/function they have been declared and not outside them
(which defines their scope). Of course, these can be accessed within nested blocks within the
parent block/function in which the auto variable was declared.

2. extern:
Extern storage class simply tells us that the variable is defined elsewhere and not within the
same block where it is used. Basically, the value is assigned to it in a different block and this
can be overwritten/changed in a different block as well. So an extern variable is nothing but a
global variable initialized with a legal value where it is declared in order to be used elsewhere.
It can be accessed within any function/block. The main purpose of using extern variables is
that they can be accessed between two different files which are part of a large program.

3. static:
This storage class is used to declare static variables which are popularly used while writing
programs in C language. Static variables have the property of preserving their value even after
they are out of their scope! Hence, static variables preserve the value of their last use in their
scope. So we can say that they are initialized only once and exist till the termination of the
program. Thus, no new memory is allocated because they are not re-declared.
Their scope is local to the function to which they were defined. Global static variables can be
accessed anywhere in the program. By default, they are assigned the value 0 by the compiler.

4. register:
This storage class declares register variables that have the same functionality as that of the auto
variables. The only difference is that the compiler tries to store these variables in the register of
the microprocessor if a free register is available. This makes the use of register variables to be
much faster than that of the variables stored in the memory during the runtime of the program.
If a free register is not available, these are then stored in the memory only. Usually, a few
variables which are to be accessed very frequently in a program are declared with the register
keyword which improves the running time of the program. An important and interesting point
to be noted here is that we cannot obtain the address of a register variable using pointers.

Syntax:
To specify the storage class for a variable, the following syntax is to be followed:

storage_class var_data_type var_name;

Note:

This material is for introductory reading. You may refer text book for more detail part.

Be prepared with Lab work (Programs). It is practical example of each topic from syllabus.

You might also like