0% found this document useful (0 votes)
11 views57 pages

CSF101 Unit-01-1

Uploaded by

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

CSF101 Unit-01-1

Uploaded by

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

CSF101: Programming for Problem

Solving

Session: 2023-24

B. Tech 1st Semester

Unit-1: Introduction to Computer,


Programming & Algorithms
Course Instructor
Prabhjot Kaur
Assistant Professor, School of Computing
What is Computer?
• The word computer comes from the word “compute”, which
means, “to calculate”.
• A computer is an electronic device that can perform arithmetic
operations at high speed, and it can process data, pictures,
sound and graphics.
• It can solve highly complicated problems quickly and
accurately.
Advantages of Computer
• Speed
• It can calculate millions of expression within a fraction of second.
• Storage
• It can store large amount of data using various storage devices.
• Accuracy
• It can perform the computations at very high speed without any mistake.
• Reliability
• The information stored in computer is available after years in same form. It
works 24 hours without any problem as it does not feel tiredness.
• Automation
• Once the task is created in computer, it can be repeatedly performed again by
a single click whenever we want.
• Multitasking
• It can perform more than one tasks/operations simultaneously.
Disadvantages of Computer
• Lake of intelligence
• It cannot think while doing work.
• It does not have natural intelligence.
• It cannot think about properness, correctness or effect of work it is
doing.
• Unable to correct mistake
• It cannot correct mistake by itself.
• So, if we provide wrong or incorrect data then it produces wrong
result or perform wrong calculations.
Block Diagram of Computer
• It is a pictorial representation of a computer which shows how
it works inside.
• It shows how computer works from feeding/inputting the data
to getting the result.
CENTRAL PROCESSING
UNIT
CONTROL UNIT

INPUT SECTION OUTPUT SECTION


ARITHMATIC AND
(Mouse, Keyboard (Monitor, Printer
etc…)
LOGICAL UNIT etc…)

PRIMARY MEMORY
(RAM, ROM etc…)

SECONDARY MEMORY
(Hard disk, Pen drive
etc…)
Block diagram of computer (Input Section)
• The devices used to enter data into computer system are
called input devices.
• It converts human understandable input to computer
controllable data.
• CPU accepts information from user through input devices.
• Examples: Mouse, Keyboard, Touch screen, Joystick etc…
Block diagram of computer (Output Section)
• The devices used to send the information to the outside world
from the computer is called output devices.
• It converts data stored in 1s and 0s in computer to human
understandable information.
• Examples: Monitor, Printer, Plotter, Speakers etc…
Block diagram of computer (Central Processing Unit
(CPU))
• It contains electronics circuit that processes the data based on instructions.
• It also controls the flow of data in the system.
• It is also known as brain of the computer.
• CPU consists of,
• Arithmetic Logic Unit (ALU)
• It performs all arithmetic calculations such as add, subtract, multiply, compare, etc. and takes
logical decision.
• It takes data from memory unit and returns data to memory unit, generally primary memory
(RAM).
• Control Unit (CU)
• It controls all other units in the computer system. It manages all operations such as reads
instruction and data from memory.
• Primary Memory
• It is also known as main memory.
• The processor or the CPU directly stores and retrieves information from it.
• Generally, currently executing programs and data are stored in primary memory.
Block diagram of computer (Secondary Memory)

• Secondary memory is also called Auxiliary memory or External


