0% found this document useful (0 votes)
8 views56 pages

CP Chapter 01 Notes

The document provides an introduction to computer systems, detailing components such as hardware, software, and user interaction. It explains the roles of input, output, and storage devices, as well as the classification of programming languages from low-level to high-level. Additionally, it covers algorithms and flowcharts, emphasizing their importance in problem-solving and program design.

Uploaded by

seema.bhuravane
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)
8 views56 pages

CP Chapter 01 Notes

The document provides an introduction to computer systems, detailing components such as hardware, software, and user interaction. It explains the roles of input, output, and storage devices, as well as the classification of programming languages from low-level to high-level. Additionally, it covers algorithms and flowcharts, emphasizing their importance in problem-solving and program design.

Uploaded by

seema.bhuravane
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/ 56

Module -1

1.6.1 Introduction to components of a computer system:

Computer

Computer is an electronic device, which operates under the control of


instructions stored in its memory. A computer can take data from the user
through input devices (Input), process the user given data (Processing), produce
the result to the user through output devices (Output) and store data
(Information) for future use.

Every computer mainly consists of three things and those are

1. Hardware

2. Software

3. User
Fig. 1.1 Components of a Computer

Here the user interacts with the software, and the software makes the computer
hardware parts to work for the user.
Computer Hardware

All physical components of the computer are called computer hardware. A user
can see, touch and feel every hardware of the computer. All hardware
components perform any task supported by the computer software.

The computer hardware components are as follows...


1. Input Devices - A user can give the data to the computer through these
parts.
2. Output Devices - These are the physical components of a computer
through which the computer gives the result to the user.
3. Storage Devices - These are the physical components of a computer in
which the
data can be stored.
4. Devices Drives - Using drives, user can read and write data on to the storage devices like
CD, floppy, etc.,

5. Cables - Various cables (Wires) are used to make connections in a computer

6. Other Devices - Other than the above hardware components, a computer also contains
components like Motherboard, CPU (Processor), SMPS, Fans, etc.,

Input Devices

Computer input devices are the physical components of the computer which are used to give the
data given by the user to the computer. Using input devices, the user can give the data to the
computer.

Example

Fig. 1.2: Input Devices

Output Devices
Computer output devices are the physical components of the computer which are used to give the
computer result to the User. Using output devices, the user can see the computer- generated result.
Example

Fig. 1.3: Output Devices

Storage Devices

Computer storage devices are the physical components of the computer which are used to store
data internally or externally.
Example
Fig. 1.4: Storage Devices
Device Drives

Computer Device drives are the physical components of the computer which are used to read and
write data on the storage devices.

Example

Fig. 1.5: Devices Drives

Computer Cables

In a Computer, various cables are used to make connections among the various hardware
components of the computer.

Example
Fig. 1.5: Computer Cables

Other Devices

Other devices of the computer are shown below.


Fig. 1.6: CPU (Processor)

Fig. 1.7: SMPS

Fig. 1.8: CPU Fan

Fig. 1.9: Motherboard

How does Computer work?


When a user wants to speak with the monitor, the user interacts with an application. The
application interacts with the OS, and therefore the OS makes hardware components to figure
consistent with the user given instructions. The hardware components send the result back to the
OS, then the OS forwards an equivalent to the appliance and therefore the application shows the
result to the user.
By using input devices, the user interacts with the appliance and therefore the application uses
output devices to point out the result. All input and output devices work according to the
instructions given by the operating system. The working process of a computer is shown in the
following figure.

1.1.1 Programming Fundamentals:

⮚ Computer Language

Generally, we use languages like English, Hindi, etc., to form communication between two persons.
That means once we want to form communication between two persons, we'd like a language
through which persons can express their feelings. Similarly, once we want to form communication
between a user and computer or between two or more computers, we'd like a language through
which the user can give information to the computer and vice versa? When a user wants to offer
any instruction to the monitor, the user needs a selected language which is understood as a
computer-oriented language.

The user interacts with the pc using programs which programs are created using programming
languages like C, C++, Java, etc.,

Every programming language contains a group of predefined words and a group of rules (syntax)
that are wont to create instructions of a program.

Computer Languages Classification

Over the years, computer languages have evolved from Low-Level to High- Level Languages. In the
earliest days of computers, only Binary Language was used to write programs. The computer
languages are classified as follows.

Fig. 1.11: Computer Languages

Low-Level Language (Machine Language)

Low-Level language is the only language which can be understood by the computer. Binary
Language is an example of a low-level language. Low-level language is also known as Machine
Language. The binary language contains only two symbols 1 &
0. All the instructions of binary language are written in the form of binary numbers 1's & 0's.
A computer can directly understand the binary language. Machine language is also
known as the Machine Code. As the CPU directly understands the binary language instructions, it
does not require any translator. CPU directly starts executing the binary language instructions and
takes very less time to execute the instructions as it does not require any translation. Low-level
language is considered as the First-Generation Language (1GL).
Advantages

● A computer can easily understand the low-level language.

● Low-level language instructions are executed directly without any translation.

● Low-level language instructions require very less time for their execution.

Disadvantages

● Low-level language instructions are very difficult to use and understand.

