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

Problem Solving Using C

1. The document discusses an introduction to programming concepts including components of a computer system, algorithms, and the process of creating and running programs in C. 2. It defines key terms like algorithms, flowcharts, pseudocode, compilers, linkers and describes the process of writing, compiling, linking and executing a C program. 3. The document also explains concepts like data types, variables, memory locations, I/O functions and errors that can occur during compilation.

Uploaded by

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

Problem Solving Using C

1. The document discusses an introduction to programming concepts including components of a computer system, algorithms, and the process of creating and running programs in C. 2. It defines key terms like algorithms, flowcharts, pseudocode, compilers, linkers and describes the process of writing, compiling, linking and executing a C program. 3. The document also explains concepts like data types, variables, memory locations, I/O functions and errors that can occur during compilation.

Uploaded by

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

Problem Solving using C

Text Books:

1.Byron Gottfried, Schaum's Outline of Programming with C, McGraw-


Hill.
2.E. Balaguruswamy, Programming in ANSI C, Tata McGraw-Hill.

Reference Books:
 
3.Brian W. Kernighan and Dennis M. Ritchie, The C Programming
Language, Prentice Hall of India.
UNIT-1
Topics to be covered in
UNIT-1
Introduction to Programming:

Introduction to components of a computer system (disks, memory,


processor, where a program is stored and executed, operating system,
compilers etc.)

Idea of Algorithm:

Steps to solve logical and numerical problems.

Representation of Algorithm: Flowchart / Pseudo code with examples.

From algorithms to programs:


Source code, variables (with data types) variables and memory locations,
Syntax and Logical Errors in compilation, object and executable code.
What is a Computer?

A computer is an electronic
device or programmable
machine. It allows the user to
store all sorts of information
and then process that
information or carry out
actions with the information
such as calculating numbers
or organizing words.
Computer Systems
 A computer system consists of hardware and software.
 Hardware refers to any physical, electrical components of the
computer.
 For example keyboard, mouse, cabinet of computer is considered as
hardware.
 Software refers to a program or set of instructions that is written to
achieve a specified task.
Components of a Computer System:
 Input Devices
 Central Processing Unit (CPU)
 Arithmetic and Logic Unit (ALU)
 Control Unit
 Storage Devices
 Output Devices
Input Devices:
 The input device is used to enter data into a computer.
 The devices like keyboard, mouse and scanner are commonly
used input devices.
Central Processing Unit:
 It is the main part of the computer.
 It’s main function is to execute programs stored in the main
memory.
 It consists of three functional units: ALU, CU and MU.
Arithmetic and Logic Unit (ALU):
 It performs arithmetic and logical operations on the data.
Control Unit:
 It controls the overall activities of the components of the
computer.
Memory Unit:
 It is used to hold the waiting data to be processed.
Memory: There are two types of memories.
• Volatile Memory
• Non-volatile Memory

Volatile Memory: It means that the information present in these types


of memory devices is deleted as soon as the power is switched off.

Non-volatile Memory: It means that the information present in these


types of memory devices is not lost as soon as the power is switched off.

Types of Storage Devices:


• Primary Storage or Main Memory.
• Auxiliary Storage or Secondary Storage
• Cache memory
• Registers
Types of Storage Devices:
Primary Storage/Main Memory:
 This is the place where the data is stored temporarily during
processing.
 Primary memory (main memory) is available in two forms:
RAM and ROM.

RAM (Random Access Memory):


 It is a temporary storage medium in a computer.
 The data which is to be processed by the computer is transferred from a
storage device to RAM during data processing.
 RAM is a volatile memory.

ROM (Read Only Memory) :


 It is a permanent storage medium which stores start up programs.
 These programs are loaded when computer is switched on.
 ROM is non-volatile memory.
Auxiliary Storage/Secondary Memory:
 It is the place where data to be stored permanently. Ex: Disk,tapes.

Cache Memory:
 It is a memory placed between CPU and main memory.
 It is faster compared to the primary memory.
 Parts of the program or data that need to be accessed repeatedly are
stored in cache memory.
 It is a volatile memory.

Registers:
 Registers are small memory units internally available within the
processor.
 It is a volatile memory.

Output Devices:
 It is used to display or print the result.
 Monitor, printer and plotter are commonly used output devices.