memory.
• It is Used to store data permanently.
• It can be modified easily.
• It can store large data compared to primary memory. Now
days, it is available in Terabytes.
• Examples: Hard disk, Floppy disk, CD, DVD, Pen drive, etc…
What is Hardware?
• Hardware refers to the physical parts of a computer.
• The term hardware also refers to mechanical device that
makes up computer.
• User can see and touch the hardware components.
• Examples of hardware are CPU, keyboard, mouse, hard disk,
etc.
What is Software?
• A set of instruction in a logical order to perform a
meaningful task is called program and a set of program
is called software.
• It tell the hardware how to perform a task.
• Types of software
• System software
• It is designed to operate the computer hardware efficiently.
• Provides and maintains a platform for running application software.
• Examples: Windows, Linux, Unix etc.
• Application software
• It is designed to help the user to perform general task such as word processing,
web browser etc.
• Examples: Microsoft Word, Excel, PowerPoint etc.
Categories of System Software
• Operating system
• It controls hardware as well as interacts with users and provides
different services to user.
• It is a bridge between computer hardware and user.
• Examples: Windows XP, Linux, UNIX, etc…
• System support software
• It makes working of hardware more efficiently.
• For example, drivers of the I/O devices or routine for socket
programming, etc…
• System development software
• It provides programming development environment to programmers.
• Example: Editor, pre-processor, compiler, interpreter, loader, etc…
Categories of Application Software
• General purpose software
• It is used widely by many people for some common task, like word
processing, web browser, excel, etc…
• It is designed on vast concept so many people can use it.
• Special purpose software
• It is used by limited people for some specific task like accounting
software, tax calculation software, ticket booking software, banking
software etc…
• It is designed as per user’s special requirement.
Compiler, Interpreter and Assembler
• Compiler translates program of higher-level language to
machine language. It converts whole program at a time.
• Interpreter translates program of higher-level language to
machine language. It converts program line by line.
• Assembler translates program of assembly language to
machine language.
Common Number Systems

Syste Base Symbo Used by Used in


m ls Humans? Computers?
Decima 10 0, 1, … Yes No
l
Binary 2 0,9 1 No Yes
Octal 8 0, 1, … No No
Hexa- 7 …
0, 1,
decim 9,
al 16 No No
A, B, …
F
Conversion among Bases
• Possibilities

Decimal Octal

Binary Hexadecimal

• Example
2510 = 110012 = 318 = 1916
Base
Decimal to Binary
• Technique
• Divide by two, keep track of the remainder
• The remainders read from bottom to top give the equivalent binary integer
number.
• Example - 1  Example - 2
12510 = ?2 2 12 1
5 0.687510 integer fraction
2 62 0 = ?2
2 31 1 0.6875 x 21.3750 1 + 0.3750
2 15 1 = x 20.7500
0.3750 0 + 0.7500
2 7 1 = x 21.5000
0.7500 1 + 0.5000
2 3 1 = x 21.0000
0.5000 1 + 0.0000
2 1 1 =
0 0.687510 0.10112
12510 =11111012 =
Binary to Decimal
• Technique
• Multiply each bit by 2n, where n is the “weight” of the bit
• The weight is the position of the bit, starting from 0 on the right. Finally, Add the results.
• Example - 1  Example -
1010112 2 2 = ?10
11.11
= ?10 1 0 1 0 1 1 1 . 1
1 1

1 x 25+0 x 24+1 x 23+0 x 22+1 x 21+1 x 20 1 x 21+1 x 20+1 x 2-1+1 x 2-2


32 + 0 + 8 + 0 + 2 + 1 2 + 1 + 0.5 + 0.25

1010112 =4310 11.112 =3.7510


Decimal to Octal
• Technique
• Divide by eight, keep track of the remainder
• The remainders read from bottom to top give the equivalent octal integer number.
• Example - 1  Example -
12510 = ?8 20.6875
10

8 12 5 = ?8 integer fraction
8 5
15 7
0.6875 x 85.5000 5 + 0.5000
8 1 1
= x 84.0000
0.5000 4 + 0.0000
0
=

12510 =1758 0.687510 0.548


=
Octal to Decimal
• Technique
• Multiply each digit by 8n, where n is the “weight” of the digit
• The weight is the position of the digit, starting from 0 on the right. Finally, Add the results.
• Example - 1  Example -
7248 = ?10 2
43.25 =?8 10
7 2 4 4 3 . 2
5

7x8 2 + 2 x 81 + 4 x 80 4 x 81+ 3 x 80 +2 x 8-1+ 5 x 8-2


448 + 16 + 4 32 + 3 + 0.25 + 0.078
1

7248 =46810 43.258 =