● Low-level language instructions are machine-dependent, that means a program written for
a particular machine does not execute on another machine.
● In low-level language, there is more chance for errors and it is very difficult to find errors,
debug and modify.

Middle-Level Language (Assembly Language)

Middle-level language is a computer language in which the instructions are created using symbols
such as letters, digits and special characters. Assembly language is an example of middle-level
language. In assembly language, we use predefined words called mnemonics. Binary code
instructions in low-level language are replaced with mnemonics and operands in middle-level
language. But the computer cannot understand mnemonics, so we use a translator called
Assembler to translate mnemonics into binary language. Assembler is a translator, which takes
assembly code as input and produces machine code as output. That means, the computer cannot
understand middle-level language, so it needs to be translated into a low- level language to make it
understandable by the computer. Assembler is used to translate middle-level language into
low-level language.
Advantages

● Writing instructions in a middle-


level language is easier than writing instructions
in a low-level language.
● Middle-level language is more readable compared to low-level language.

● Easy to understand, find errors and modify.


Disadvantages

● Middle-level language is specific to a particular machine architecture that means it is


machine-dependent.
● Middle-level language needs to be translated into low-level language.

● Middle-level language executes slower compared to low-level language.

High-Level Language

A high-level language is a computer language which can be understood by the users. The high-level
language is very similar to human languages and has a set of grammar rules that are used to make
instructions more easily. Every high-level language has a set of predefined words known as
Keywords and a set of rules known as Syntax to
create instructions. The high-level language is easier to understand for the users, but the computer
cannot understand it. High-level language needs to be converted into the low-level language to
make it understandable by the computer. We use a Compiler or interpreter to convert high- level
language to low-level language.
Languages like COBOL, FORTRAN, BASIC, C, C++, JAVA, etc., are examples of high-level languages. All
these programming languages use human-understandable language like English to write program
instructions. These instructions are converted to low-level language by the compiler so that the
computer can understand it.
Advantages

● Writing instructions in a high-level language is easier.

● A high-level language is more readable and understandable.

● The programs created using high-level language runs on different machines with little
change or no change.
● Easy to understand, create programs, find errors and modify.

Disadvantages

● High-level language needs to be translated into low-level language.

● High-level language executes slower compared to middle and low-level languages.


Understanding Computer Languages

The following figure provides a few key points related to computer languages.
Fig. 1.12: key points related to computer languages From the above figure, we can observe the
following key points.
● The programming languages like C, C++, Java, etc., are written in High-level language which
is more comfortable for the developers.
● A high-level language is closer to the users.

● Low-level language is closer to the computer. Computer hardware can understand only the
low-level language (Machine Language).
● The program written in the high-level language needs to be converted to low- level
language to make communication between the user and the computer.
● Middle-level language is not closer to both user and computer. We can consider it as a
combination of both high-level language and low-level language.

Algorithm
An algorithm specifies a series of steps that perform a particular computation or task
An algorithm is ‘an effective procedure for solving a problem in a finite number of
steps.
In mathematics and computer science, an algorithm is a step-by-step procedure for
calculations. Algorithms are used for calculation, data processing, and automated reasoning.
Starting from an initial state and given initial inputs it precedes in a stepwise manner to a final
or desired state, producing “output” along the way. For example, a company may have a
specific procedure to calculate the salary of its employees. The clerical staff who calculate the
salaries repeatedly follow the process for each employee. They then hand over the salary slips
and salaries.

Computer algorithms Classification


Classifying an algorithm by implementation means we have Recursive or iterative
implementations. A recursive algorithm is one that invokes (makes reference to) itself
repeatedly until a certain condition matches, which is a method common to functional
programming. Iterative algorithms use repetitive constructs like loops and sometimes
additional data structures like stacks to solve the given problems.
Another way of classifying algorithms is by their design methodology or paradigm. Some
commonly found paradigms include Brute-force or exhaustive search, divide and conquer,
dynamic programming, greedy method and so on.
An Algorithm can have the following 3 types of constructs
1. Sequence 2. Selection 3. Iteration

Flowchart
A flowchart provides the steps to be followed in order to arrive at the solution to a problem. It
is a design tool used before the actual program is written. It may also be used as a
communication tool to explain the logic to non-technical people.
It is a diagram created using various standard shaped symbols. Given below is a list of basic
flowchart symbols
Symbol Use
Start or end of a program or flowchart

Computational steps or processing


function of a program

Input entry or output display


operation

Decision making and branching that


has two alternatives

Connector, connects remote parts of


the
flowchart on the same page
Flow lines, showing the flow of the
program
Fig. 1.13: Flowchart Symbols The three basic constructs can also
be shown as below
1. Sequence: Sequence logic is used for performing instructions one after another in
sequence.
● Sequence is the most basic of the constructs
● It is simply performing one step after another
● Each step is followed in a specific sequence, hence the name
● Sequence can be thought of as “do this, then do this, then do this”

2. Selection: Selection logic, also known as decision logic, is used for making decisions.
Selection logic is depicted as either an IF…THEN…ELSE or IF…. THEN structure.
● Selection is the decision-making construct.
● It is used to make yes/no or true/false decisions logically.
● Selection can be thought of as “if something is true, take this action,
otherwise take that action”.