Operating System:

An Operating System (OS) is an interface between a computer


user and computer hardware.

An operating system is a software which performs the following


tasks:
 File Management
 Memory Management
 Process Management
 Device Management
 Controlling peripheral devices such as disk drives and
printers.
Creating and Running Programs
Creating and running programs takes place in 4 steps.
1. Writing and Editing the program.
2. Compiling.
3. Linking the program with the required library functions.
4. Executing the program.
Building a C Program
1. Writing and Editing the program
 Software used to write programs is known as a text editor, where
you can type, edit and store the data.

 You can write a C program in text editor and save that file on to the
disk with “.c” extension. This file is called source file.
2. Compiling Program
 Compiler is used to convert High Level Language instructions
into the Machine Language instructions.
 It could complete its task in two steps.
i) Preprocessor
ii) Translator
Preprocessor:
 It reads the source file and checks for special commands
known as preprocessor commands ( instructions which starts
with # symbols ).
 The result of preprocessor is called as translation unit.
 Preprocessor processes the source file before compilation only.

Translator:
 It is a program which reads the translation unit and converts
the program into machine language and gives the object
module.
 This module is not yet ready to run because it does not have
the required C and other functions included.
3. Linking a program with required library
functions
 C program is made up of different functions in which some
functions can be written by the programmer, other functions like
input/output functions and mathematical library functions, that
exist elsewhere and must be attached to our program.

 The linker assembles all of these functions and produces the


executable file which is ready to run on the computer.

4. Executing the program.


 Once a program has been linked, it is ready for execution.
 Now, you can execute the program by using the run command.
 Loader is a program which is used to load the program from the
disk to main memory.
Writing and Running Programs

1. Write a program (source code) using vi editor and save it with .c


extension. Ex: $vi sample.c

2. Run the compiler to convert a program into to “binary” code.


Ex: $cc sample.c

3. Compiler gives errors and warnings if any, then edit the source
file, fix it, and re-compile.

4. Run it and see the output. Ex: $ ./a.out


Algorithm
Algorithm: It is an ordered sequence of unambiguous and well-
defined instructions that performs some task and halts in finite time 

Let's examine the four parts of this definition more closely.


1. Ordered Sequence: You can number the step.
2. Unambiguous and well defined instructions: Each instruction should
be clear, understand without difficulty.
3. Performs some task
4. Halts in finite time: Algorithm must terminate at some point.
Properties of an Algorithm:-

 Finiteness: An algorithm must terminate in a finite number of steps.

 Definiteness: Each step of an algorithm must be precisely and


unambiguously stated.

 Effectiveness: Each step must be effective, and can be performed


exactly in a finite amount of time.

 Generality: The algorithm must be complete in itself.

 Input/Output: Each algorithm must take zero, one or more inputs


and produces one or more output.
Three Categories of Algorithmic Operations
An algorithm must have the ability to alter the order of its instructions.
An instruction that alters the order of an algorithm is called a control
structure.

Three categories of an algorithmic operations:


1. Sequential operations: Instructions are executed in order

2. Conditional/Selection  ("question asking") Operations: A control


structure that asks a true/false question and then selects the next
instruction based on the answer.

3. Iterative Operations (loops): A control structure that repeats the


execution of a block of instructions.
Pseudo-code and Algorithm Construction
Assignment:
        variable = "expression"
Input/Output:
Get/enter/read "variable", "variable", ...
Display/print "variable", "variable", ...
Conditional:
1.  if  "condition"
1.1    (subordinate) statement 1 
1.2     etc ...
2.  else
2.1    (subordinate) statement 2
2.2    etc ...
Iterative:
3.  while "condition" 
3.1    (subordinate) statement 1
3.2    etc ...
Pseudo Code
Definition: English-like statements that follow a loosely defined syntax
and are used to convey the design of an algorithm.

Pseudocode is sometimes used as a detailed step in the process of


developing a program.

Example1: To determine whether a student is passed or not


Pseudo Code: Algorithm:
1. If student's grade is greater than or equal to 60 Begin
1.1 Print "passed" 1. If grade >= 60
2. else 1.1 Print
2.1 Print "failed" "passed"
2. else
2.1 Print
"failed”
Flowchart
 Pictorial representation of an algorithm is called flowchart.
or
 A diagram that uses graphic symbols to depict the nature and
flow of the steps in a process.
SYMBOLS USED WITH FLOWCHARTS
Flowchart to find the addition of two numbers

Start

Accept a, b

c=a+b

Display C

End
Algorithm to find whether a given year is a leap year or not.

Algorithm:

BEGIN
Step 1: Accept the YEAR
Step 2: if (YEAR %4 == 0) then
Display “Year is a leap year”
else
Display “Year is not a leap year”
end if
END
Flowchart to find whether a given year is a leap year or not

Start

Accept year

false
if(year%4 = = 0)

true
Display non leap year

Display leap year

End
Exercise:
1. Sum of the digits of a number.
2. Nature of quadratic equations.
3. Income tax problem.
4. Standard deviation.
Identifiers
 Identifiers are names given to various programming elements such
as variables, constants, and functions.
 It should start with an alphabet or underscore, followed by the
combinations of alphabets and digits.
 No special character is allowed except underscore.
 An Identifier can be of arbitrarily long. Some implementation of C
recognizes only the first 8 characters and some other recognize first
32 Characters.

The following are the rules for writing identifiers in C:


 First character must be alphabetic character or underscore.
 Must consist only of alphabetic characters, digits, or underscore.
 Should not contain any special character, or white spaces.
 Should not be C keywords.
 Case matters (that is, upper and lowercase letters). Thus, the names
count and Count refer to two different identifiers.
Identifier Legality

Percent Legal

y2x5__fg7h Legal

annual profit Illegal: Contains White space

_1990_tax Legal but not advised

savings#account Illegal: Contains the illegal character #

double Illegal: It is s a C keyword

9winter Illegal: First character is a digit

Examples of legal and illegal C identifiers


Variables
 Variable is a valid identifier which is used to store the value in the
memory location, that value varies during the program execution.
Types of variables:
Global Variables
Local Variables
 Global Variable: The variables which are declared at the starting
of the program are called as global variable. They are visible to
all the parts of the program.

 Local Variable: The variables which are declared in a function


are called local variables to that function. These variables visible
only within the function.
Variables (contd…)
Variable Declaration & Definition:
 Each variable in your program must be declared and defined.
 In C, a declaration is used to name an object, such as a variable.
 Definitions are used to create the object.
 When you create variables, the declaration gives them a symbolic
name and the definition reserves memory for them.
 A variable’s type can be any of the data types, such as character,
integer or real except void.
 C allows multiple variables of the same type to be defined in one
statement.
Example: int a, b;
Variable Initialization:
 You can initialize a variable at the same time that you declare it by
including an initializer.
 To initialize a variable when it is defined, the identifier is followed by
the assignment operator and then the initializer.
Example: int count = 0;
Variables (contd…)
Variable declaration and definition:
Example: int a;
a Variable name

23456 Garbage value

1000 Address of the variable

Variable initialization:
datatype identifier = initial value;
Examples:
int a=10;
float b=2.1;
float pi=3.14;
char ch=‘A’;
Variables (contd…)
 When you want to process some information, you can save the values
temporarily in variables.

#include<stdio.h>
main()
{
int a=10,b=20,c;
c=a+b;
printf(“sum of a and b=%d\n”,c);
return 0;
}

 Note : Variables must be declared before they are used, usually at


the beginning of the function.
Variables (contd…)
There are some restrictions on the variable names (same as
identifiers):

 First character must be alphabetic character or underscore.

 Must consist only of alphabetic characters, digits, or underscore.

 Should not contain any special character, or white spaces.

 Should not be C keywords.

 Case matters (that is, upper and lowercase letters). Thus, the names
count and Count refer to two different identifiers.
Data types in C
 Data types are used to indicate the type of value represented or
stored in a variable, the number of bytes to be reserved in memory,
the range of values that can be represented in memory, and the
type of operation that can be performed on a particular data value.

 ANSI C supports 3 categories of data types:  


 Built-in data types
 Derived data types
 User Defined data types
Data types in C (contd…)
Built-in data types
Integer data type :

 An integer number (also called whole number) has no fractional part


or decimal point.

 The keyword int is used to specify an integer variable.

 It occupies 2 bytes (16 bits) or 4 bytes (32 bits), depending on the


machine architecture.

 16-bit integer can have values in the range of     -32768 to 32767


 One bit is used for sign.

void data type:


 Defines an empty data type which can then be associated with some
data types. It is useful with pointers.
Note

sizeof (short) ≤ sizeof (int) ≤ sizeof (long) ≤ sizeof (long long)


Integer Types
Built-in data types (contd…)

Character Data Type :

 The shortest data type is character.

 The keyword char is used to declare a variable of a character type.

 It is stored in 1 byte in memory.

 Corresponding integer values for all characters are defined in ASCII


(American Standard Code for Information Interchange).

 Example: character constant ‘a’ has an int value 97,


‘b’ has 98, ‘A’ has 65 etc.

 Character can have values in the range of -128 to 127.


Character Types
Built-in data types (contd…)
The floating point data type:
 The keyword float is used to declare a variable of the type float.
 The float type variable is usually stored in 32 bits, with 6 digits of
precision.
 A float variable can have values in the range of 3.4E-38 to 3.4 E+38.

The double data type:


 A floating point number can also be represented by the double data
type.
 The data type double is stored on most machines in 64 bits which is
about 15 decimal places of accuracy.
 To declare a variable of the type double, use the keyword double.
 A double variable can have values in the range of 1.7E-308 to
+1.7E+308.
Note
sizeof (float) ≤ sizeof (double) ≤ sizeof (long double)

Floating-point Types
Type Modifiers:
 The basic data types may have various modifiers (or qualifiers)
preceding them, except type ‘void’.

 A modifier is used to alter the meaning of the base data type to fit
the needs of various situations more precisely.

 The modifiers signed, unsigned, long, short may be applied to


integer base types.

 The modifiers unsigned and signed may be applied to characters.

 The modifier long may also be applied to double.

 The difference between signed and unsigned integers is in the way


high-order bit (sign bit) of the integer is interpreted.

 If sign bit is 0, then the number is positive; if it is 1, then the number


is negative.
Derived data types and User defined data types are the combination
of primitive data types. They are used to represent a collection of data.

They are:
 Arrays
 Pointers
 Structures
 Unions
 Enumeration
 
Note: Number of bytes and range given to each data type is platform
dependent.
Data types in C
size smallest largest format
type precision constant
(byte) number number specifier
1.2345L,
long double 10 3.4E-4932 1.1E+4932 1.08E-19 %Lf, %Le, %Lg
1.234E-5L
1.2345,
double 8 1.7E-308 1.7E+308 2.22E-16 %lf, %le, %lg
1.234E-5
1.2345F,
float 4 1.7E-38 3.4E+38 1.19E-7 %f, %e, %g
1.234E-5F

unsigned long 4 0 4294967295 123UL %lu

long 4 -2147483648 2147483647 123L %ld, %li

unsigned 4 0 4294967295 123U %u

int 4 -2147483648 2147483647 123 %d, %i

unsigned short 2 0 65535 123U %hu

short 2 -32768 32767 123 %hd, %hi

unsigned char 1 0 255 ’a’, 123, ’\n’ %c

char 1 -128 or 0 127 or 255 ’a’, 123, ’\n’ %c


Syntax:
All languages have a set of rules for how words and sentences should
be structured.

These rules are collectively known as the language syntax.

In computer programming, syntax serves the same purpose, defining


how declarations, functions, commands, and other statements should
be arranged.

Types of Errors:
1. Syntax Errors
2. Logical Errors
Syntax Errors:
A syntax error is an error in the source code of a program.

Since computer programs must follow strict syntax to compile


correctly, any aspects of the code that do not conform to the syntax of
the programming language will produce a syntax error.

Examples:
Spelling mistakes.
Missing out quotes.
Missing out brackets.
Using upper case characters in key words e.g. IF instead of if.
Missing out a colon or semicolon at end of a statement.
Logic errors:
A logic error (or logical error) is a ‘bug’ or mistake in a program’s
source code that results in incorrect or unexpected behaviour.

It is a type of runtime error that may simply produce the wrong output
or may cause a program to crash while running.

Many different types of programming mistakes can cause logic errors.

Example:

Multiplying two numbers instead of adding them together may also


produce unwanted results

You might also like