35.328110
Decimal to Hexa-Decimal
• Technique
• Divide by sixteen, keep track of the remainder
• The remainders read from bottom to top give the equivalent hexadecimal integer number.
• Example - 1  Example -
123410 = ?16 2
0.03125 10 =

16 1234 2 ?16 integer fraction


16 77 13=
0.03125 x 0.5000 0 + 0.5000
16 4 4D
16 =x 168.0000
0.5000 8 + 0.0000
0
=

123410 4D216 0.03125100.0816


= =
Hexa-Decimal to Decimal
• Technique
• Multiply each digit by 16n, where n is the “weight” of the digit
• The weight is the position of the digit, starting from 0 on the right. Finally, Add the
results.
 Example -
• Example - 1
ABC16 = ?10 2
43.2516 = ?
A B C 4 3 . 2
10
5

Ax + Bx + Cx 4x + 3x + 2x + 5x
162 + 161 16 0
+ 12 x 161
160
16-1
16-2
10 x 11 x 64 + 3 + 0.125+ 0.019
162
2560 + 16
176
1 16
+ 12
0
5

ABC16 =274810 43.2516 =


67.144510
Types of Computer Languages
• Machine level language OR Low-level language
• It is language of 0’s and 1’s.
• Computer directly understand this language.
• Assembly language
• It uses short descriptive words (MNEMONIC) to represent each of the
machine language instructions.
• It requires a translator knows as assembler to convert assembly language
into machine language so that it can be understood by the computer.
• Examples: 8085 Instruction set
• Higher level language
• It is a machine independent language.
• We can write programs in English like manner and therefore easier to learn
and use.
• Examples: C, C++, JAVA etc…
Types of Computer Languages
Flowchart Algorithm
Flowchart is a pictorial or graphical Algorithm is a finite sequence of well-
representation of a program. defined steps for solving a problem.
It is written in the natural language like
It is drawn using various symbols.
Easy to understand. English.
Difficult to understand.
Easy to show branching and looping. Difficult to show branching and looping.
Flowchart for big problem is impractical. Algorithm can be written for any problem.
Symbols used in Flowchart

Start / Stop Input / Output

Process Decision Making

Subroutine Arrows
Number is positive or negative
Step 1: Read no.
Start
Step 2: If no is greater than equal
zero, go to step 4.
Read no Step 3: Print no is a negative
number, go to step 5.
True False Step 4: Print no is a positive
Is no >= 0 number.
Step 5: Stop.
Print no is Print no is
Positive Negative

Stop
Number is odd or even
Step 1: Read no.
Start
Step 2: If no mod 2 = 0, go to
step 4.
Read no Step 3: Print no is a odd, go to
step 5.
True Is no % 2 = False Step 4: Print no is a even.
0 Step 5: Stop.

Print no is Print no is
Even Odd

Stop
Largest number from 2 numbers
Step 1: Read a, b.
Start
Step 2: If a>b, go to step 4.
Step 3: Print b is largest number,
Read a, b go to step 5.
Step 4: Print a is largest number.
True False Step 5: Stop.
Is a>b

Print a is Print b is
largest largest

Stop
Largest number from 3 numbers (Flowchart)
Start

Read a, b, c

True False
Is a>b

True False True False


Is a>c Is b>c

Print a is Print c is Print b is Print c is


largest largest largest largest

Stop
Largest number from 3 numbers (Algorithm)
Step 1: Read a, b, c.
Step 2: If a>b, go to step 5.
Step 3: If b>c, go to step 8.
Step 4: Print c is largest number, go to step 9.
Step 5: If a>c, go to step 7.
Step 6: Print c is largest number, go to step 9.
Step 7: Print a is largest number, go to step 9.
Step 8: Print b is largest number.
Step 9: Stop.
Print 1 to 10
Step 1: Initialize a to 1.
Start
Step 2: Print a.
Step 3: Repeat step 2 until
a=1 a<=10.
Step 3.1: a=a+1.
a=a+1 Print a Step 4: Stop.

True False
Is a<=10