Fig. 1.14: Selection Flowchart


3. Iteration: Iteration logic is also known as Loop. Iteration logic is used when one or more
instructions may be executed several times depending on some condition.
▪ Iteration comes from the word “reiterate”, which means to repeat
▪ Iteration is a looping construct
▪ Iteration is a combination of decision and sequence and can repeat steps
▪ Iteration can be thought of as “while something is true, do this, otherwise stop”

Fig. 1.15: Iteration Flowchart

Advantages of Flowcharts
● Communication: They are a better way of communicating
● Effective Analysis: Effective way of analysis of a problem
● Proper Documentation: Serve as good documentation
● Efficient Code: Aid in writing efficient code
● Proper Debugging: Help in debugging
● Efficient program maintenance: Maintaining the program becomes easier

Limitations of Flowcharts
● Cannot show complex logic, become clumsy in such cases
● May be difficult to alter
● What is to be done may be lost in the how it is to be done

⮚ Characteristics of an Algorithm
Algorithm should satisfy the following criteria
1. Input: Zero or more quantities are externally supplied.
2. Output: At least one quantity is produced.
3. Definiteness: Each instruction is clear and unambiguous. Ex Add B or C to A
4. Finiteness: Algorithm should terminate after finite number of steps when traced in
all cases Ex: Go on adding elements to an array
5. Effectiveness: Every instruction must be basic i.e., it can be carried out, by a person
using pencil and paper.
Algorithms must also be general to deal with any situation.

Advantages of Algorithms
● It provides the core solution to a given problem. The solution can be implemented on
a computer system using any programming language of the user's choice.
● It facilitates program development by acting as a design document or a blueprint of a
given problem solution.
● It ensures easy comprehension of a problem solution as compared to an equivalent
computer program.
● It eases identification and removal of logical errors in a program.
● It facilitates algorithm analysis to find out the most efficient solution to a given
problem.
Disadvantages of Algorithms
● In large algorithms the flow of program control becomes difficult to track.
● Algorithms lack visual representation of programming constructs like flowcharts;
thus, understanding the logic becomes relatively difficult.

Examples of Algorithm and Flowchart:


Q.1) Write an algorithm and draw a flowchart for swapping two numbers using and without using the
third variable.
Answer:
To Swap two integer numbers: Algorithm: a. using third variable
Step1: Start
Step 2: Input num1, num2
Step 3: temp = num1
Step 4: num1 = num2
Step 5: num2 = temp
Step 6: Output num1, num2
Step 7: Stop
Algorithm: b. without using third variable
Step 1: Start
Step 2: Input num1, num2
Step 3: calculate num1 = num1 + num2

Step 4: calculate num2 = num1 – num2 Step 5: calculate num1 = num1 – num2 Step 6: Output
num1, num2
Step 7: Stop

Flowcharts:

Q.2) Write an algorithm and draw a flowchart to find the largest among two numbers.
Answer:
Algorithm:
Step 1: Start
Step 2: Input A, B
Step 3: if A > B then
output A else output B
Step 4: Stop
Flowchart:

Q. 3) Write an algorithm and draw a flowchart to find the largest among three numbers.
Answer:
Algorithm: (method 1)
Step 1: Start
Step 2: Input A, B, C
Step 3: if A > B go to step 4, otherwise go to step 5 Step 4: if A > C go to step 6, otherwise go to
step 8 Step 5: if B > C go to step 7, otherwise go to step 8 Step 6: print “A is largest”, go to step 9
Step 7: print “B is largest”, go
to step 9
Step 8: print “C is largest”, go
to step 9
Step 9: Stop

Flowchart:
Algorithm: (method 2)
Step 1: Start
Step 2:Input A, B, C
Step 3:Let max = A
Step 4: if B > max then max = B
Step 5: if C > max then max = C
Step 6: output max is largest
Step 7: Stop
Flowchart:
Q.4) Write an algorithm and draw a flowchart to find the factorial of a number
Answer:
Algorithm:
Step 1:
Start Step 2:
Input n
Step 3: Initialize counter variable, i , to 1 and factors = 1 Step 4: if i <= n go to step 5 otherwise go
to step 7
Step 5: calculate factors = factors * i
Step 6: increment counter variable, i, and go to step 4 Step 7: output factors.
Step 8: stop

Flowchart:
Q.5) Write an algorithm and draw a flowchart to find the reverse of a number.
Answer:
Algorithm:
Step 1:
Start Step 2:
Input n Step 3:
Let rev=0
Step 4: if n<=0 go to step 8 Step 5: digit = n % 10
Step 6: rev = (rev * 10) + digit Step 7: n = n / 10 then go to step 4 Step 8: output rev
Step 9: Stop
Flowchart:
● Applications:
1) Algorithms can be made very precise for implementation on computers, smart phones,
and other devices.
2) The flowchart helps in the coding process efficiently, as it gives directions on what to do,
when to do, and where to do. It makes the work easier.
3) Flowchart also helps in finding the error (if any) in program