Stop
Pseudo-code
• A program planning tool where program logic is written in
an ordinary natural language using a structure that
resembles computer instructions.
• “Pseudo” means imitation or false and “ Code” refers to the
instructions written in a programming language. Hence,
pseudocode is an imitation of actual computer instructions.
• Because it emphasizes the design of the program,
pseudocode is also called Program Design Language (PDL).
Basic Logic (Control) Structures
• Any program logic can be expressed by using only following
three simple logic structures:

1. Sequence logic,
2. Selection logic, and
3. Iteration (or looping) logic

• Programs structured by using only these three logic


structures are called structured programs, and the
technique of writing such programs is known as structured
programming.
• Sequence Logic: It is used for performing instructions one
after another in sequence.

• Selection Logic: Also known as decision logic, it is used


for making decisions. Two popularly used selection logic
structures are
1. IF…THEN
2. IF…THEN…ELSE
Iteration(or Looping) Logic: Used to produce loops in
program logic when one or more instructions may be
executed several times depending on some conditions. Two
popularly used iteration logic structures are
1.DO…WHILE
2.REPEAT…UNTIL
Sample Pseudo-code
Suppose the input data of each student for the examination of Example 3 also contains
information regarding the gender of the candidate in the field named Gender code having
values M (for male) or F (for female).We want to make a list of only those female students
who have passed in second division (obtained 45% or more but less than 60% marks).In
the end, we also want to print out the total number of such students. Assuming that the
input data of all the students is terminated by a trailer record, which has a sentinel value
of Z for Gender code, Write a pseudo code for 72 this.
Introduction to C Programming Language
• C is a programming language developed at AT & T’s Bell Laboratories of USA in
1972. It was designed and written by a man named Dennis Ritchie.
• It incorporates properties of High-Level language as well as low level language.
• It is a structured programming language.
• C is a Case-Sensitive language. For example: int and INT are two different
words.
• C Character Sets: A character denotes any alphabet, digit or special symbol
used to represent information. Following Figure shows the valid alphabets,
numbers and special symbols allowed in C.
Tokens
• The smallest individual unit of a program is known as token.

• C has the following tokens:

• Identifiers: Identifiers are names that are given to various user defined program elements,
such as variable, function and arrays.
• Keywords: C reserves a set of 32 words for its own use. These words are called keywords (or
reserved words), and each of these keywords has a special meaning within the C language.
• Constants: Constants refer to fixed values that do not change during execution of program.
• Strings: A string is a sequence of characters terminated with a null character \0.
• Special Symbols: Symbols such as #, &, =, * are used in C for some specific function are
called as special symbols.
• Operators: An operator is a symbol that tells the compiler to perform certain mathematical
or logical operation.
Identifiers
• Identifier refers to name given to entities such as variables, functions,
structures etc. Identifiers must be unique. They are created to give a
unique name to an entity to identify it during the execution of the
program.
• Rules for naming identifiers:
 A valid identifier can have letters (both uppercase and lowercase
letters), digits and underscores.
 The first letter of an identifier should be either a letter or an
underscore.
 You cannot use keywords as identifiers.
 There is no rule on how long an identifier can be. However, you may
run into problems in some compilers if the identifier is longer than
31 characters.
• Examples: abc, _abc, abc123
Keywords
• Keywords are predefined, reserved words used in
programming that have special meanings to the compiler.
Keywords are part of the syntax, and they cannot be used as
an identifier. C having 32predefined keywords.
Variables and Constants
𝑥, 𝑦, 𝑎, 𝑐𝑜𝑢𝑛𝑡, 𝑒𝑡𝑐. can be variable names.
• Variable is a symbolic name given to some value which can be changed.

𝑥=5 𝑎=𝑏+𝑐


• A variable is a name given to memory location. Basically, a variable is
used to store some form of data. Different types of variables require
different amounts of memory and have some specific set of operations
which can be applied on them.
• A variable must be declared before use in the program.
• Syntax for declaring a variable in C: datatype variable_name;
datatype tells the type of variable and variable_name is a valid identifier
name.
• Example: int x; In this example x is a variable which is going to store
integer data type.

5, −7.5, 1452, 0, 3.14, 𝑒𝑡𝑐.


• Constant is a fixed value which cannot be changed.

Data Types
• Data types are defined as the data storage format that a
variable can store a data.
• It determines the type and size of data associated with
variables.
Data types in C

Primary Data type


Secondary Data type
(int, float, char)

User definer Data


Derived Data type type
(array, pointer) (structure, union,
enum)
Primary Data Type
• Primary data types are built in data types which are directly
supported by machine.
• They are also known as fundamental data types.
• int:
• int datatype can store integer number which is whole number without fraction part
such as 10, 105 etc.
• C language has 3 classes of integer storage namely short int, int and long int. All
these data types have signed and unsigned forms.
• Example: int a=10;
• float:
• float data type can store floating point number which represents a real number with
decimal point and fractional part such as 10.50, 155.25 etc.
• When the accuracy of the floating-point number is insufficient, we can use the double
to define the number. The double is same as float but with longer precision.
• To extend the precision further we can use long double which consumes 80 bits of
memory space.
• Example: float a=10.50;
Primary Data Type (cont…)
• char:
• Char data type can store single character of alphabet or digit or special symbol such as ‘a’, ‘5’
etc.
• Each character is assigned some integer value which is known as ASCII values.
• Example: char a=‘a’;
• void:
• The void type has no value therefore we cannot declare it as variable as we did in case of int
or float or char.
• The void data type is used to indicate that function is not returning anything.
Secondary Data Type
• Secondary data types are not directly supported by the machine.
• It is combination of primary data types to handle real life data in more
convenient way.
• It can be further divided in two categories,
• Derived data types: Derived data type is extension of primary data type. It is
built-in system and its structure cannot be changed. Examples: Array and
Pointer.
• Array: An array is a fixed-size sequenced collection of elements of the same data type.
• Pointer: Pointer is a special variable which contains memory address of another variable.
• User defined data types: User defined data type can be created by programmer
using combination of primary data type and/or derived data type. Examples:
Structure, Union, Enum.
• Structure: Structure is a collection of logically related data items of different data types
grouped together under a single name.
• Union: Union is like a structure, except that each element shares the common memory.
• Enum: Enum is used to assign names to integral constants, the names make a program easy
to read and maintain.
Structure of C Program
Following rules that are applicable to all C programs:

• Each instruction in a C program is written as a separate statement.


Therefore, a complete C program would comprise of a series of
statements.
• The statements in a program must appear in the same order in which
we wish them to be executed; unless of course the logic of the problem
demands a deliberate ‘jump’ or transfer of control to a statement,
which is out of sequence.
• Blank spaces may be inserted between two words to improve the
readability of the statement. However, no blank spaces are allowed
within a variable, constant or keyword.
• All statements should be entered in small case letters.
• C has no specific rules for the position at which a statement is to be
written. That’s why it is often called a free-form language.
• Every C statement must end with a ;. Thus ; acts as a statement
Printing Hello World on Screen
Compilation and Execution
• Once you have written the program you need to type it and instruct
the machine to execute it. To type your C program, you need another
program called Editor.
• There are several such IDEs available in the market targeted towards
different operating systems. For example, Turbo C, Turbo C++ and
Microsoft C are some of the popular compilers that work under
MSDOS; Visual C++ and Borland C++ are the compilers that work
under Windows, whereas gcc compiler works under Linux.
• Assuming that you are using a Turbo C or Turbo C++ compiler. Here
are the steps that you need to follow to compile and execute your first
C program.
 Start the compiler at C> prompt. The compiler (TC.EXE is usually
present in C:\TC\BIN directory).
 Select New from the File menu.
 Type the program.
 Save the program using F2 under a proper name (say Program1.c).