Unsolved questions/problems:
● List and explain the functions of various parts of computer hardware and software.
● What is an algorithm? What are the points to be considered while developing the algorithm?
● Write algorithm and draw flowchart to calculate roots of quadratic equation.
● Write an algorithm and draw a flowchart to calculate Simple interest.
● Write an algorithm and flowchart to find whether a number is Prime or not.
● List out the advantages and disadvantages of algorithms.
● Write an algorithm and flowchart to find whether a number is Armstrong or not.
● Write an algorithm and draw a flowchart to find the GCD and LCM of two numbers.
● Write an algorithm and draw a flowchart to generate Fibonacci series of first ‘n’ numbers.

Fundamentals of C-Programming
Theoretical Background:
C is a general-purpose programming language that options economy of expression,
fashionable management flow and information structures, and a fashionable set of operators. C
isn't a "very high level" language, nor a "big" one, and isn't specialized to any specific space of
application. However its absence of restrictions and its generality create it a lot of convenient and
effective for several tasks than purportedly a lot of powerful languages. In the early 1970s the C
programing language was designed and enforced by Dennis Ritchie at Bell Laboratories on a DEC
PDP-11 that used the UNIX operating system. During development of the language it absolutely was
influenced by an older language called BPCL, which was developed by Martin I. A. Richards. The
language BPCL influenced a language referred to as B (written by Ken Thompson) which led to the
development of C in the 1970s.
Character Set, Identifiers and keywords:
⮚ Character Set:
As every language contains a group of characters used to construct words, statements, etc.,
C language also features a set of characters which include alphabets, digits, and special
symbols. C language supports a total of 256 characters. Every C program contains
statements. These statements are constructed using words and these words are
constructed using characters from C character list. C language character list contains the
subsequent set of characters.
i. Alphabets
ii. Digits
iii. Special Symbols
Alphabets
C language supports all the alphabets from the English language. Lower and upper case
letters together support 52 alphabets.
Lower case letters - a to z UPPER CASE LETTERS - A to Z
Digits
C language supports 10 digits which are used to construct numerical values in C language.
Digits - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
Special Symbols
C language supports a rich set of special symbols that include symbols to perform
mathematical operations, to check conditions, white spaces, backspaces, and other special
symbols.
Special Symbols - ~ @ # $ % ^ & * ( ) _ - + = { } [ ] ; : ' " / ? . > , < \ | tab newline space
NULL bell backspace vertical tab etc.,
⮚ Identifiers:
Identifier refers to call given to entities like variables, functions, structures etc. Identifier
must be unique. They are created to offer unique name to an entity to spot it during the
execution of the program.
For example: int money; double account Balance; Here, money and account Balance are
identifiers.
Also remember, identifier names must be different from keywords. You cannot use int as an
identifier because int is a keyword.
Rules for writing an identifier
✔ 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. However, it
is discouraged to start an identifier name with an underscore.
✔ There is no rule on length of an identifier. However, the first 31 characters of
identifiers are discriminated by the compiler.

⮚ Keywords:
Keywords are predefined; reserved words utilized in programming that have a special
meaning. Keywords are a part of the syntax and that they can’t be used as an identifier.
For example: int make;
Here, int is a keyword that indicates 'make' is a variable of type integer.
As C is a case sensitive language, all keywords must be written in lowercase. In the C
programming language, there are 32 keywords. All the 32 keywords have their meaning
which is already known to the compiler. Here is a list of all keywords allowed in ANSI C.

There are 32 keywords in the C programming language, and each one has a predefined meaning
which is known to the compiler, and as such shouldn't be used otherwise. As a C developer, you
should be aware of their existence and never use them for other purposes other than their original
use.

Properties of keywords in C
Keywords in C has properties that should be noted when in use. Failure to adhere to these
properties may result in unexpected behaviour.
1. Keywords are case-sensitive. They are defined in lowercase letters and can only be used in
lowercase.
2. Keywords has a semantic meaning known to the C compilers and their meaning cannot be
overridden by the users.
3. Keywords cannot be used as a variable name, function and other expressions.
Table1. Keywords in C

For details: https://iq.opengenus.org/keywords-in-c/


Data types, Variable, Constants:
Data Types:
Data utilized in c program is assessed into different types supported its properties. In the C
programming language, a data type are often defined as a group of values with similar
characteristics. All the values during a data type have an equivalent properties.
Data types within the c programming language are used to specify what quite value are
often stored during a variable. The memory size and type of the value of a variable are
determined by the variable data type. In a c program, each variable or constant or array
must have a data type and this data type specifies what proportion memory is to be
allocated and what type of values are to be stored therein variable or constant or array.
The Data type must be a set of value with predefined characteristics. Data types are used to
declare variable, constants, arrays, pointers, and functions.
In the c programming language, data types are classified as follows...
● Primary data types (Basic data types OR Predefined data types)
● Derived data types (Secondary data types OR User-defined data types)
● Enumeration data types
● Void data type
Figure 2.1: Data Types
Primary data types
The primary data types within the C programming language are the essential data types. All
the primary data types are already defined within the system. Primary data types also are
called as Built-In data types. The following are the primary data types in c programming
language.
● Integer data type
● Floating Point data type
● Double data type
● Character data type
Figure 2.2: Basic Data types

Integer Data type