Comments
• A comment is an explanation or description of the source code of the
program
• It helps a programmer to explain logic of the code and improves program
readability.
• At run-time, a comment is ignored by the compiler.
• There are two types of comments in C:
• Single line comment
• Represented as // double forward slash
• It is used to denote a single line comment only.
• Example: // Single line comment
• Multi-line comment
• Represented as /* any text */ start with forward slash and asterisk (/*) and end with asterisk and
forward slash (*/).
 It is used to denote single as well as multi-line comment.
 Example: /* multi line comment line -1
• multi line comment line -2 */
Header files
• A header file is a file with extension .h which contains the set
of predefined standard library functions.
• The “#include” preprocessing directive is used to include the
header files with extension in the program.

Header Description
file
stdio.h Input/Output functions (printf and scanf)
conio.h Console Input/Output functions (getch and clrscr)
math.h Mathematics functions (pow, exp, sqrt etc…)
string.h String functions (strlen, strcmp, strcat etc…)
Format Specifiers
• Format specifiers in C are used to take inputs
and print the output of a type.
• The symbol we use in every format specifier is %.
• Format specifiers tell the compiler about the type
of data that must be given or input and the type
of data that must be printed on the screen.
• Example:
#include <stdio.h>
int main()
{
int a=50;
printf("The integer value of a is %d \n",a);
return 0;
}
Escape Sequence in C
• The escape sequence in C is the characters or the sequence of characters that can be used inside the string
literal.
• The purpose of the escape sequence is to represent the characters that cannot be used normally using the
keyboard.
• Some escape sequence characters are the part of ASCII char set but some are not.
• Different escape sequences represent different characters, but the output is dependent on the compiler you are
using.

Escape Example:
Name Description
Sequence #include <stdio.h>
int main()
It moves the cursor {
\n New Line to the start of the
next line.
int a=50;
printf("The integer value of a is %d \n",a);
It inserts some return 0;
whitespace to the left }
\t Horizontal Tab of the cursor and
moves the cursor
accordingly.

Use to insert
\\ Backlash
backslash character.
Object and Executable Code
• It is important to understand that compilation and execution
are two distinct processes.
• During compilation, the computer runs the compiler
program.
• During execution, the object program is loaded into the
computer’s memory unit, replacing the compiler program.
• The computer then directly executes the object program,
doing whatever the program instructs it to do. See the
figure.
Types of Programming Errors
Programming errors are broadly classified into four categories:
1. Syntax error/Compile-time error: Errors that occur when you violate the rules of writing Programming
syntax are known as syntax errors. This compiler error indicates something that must be fixed before the code can
be compiled. All these errors are detected by compiler and thus are known as compile time errors.

The most commonly occurring syntax errors in C #include <stdio.h>


language are: int main()
• Missing semi-colon (;) {
• Missing parenthesis ({}) int var = 10
• Assigning value to a variable without declaring it return 0;
}

2. Run-time error: Errors which occur


during program execution(run-time) after successful compilation are called run-time errors. One of the most
common runtime error is division by zero also known as Division error. These types of error are hard to find as the
compiler doesn’t point to the line at which the error occurs. #include<stdio.h>
#include<stdio.h> void main()
void main() {
{ int var = 2147483649;
int var; printf("%d", var);
var = 20 / 0; }
printf("%d", var);
Types of Programming Errors
3. Logical Errors: On compilation and execution of a program, desired output is not obtained when certain input
values are given. These types of errors which provide incorrect output but appears to be error free are called
logical errors. Example: #include <stdio.h>
void main()
{
float a = 10;
float b = 5;
if (b = 0)
printf("Division by zero is not possible");
else
printf("The output is: %f", a/b);
}// In the above example, we wanted to check whether the variable b was equal to zero. But instead of
using the equal to comparison operator (==), we use the assignment operator (=). Because of this, the if
statement became false and the value of b became 0. Finally, the else clause got executed.

4. Semantic Errors: This error occurs when the statements written in the program are not meaningful to the
compiler.
#include <stdio.h>
void main()
{
int a, b, c;
a * b = c;
}//When we have an expression on the left-hand side of an assignment operator (=), the program generates a
semantic error. Even though the code is syntactically correct, the compiler does not understand the code.
What about this?

#include <stdio.h>
void Main()
{
int var = 10;
printf("%d", var);
}

You might also like