The integer data type may be a set of whole numbers. Every integer value doesn’t have the
decimal value. We use the keyword "int" to represent integer data type in c. We use the
keyword int to declare the variables and to specify the return sort of a function. The integer
data type is employed with different type modifiers like short, long, signed and unsigned. The
subsequent table provides complete details about the integer data type.

Table.2: Integer Data types with its size, range and format specifier

Typ Size (in Range Format


e Bytes) Specifier

int (signed short 2 -32768 to +32767 %


int) d
short int (signed 2 -32768 to +32767 %
short int) d
long int (signed 4 -2,147,483,648 %
long int) to d
+2,147,483,647
unsigned int 2 0 to 65535 %
(unsigned short u
int)
unsigned long int 4 0 to 4, %
294,967,295 u

Floating Point data types


Floating-point data types are a group of numbers with the decimal value. Every floating- point
value must contain the decimal value. The floating-point data type has two variants.

● float
● double
We use the keyword "float" to represent floating-point data type and "double" to represent
double data type in c. Both float and double are similar but they differ in the number of
decimal places. The float value contains 6 decimal places whereas double value contains 15 or
19 decimal places. The following table provides complete details about floating-point data
types.
Table 3: Floating point Data types with its size, range and format specifier
Type Size (in Range Format
Bytes) Specifie
r
Float 4 3.4 E –38 to 3.4 E +38 %f
Double 8 1.7 E –308 to 1.7 E +308 %ld
long double 10 1.1 E –4932 to 1.1 E + %ld
4932

Character data type


The character data type is a set of characters enclosed in single quotations. The following table
provides complete details about the character data type.
Table 2.4: Character Data types with its size, range and format specifier
Type Size (in Range Format
Bytes) Specifie
r
char (signed char) 1 -128 to 127 %c
unsigned char 1 0 to 255 %c

Enumerated data type


An enumerated data type may be a user-defined data type that consists of integer constants
and every integer constant is given a name. The keyword "enum" is employed to define the
enumerated data type
Void data type
The void data type means nothing or no value. Generally, the void is employed to specify a
function which does not return any value. We also use the void data type to specify empty
parameters of a function.

Derived data types


Derived data types are user-defined data types. The derived data types also are called as
user-defined data types or secondary data types. Within the c programming language, the
derived data types are created using the subsequent concepts.
● Arrays
● Structures
● Unions
Variable:
Variables within the c programming language are the named memory locations where the user
can store different values of equivalent data type during the program execution. Meaning a
variable may be a name given to a memory location during which we will store different values
of an equivalent data type. In other words, a variable are often defined as a storage container to
carry values of an equivalent data type during the program execution. Every variable in c
programming language must be declared within the declaration section before it’s used. Every
variable must have a data type that determines the range and sort of values be stored and
therefore the size of the memory to be allocated. A
variable name may contain letters, digits and underscore symbol. The subsequent are the
principals to specify a variable name.

✔ Variable name should not start with a digit.


✔ Keywords should not be used as variable names.
✔ A variable name should not contain any special symbols except underscore (_).
✔ A variable name can be of any length but compiler considers only the first 31 characters
of the variable name.

Declaration of Variable:
Declaration of a variable tells the compiler to allocate the required amount of memory with the
specified variable name and allows only specified data type values into that memory location.
In C programming language, the declaration are often performed either before the function as
global variables or inside any block or function. But it must be at the start of block or function.
Declaration Syntax:
datatype variableName;
Example:
int number;
The above declaration tells to the compiler that allocates 2 bytes of memory with the name
number and allows only integer values into that memory location.

Constants:
In C programming language, a constant is analogous to the variable but the constant hold just
one value during the program execution. Meaning, once a value is assigned to the constant, that
value cannot be changed during the program execution. Once the value is assigned to the
constant, it is fixed throughout the program. A constant may be a named memory location
which holds just one value throughout the program execution.
In C programming language, a constant are often of any data type like integer, floating-point,
character, string and double, etc.,
Creating constants in C
In a c programming language, constants can be created using two concepts. Using the 'const'
keyword
Using '#define' preprocessor

Using the 'const' keyword


We create a constant of any data type using 'const' keyword. To create a constant, we prefix the
variable declaration with 'const' keyword.
The general syntax for creating constant using 'const' keyword is as follows... const datatype
constantName ;
OR
const datatype constantName = value ;
Example
const int x = 10 ;
Here, 'x' is a integer constant with fixed value 10.
Program:
#include<stdio.h> #include<conio.h> void main(){
int i = 9 ;
const int x = 10 ; i = 15;
x = 100; // creates an error printf("i = %d\nx = %d", i, x ) ; getch();
}
The above program gives an error because we are trying to change the constant variable value
(x = 100).

Using '#define' preprocessor


We can also create constants using '#define' preprocessor directive. When we create constant
using this preprocessor directive it must be defined at the beginning of the program (because
all the preprocessor directives must be written before the global declaration).
We use the following syntax to create constant using '#define' preprocessor directive.
#define CONSTANTNAME value

Example: Find area of circle using constant function definition #define PI 3.14
Here, PI is a constant with value 3.14
Program:
#include<stdio.h> #include<conio.h>
#define PI 3.14
void main(){
int r, area ;
printf("Please enter the radius of circle : ") ;
scanf("%d", &r) ;
area = PI * (r * r) ;
printf("Area of the circle = %d", area) ;
}
Operators-
1. Arithmetic,
2. Relational
3. logical,
4. Assignment,
5. Bitwise
6. Conditional:
An operator is a symbol used to perform arithmetic and logical operations during a program. That
means an operator may be a special symbol that tells the compiler to perform mathematical or
logical operations.
1. Arithmetic Operators (+, -, *, /, %)
The arithmetic operators are the symbols that are used to perform basic mathematical
operations like addition, subtraction, multiplication, division and percentage modulo. The
following table provides information about arithmetic operators.

Oper Meaning Example


ator
+ Addition 10 + 5 = 15

- Subtraction 10 - 5 = 5

* Multiplication 10 * 5 = 50

/ Division 10 / 5 = 2

% Remainder of the 5%2=1


Division

2. Relational Operators (<, >, <=, >=, ==,!=)


The relational operators are the symbols that are used to compare two values. That means the
relational operators are used to check the relationship between two values. Every relational
operator has two results TRUE or FALSE. In simple words, the relational operators are used to
define conditions in a program. The following table provides information about relational
operators.
Operatio
n
Meaning Example

< Returns TRUE if the first value is smaller than second 10 < 5 is
value otherwise returns FALSE FALSE

> Returns TRUE if the first value is larger than second value 10 > 5 is
otherwise returns FALSE TRUE
< Returns TRUE if the first value is smaller than or equal to 10 <= 5
= second value otherwise returns FALSE is
FALSE

> Returns TRUE if the first value is larger than or equal to 10 >= 5
= second value otherwise returns FALSE is
TRUE
= Returns TRUE if both values are equal otherwise returns 10 == 5
= FALSE is
FALSE
!= Returns TRUE if both values are not equal otherwise 10 != 5 is
returns FALSE TRUE

Table 6: Relational Operators with example


3. Logical Operators (&&, ||, !)
The logical operators are the symbols that are used to combine multiple conditions into one
condition. The following table provides information about logical operators.

Table 2.7: Logical Operators with example

Opera tor
Meaning Examp
le
&& Logical AND - Returns TRUE if all conditions are TRUE 10 < 5 && 12 >
otherwise returns FALSE 10 is FALSE

|| Logical OR - Returns FALSE if all conditions are FALSE 10 < 5 || 12 >


otherwise returns TRUE 10 is TRUE

! Logical NOT - Returns TRUE if condition is FLASE and returns !(10 < 5 && 12
FALSE if it is TRUE > 10) is TRUE

Increment & Decrement Operators (++ & --)

Operato
r Meaning Example

++ Increment - Adds one to existing int a = 5; a++; ⇒ a = 6


value

-- Decrement - Subtracts one from int a = 5;


existing value a--; ⇒ a = 4

The increment and decrement operators are used in front of the operand (++a) or after the
operand (a++). If it is used in front of the operand, we call it as pre-increment or pre-
decrement and if it is used after the operand, we call it as post-increment or post-
decrement.
Pre-Increment or Pre-Decrement
In the case of pre-increment, the value of the variable is increased by one before the
expression evaluation. In the case of pre-decrement, the value of the variable is decreased by
one before the expression evaluation. That means, when we use pre-increment or pre-
decrement, first the value of the variable is incremented or decremented by one, then the
modified value is used in the expression evaluation.
Program:
#include<stdio.h>
#include<conio.h> void main(){
int i = 5,j;
j = ++i; // Pre-Increment printf("i = %d, j = %d",i,j); }
Output:
i=6, j=6
Post-Increment or Post-Decrement
In the case of post-increment, the value of the variable is increased by one after the expression
evaluation. In the case of post-decrement, the value of the variable is decreased by one after
the expression evaluation. That means, when we use post-increment or post- decrement, first
the expression is evaluated with existing value, then the value of the variable is incremented
or decremented by one.
Program:
#include<stdio.h> #include<conio.h> void main(){
4. Assignment Operators (=, +=, -=, *=, /=, %=)
The assignment operators are used to assign right-hand side value (Rvalue) to the left-hand
side variable (Lvalue). The assignment operator is used in different variants along with
arithmetic operators. The following table describes all the assignment operators in the C
programming language.
Table 2.9: Assignment Operators with example

Opera
tor Meaning Example

= Assign the right-hand side value to left-hand side A = 15


variable

+= Add both left and right-hand side values and store the A += 10
result into left-hand side variable ⇒ A = A+10

-= Subtract right-hand side value from left-hand side A -= B


variable value and store the result ⇒ A = A-B
into left-hand side variable

*= Multiply right-hand side value with left-hand side A *= B


variable value and store the result ⇒ A = A*B
into left-hand side variable

/= Divide left-hand side variable value with right-hand A /= B


side variable value and store the result ⇒ A = A/B
into the left-hand side variable

%= Divide left-hand side variable value with right-hand A %= B


side variable value and store the remainder ⇒ A = A%B
into the left-hand side variable

5. Bitwise Operators (&, |, ^, ~, >>, <<)


The bitwise operators are used to perform bit-level operations in the c programming
language. When we use the bitwise operators, the operations are performed based on the
binary values. The following table describes all the bitwise operators in the C programming
language.
Let us consider two variables A and B as A = 25 (11001) and B = 20 (10100).
Table 10: Bitwise Operators with example

Operato r
Meaning Example

& the result of Bitwise AND is 1 if all the bits are 1 otherwise it A&B
is 0 ⇒ 16 (10000)
| the result of Bitwise OR is 0 if all the bits are 0 otherwise it is A|B
1 ⇒ 29 (11101)

^ the result of Bitwise XOR is 0 if all the bits are same A^B
otherwise it is 1 ⇒ 13 (01101)

~ the result of Bitwise once complement is negation of the bit ~A


(Flipping) ⇒ 6 (00110)

<< the Bitwise left shift operator shifts all the bits to the left by A << 2
the specified number of positions ⇒ 100 (1100100)

>> the Bitwise right shift operator shifts all the bits to the right A >> 2
by the specified number of positions ⇒ 6 (00110)

6. Conditional Operator (?:)


The conditional operator is also called a ternary operator because it requires three operands.
This operator is used for decision making. In this operator, first we verify a condition, then we
perform one operation out of the two operations based on the condition result. If the
condition is TRUE the first option is performed, if the condition is FALSE the second option is
performed. The conditional operator is used with the following syntax.

Condition ? TRUE Part : FALSE Part;

Example
A = (10<15)? 100:200; ⇒ A value is

100

The following are the special operators in c programming language.


sizeof operator
This operator is used to find the size of the memory (in bytes) allocated for a variable. This
operator is used with the following syntax.

sizeof(variableName);

Example

sizeof(A); ⇒ the result is 2 if A is an integer

Comma operator (,)


This operator is used to separate variables while they are declaring, separate the expressions
in function calls, etc.

Dot operator (.)


This operator is used to access members of structure or union.
Operator Precedence
There are so many operators in C language, how they affect the output of an expression when multiple
operators are used together is decided by the operator precedence. Based on the operator precedence,
the C compiler decides the order in which the operators are evaluated. For example, if we have three
variables a, b and c, then for the expression a+b*c, the compiler will first multiply b and c, and then add
the result of multiplication with a, because the * operator has higher precedence than the + operator.

Not all operators can be used together in a single expression, hence the operator precedence is only
relevant for the operators that can be used together, and they are:
1. Arithmetic operators
2. Relational operators
3. Logical operators
Data Input and Output –
1. printf( ),
2. scanf( ),
3. putchar( ),
4. getchar( ),
5. puts( ),
6. gets( )

⮚ C Input Functions
C programming language provides built-in functions to perform input operations. The input
operations are used to read user values (input) from the keyboard. The c programming
language provides the following built-in input functions.

1. scanf()
2. getchar()
3. getch()
4. gets()
5. fscanf()

1. scanf() function
The scanf() function is used to read multiple data values of different data types from the
keyboard. The scanf() function is built-in function defined in a header file called "stdio.h".
When we want to use scanf() function in our program, we need to include the respective
header file (stdio.h) using #include statement. The scanf() function has the following syntax...
Syntax:
scanf("format strings",&variableNames);
Program:
#include<stdio.h> #include<conio.h> void main(){
int i;
printf("\nEnter any integer value: "); scanf("%d",&i);
printf("\nYou have entered %d number",i); getch();
}
Output:
In the above example program, we used the scanf() function to read an integer value from the
keyboard and store it into variable 'i'.

The scanf function also used to read multiple data values of different or the same data types.
Consider the following example program.
Program:
#include<stdio.h> #include<conio.h> void main(){
int i; float x;
printf("\nEnter one integer followed by one float value : "); scanf("%d%f",&i, &x);
printf("\ninteger = %d, float = %f",i, x);
}
Output:
In the above example program, we used the scanf() function to read one integer value and one
float value from the keyboard. Here 'i' is an integer variable so we have used format string
%d, and 'x' is a float variable so we have used format string %f

2. getchar( ) function
The getchar() function is used to read a character from the keyboard and return it to the
program. This function is used to read a single character. To read multiple characters we need to
write multiple times or use a looping statement. Consider the following example program.
Program:
#include<stdio.h> #include<conio.h> void main(){
char ch;
printf("\nEnter any character : "); ch = getchar();
printf("\nYou have entered : %c\n",ch);
}
Output:
Enter any Character : B

Program:
#include<stdio.h> #include<conio.h> void main(){
char ch;
printf("\nEnter any character : "); ch = getch();
printf("\nYou have entered : %c",ch);

}
Output:
Enter any character :
You have entered : S
4. gets() function
The gets() function is used to read a line of string and stores it into a character array. The gets()
function reads a line of string or sequence of characters till a newline symbol enters. Consider
the following example program.
Program
#include<stdio.h> #include<conio.h> void main(){
char name[30];
printf("\nEnter your favorite website: "); gets(name);
printf("%s",name);
}
Output:
Enter your favorite website: tcetmumbai tcetmumbai

5. fscanf() function
The fscanf() function is used with the concept of files. The fscanf() function is used to read data
values from a file. When you want to use fscanf() function the file must be opened in reading
mode.

⮚ C Output Functions
C programming language provides built-in functions to perform output operation. The output
operations are used to display data on user screen (output screen) or printer or any file. The c
programming language provides the following built-in output functions...

1. printf()
2. putchar()
3. puts()
4. fprintf()

1. printf() function
The printf() function is used to print string or data values or a combination of string and data
values on the output screen (User screen). The printf() function is built-in function defined in a
header file called "stdio.h". When we want to use printf() function in our program we need to
include the respective header file (stdio.h) using the #include statement. The printf() function
has the following syntax.
printf("message to be display!!!");
Program:
#include<stdio.h> #include<conio.h> void main(){ printf("Hello world!");
}
Output:
Hello world!

In the above example program, we used the printf() function to print a string on to the output
screen.
The printf() function is also used to display data values. When we want to display data values
we use format string of the data value to be displayed.
printf("format string",variableName);
Program: #include<stdio.h> #include<conio.h> void main(){
int i = 10; float x = 5.5;
printf("%d %f",i, x);
}
Output:
10 5.500000

In the above example program, we used the printf() function to print data values of variables i
and x on to the output screen. Here i is an integer variable so we have used format string %d
and x is a float variable so we have used format string %f.
The printf() function can also be used to display string along with data values.
Syntax:
printf("String format string",variableName);
Program:
#include<stdio.h> #include<conio.h> void main(){
int i = 10; float x = 5.5;
printf("Integer value = %d, float value = %f",i, x);
}
Output:
Integer value = 10, float value = 5.500000

In the above program, we are displaying string along with data values. To display
the output in different lines or as we wish, we use some special characters called escape
sequences. Escape sequences are special characters with special functionality used in printf()
function to format the output according to the user requirement. In the C programming
language, we have the following escape sequences.

Table 2.11: Escape Sequences


Esca
pe Meaning
seque
nce
\n Moves the cursor to New Line
\t Inserts Horizontal Tab (5 characters space)

\v Inserts Vertical Tab (5 lines space)

\a Beep sound

\b Backspace (removes the previous character from its


current position)

\\ Inserts Backward slash symbol

\? Inserts Question mark symbol

\' Inserts Single quotation mark symbol

\" Inserts Double quotation mark symbol

Consider the following example program.


Program: #include<stdio.h> #include<conio.h> void main(){
printf("Welcome to\n"); printf("tcetmumbai\n");
printf("the perfect website for learning");
}
Output:
Welcome to tcetmumbai

2. putchar() function
The putchar() function is used to display a single character on the output screen. The putchar()
functions prints the character which is passed as a parameter to it and returns the same
character as a return value. This function is used to print only a single character. To print
multiple characters we need to write multiple times or use a looping statement. Consider the
following example program...
Program: #include<stdio.h> #include<conio.h> void main(){
char ch = 'A'; putchar(ch);
}
Output:
A

3. puts() function
The puts() function is used to display a string on the output screen. The puts() functions prints a
string or sequence of characters till the newline. Consider the following example program.
Program:
#include<stdio.h> #include<conio.h> void main(){
char name[30];
printf("\nEnter your favorite website: "); gets(name);

4. fprintf() function
The fprintf() function is used with the concept of files. The fprintf() function is used to print a
line into the file. When you want to use fprintf() function the file must be opened in writing
mode.
⮚ Structure of C Program
Generally, the programs created using programming languages like C, C++, Java, etc., are
employing a application-oriented language like English. But, the machine cannot understand
the employing a application-oriented language. It can understand only low- level language. So,
the program written within the application-oriented language needs to be converted into the
low-level language to form it understandable for the machine. This conversion is performed
using either Interpreter or Compiler.
To create and execute C programs within the Windows Operating System, we need to install
Turbo C software. We use the subsequent steps to create and execute C programs in Windows
OS.

Execution Process of a C Program


When we execute a C program it undergoes with the following process.
Figure 2.3: Execution of a C Program
The file which contains C program instructions during a application-oriented language is
claimed to be ASCII text file. Every C program source file is saved with .c extension, for
instance,Sample.c.
Whenever we press Alt + F9 the source file is submitted to the compiler. Compiler checks for the
errors, if there are any errors, it returns an inventory of errors, otherwise generates code during
a file with name Sample.obj and submit it to the linker. The linker combines the code from
specified header file into an object file and generates executable file as Sample.exe. With this
compilation process completes.
Now, we need to run the executable file (Sample.exe). To run a program we press Ctrl + F9. Once
we press Ctrl + F9 the executable file is submitted to the CPU. Then CPU performs the task
consistent with the instructions written therein program and places the result into User Screen.
Then we press Alt + F5 to open User Screen and check the results of the program.

Important Points
● C program file (Source file) must save with .c extension.
● The compiler converts complete program at a time from high-level language to low-
level language.
● Input to the compiler is .c file and output from the compiler is .exe file, but it also
generates .obj file in this process.
● The compiler converts the file only if there are no errors in the source code.
● CPU places the result in User Screen window.
Overall Process
● Type the program in C editor and save with .c extension (Press F2 to save).
● Press Alt + F9 to compile the program.
● If there are errors, correct the errors and recompile the program.
● If there are no errors, then press Ctrl + F9 to execute/run the program.
● Press Alt + F5 to open User Screen and check the result.

You might also like