Unit 1 Notes Autonomous
Unit 1 Notes Autonomous
Unit 1 Notes Autonomous
INTRODUCTION TO COMPUTERS:
Basic Definitions:
Input: the data and information entering (given by user) into a computer.
Computer:
The term computer is derived from the latin word “compute” which means to calculate or to
manipulate. A Computer is an electronic device capable of performing computations and making
logical decisions at speeds millions and even billions of times faster than human beings can.
Basically computer is an electronic device which takes input from the user processes the
given data and produces the output.
COMPUTER : A computer is a electronic device which accepts data as input, process it according to
instructions given, and displays the output.
CAPABILITIES OF A COMPUTER
1. HUGE DATA STORAGE:-a computer can store any amount of data and instructions in
its memory.
2. INPUT AND OUTPUT: a computer receives data and instructions from the user and
displays it after the execution.
3. PROCESSING: it process the data entered by the user.
All the data received by the computer goes through the input unit. The input unit
comprises different devices like a mouse, keyboard, scanner, etc.
In other words, each of these devices acts as a mediator between the users and the
computer.
The data that is to be processed is put through the input unit.
The computer accepts the raw data in binary form. It then processes the data and
produces the desired output.
The 3 major functions of the input unit are-
Take the data to be processed by the user.
Convert the given data into machine-readable form.
And then, transmit the converted data into the main memory of the computer. The sole
purpose is to connect the user and the computer. In addition, this creates easy
communication between them.
CU – Control Unit
The control unit as the name suggests is the controller of all the activities/tasks and operations.
All this is performed inside the computer.
The memory unit sends a set of instructions to the control unit. Then the control unit in turn
converts those instructions. After that these instructions are converted to control signals.
These control signals help in prioritizing and scheduling activities. Thus, the control unit
coordinates the tasks inside the computer in sync with the input and output units.
Memory Unit
All the data that has to be processed or has been processed is stored in the memory unit. The
memory unit acts as a hub of all the data. It transmits it to the required part of the computer
whenever necessary.
The memory unit works in sync with the CPU.
This helps in faster accessing and processing of the data.
Thus making tasks easier and quicker.
RAM stands for Random Access Memory. It is an example of primary memory. This
memory is directly accessible by the CPU. It is used for reading and writing purposes.
For data to be processed, it has to be first transferred to the RAM and then to the CPU.
2. Secondary memory – As explained above, the primary memory stores temporary data.
Thus it cannot be accessed in the future. For permanent storage purposes, secondary
memory is used. It is also called permanent memory or auxiliary memory. The hard disk
is an example of secondary memory. Even in a power failure data does not get erased
easily.
Output
There is nothing to be amazed by what the output unit is used for.
All the information sent to the computer once processed is received by the user through the
output unit.
Devices like printers, monitors, projectors, etc. all come under the output unit.
The output unit displays the data either in the form of a soft copy or a hard copy. The printer is
for the hard copy. The monitor is for the display. The output unit accepts the data in binary form
from the computer. It then converts it into a readable form for the user.
COMPONENTS OF COMPUTER :
HARDWARE:
It is a general term used to represent the physical and tangible components of the computer itself i.e. those
components which can be touched and seen. It includes
(1) Input devices
(2) Output devices
(3) Central processing Unit
(4) Storage devices
SOFTWARE:
It is a general term to describe all the forms of programs associated with a computer. Without
software, a computer is like a human body with out a soul.
It is a general term to describe all the forms of programs associated with a computer. Without
software, a computer is like a human body without a soul.
System software
Application software
i) Operating system
ii) Language Translators
OPERATING SYSTEMis the interface between the user and the computer hardware.
LANGUAGE TRANSLATOR is a software that accepts input in one language and convert them into
another language.
Compiler
Assembler
Interpreter
Application software is a set of programs that allows the computer to help users in solving problems.
Ex:- MS-OFFICE
Operating system
An operating system acts as an interface between the software and different parts of
the computer or the computer hardware. The operating system is designed in such a
way that it can manage the overall resources and operations of the computer.
Natural language like English, Hindi, Telugu etc., are generally used by human beings to
communicate with each other.
With these languages we can express or exchange our ideas, feelings and emotions.
Similarly a computer language is used for communication between human being and the computer.
A program language can be defined as a language used for expressing a set of computer instructions
called program
MACHINE LANGUAGE
OP CODE OPERAND
Ex:
4.Machine language is machine dependent. That is program written for a particular computer has
to be changed for using on a different computer.
Ex:
Suppose to add two number stored in locations B and C and store the result in storage
location D
1.No need of remembering all binary OP codes and address of memory location
1.Execution of program takes more time as it has to be converted into machine language
Suppose to add two number stored in locations B and C and store the result in storage
location D
Pascal : D:=B+C;
C : D=B+C
1.The High level Language are easier to use and understand than the machine languages and the
assembly language
2.A High level Language is more expensive than the low level language and hence the programs
written in HLL are much more compact and self explanatory than their low level counterparts
3. High level Language are provide a better documentation than low level languages.
1.Less efficient as they take more execution time when compared to low level languages
2.The programmer cannot completely connect the total power available at hardware level .
ASSEMBLER, COMPILER AND INTERPRETER
If the program written in a language other than machine language of computer,the the computer
cannot understand it. Hence , the programs written in other languages must be translated into the
machine language of the computer before they executed . The translation process can be done
through a special software (system program) known as language processors.
Assembler
An assembler is program which translates an assembly language program into the machine
language. It gives one machine language instruction for each assembly language instruction. It
also produces error messages .
1. Compiler
A compiler is a program which translates a high level language program into machine language
of the host computer. It translates all the instructions of HLL program at a time. A compiler also
produces the error messages that occurs during translation. Once a program is error free , then
the compiled software is not needed in the memory because the machine code itself can be used
again and again.
2. Interpreter
A interpreter is a program which translate s a high level language program into machine
language of the host computer. It translates each instruction and executes it immediately. If there
is any error in any line ,it shows the error message at the same time and program execution
cannot continue until the error is rectified. Once a program is error free ,the memory is
unnecessarily occupied by interpreter as it has to reside for every run.
Compiler Interpreter
Popular for developed programs. Popular in program development environment.
Converts entire code at a time. Converts the code line by line.
Creates a permanent object file. No object file is created.
Reports all the errors at a time. It stops at the first error in program.
NUMBER SYSTEM
A number system of base (or radix), r is a system that uses distinct symbols for r digits. To determine the
quantity that the number represents, it is necessary to multiply each digit by an integer power of r
and then form the sum of all weighted digits.
7 2 4 . 5
The binary number system uses the radix 2. The two digit symbols used are 0 and 1.
23 22 21 20
The octal number system uses the radix 8. The eight numbers used in octal system are 0-7.(i.e,
0,1,2,3,4,5,6,7).
Ex:- 34.6(8)
3 4 . 6
81 80 8-1
The hexa decimal number system uses the radix 16. The sixteen numbers used in hexa decimal system are
0-F.(i.e., 0,1,2,3,4,5,6,7,8,9,A-10,B-11,C-12,D-13,E-14,F-15).
Ex:- F3(16)
F 3 = 15 * 16 + 3 * 1 = 240 + 3 = 243(10).
161 160
CONVERSIONS
Decimal to Binary:
1) 36 2 | 36
2 | 18 - 0
2|9 -0
2|4 -1
2|2 -0
|1 -0
So binary equalent of 36(10) is ( 1 0 0 1 0 0 )(2)
2) 41 2 | 41
2 | 20 - 1
2 | 10 - 0
2| 5 -1
2|2 -1
|1 -0
1) 36.12(10) 2 | 36
2 | 18 - 0
2|9 -0
2|4 -1
2|2 -0
|1 -0
0.12 * 2 = 0.24
0.24 * 2 = 0.48
--------------------
0.92 * 2 = 1.84
0.84 * 2 = 1.68
2) 14. 625(10) 2 | 14
2| 7 -0
2| 3 -0
| 1 -1
0.625 * 2 = 1.25
0.25 * 2 = 0.50
Binary to Decimal:
1) (1 0 0 1 0 0 )(2)
1 0 0 1 0 0
25 24 23 22 21 20
1 * 32 + 0 + 0 + 1 * 4 + 0 + 0 = 32 + 4 = 36(10).
2) (1 0 0 0 0 1 )(2)
1 0 0 0 0 1
25 24 23 22 21 20
1 * 32 + 0 + 0 + 0 + 0 + 1 * 1 = 32 + 1 = 33(10) .
1) 72(8) - ( 1 1 1 0 1 0)(2)
2) 64(8) - ( 1 1 0 1 0 0)(2)
1) (101 100 011 010 111 . 111 100 000 110 )(2) = 54327.7406(8)
5 4 3 2 7 7 4 0 6
3 4 1 1
5 F 1 A E 3
2) ( 101 1010 1110 . 1100 0010 )(2) = 5AE . C2(16)
5 A E C 2
Algorithm:
■ An algorithm is a set of well-defined instructions in sequence to solve a problem.
3. Develop an algorithm
Pseudocode& Algorithm
Example 1: Write an algorithm to determine a student’s final grade and indicate whether it is
passing or failing. The final grade is calculated as the average of four marks.
Pseudocode:
Input a set of 4 marks
Calculate their average by summing and dividing by 4
if average is below 50
Print “FAIL”
else
Print “PASS”
Detailed Algorithm
Step 1: Input M1,M2,M3,M4
Step 2: GRADE (M1+M2+M3+M4)/4
Step 3: if (GRADE < 50) then
Print “FAIL”
else
Print “PASS”
endif
The Flowchart
(Dictionary) A schematic representation of a sequence of operations, as in a
manufacturing process or computer program.
(Technical) A graphical representation of the sequence of operations in an information
system or program.
Information system flowcharts show how data flows from source documents through the
computer to final distribution to users.
Program flowcharts show the sequence of instructions in a single program or subroutine.
Different symbols are used to draw each type of flowchart.
A Flowchart
shows logic of an algorithm
emphasizes individual steps and their interconnections
e.g. control flow from one action to the next
Algorithm :
Pseudocode:
Function LengthCovert(length) :
Input Lft
Lcm Lft x 30
Print (Lcm)
Example3: Write an algorithm, Pseudocode and draw a flowchart
that will read the two sides of a rectangle and calculate its area.
Algorithm:
Step3) Print A
Pseudocode:
Input W,L
AL x W
Print (A)
Algorithm to find all the roots of a quadratic equation:
Step 1. Start
Step 2. Read the coefficients of the equation, a, b and c from the user.
Step 6. Else:
Step 7. Stop
C Language Evolution:
C programming language was developed in 1972 by Dennis Ritchie at bell laboratories of
AT&T (American Telephone & Telegraph), located in the U.S.A.
Dennis Ritchie is known as the founder of the c language.
It was developed to overcome the problems of previous languages such as B, BCPL, etc.
Initially, C language was developed to be used in UNIX operating system. It inherits many
features of previous languages such as B and BCPL.
Let's see the programming languages that were developed before C language.
C is the widely used language. It provides many features that are given below.
1. Simple
2. Machine Independent or Portable
3. Mid-level programming language
4. structured programming language
5. Rich Library
6. Memory Management
7. Fast Speed
8. Pointers
9. Recursion
10. Extensible
1) Simple
C is a simple language in the sense that it provides a structured approach (to break the problem
into parts), the rich set of library functions, data types, etc.
5) Rich Library
C provides a lot of inbuilt functions that make the development fast.
6) Memory Management
It supports the feature of dynamic memory allocation. In C language, we can free the allocated
memory at any time by calling the free() function.
7) Speed
The compilation and execution time of C language is fast since there are lesser inbuilt functions
and hence the lesser overhead.
8) Pointer
C provides the feature of pointers. We can directly interact with the memory by using the
pointers. We can use pointers for memory, structures, functions, array, etc.
9) Recursion
In C, we can call the function within the function. It provides code reusability for every
function. Recursion enables us to use the approach of backtracking.
10) Extensible
C language is extensible because it can easily adopt new features.
Structure and execution of a C program
Documentation section
It includes the statement specified at the beginning of a program, such as a program's name,
date, description, and title. It is represented as:
//name of a program
Or
/*
*/
Both methods work as the document section in a program. It provides an overview of the
program. Anything written inside will be considered a part of the documentation section and will
not interfere with the specified code.
Preprocessor section
The preprocessor section contains all the header files used in a program. It informs the system to
link the header files to the system libraries. It is given by:
#include<stdio.h>
#include<conio.h>
The #include statement includes the specific file as a part of a function at the time of the
compilation. Thus, the contents of the included file are compiled along with the function being
compiled.
The #include<stdio.h> consists of the contents of the standard input output files, which
contains the definition of stdin, stdout, and stderr.
Whenever the definitions stdin, stdout, and stderr are used in a function, the statement
#include<stdio.h> need to be used.
Define section
The define section comprises of different constants declared using the define keyword. It is given
by:
#define a = 2
Global declaration
The global section comprises of all the global declarations in the program. It is given by:
char = 1 byte
float = 4 bytes
int = 4 bytes
We can also declare user defined functions in the global variable section.
Main function
main() is the first function to be executed by the computer. It is necessary for a code to include
the main().
It is like any other function available in the C library. Parenthesis () are used for passing
parameters (if any) to a function.
main()
1. The void main() specifies that the program will not return any value.
2. The int main() specifies that the program can return integer type data.
int main()
Or
void main()
Main function is further categorized into local declarations, statements, and expressions.
Local declarations
The variable that is declared inside a given function or block refers to as local declarations.
main()
int i = 2;
i++;
Statements
The statements refers to if, else, while, do, for, etc. used in a program within the main function.
Expressions
An expression is a type of formula where operands are linked with each other by the use of
operators. It is given by:
a - b;
a +b;
The user defined functions specified the functions specified as per the requirements of the
user.
The program (basic or advance) follows the same sections as listed above.
Return function is generally the last section of a code. But, it is not necessary to include. It is
used when we want to return a value. The return function returns a value when the return type
other than the void is specified with the function.
Return type ends the execution of the function. It further returns control to the specified calling
function. It is given by:
1. return;
Or
1. return expression ;
For example,
return 0;
Examples
Let's begin with a simple program in C language.
It is given by:
The c compilation process converts the source code taken as input into the object code or
machine code. The compilation process can be divided into four steps, i.e., Pre-processing,
Compiling, Assembling, and Linking.
The preprocessor takes the source code as an input, and it removes all the comments from the
source code. The preprocessor takes the preprocessor directive and interprets it. For example,
if <stdio.h>, the directive is available in the program, then the preprocessor interprets the
directive and replace this directive with the content of the 'stdio.h' file.
The following are the phases through which our program passes before being transformed into an
executable form:
o Preprocessor
o Compiler
o Assembler
o Linker
Preprocessor
The source code is the code which is written in a text editor and the source code file is
given an extension ".c". This source code is first passed to the preprocessor, and then the
preprocessor expands this code. After expanding the code, the expanded code is passed to
the compiler.
Compiler
The code which is expanded by the preprocessor is passed to the compiler. The
compiler converts this code into assembly code. Or we can say that the C compiler
converts the pre-processed code into assembly code.
Assembler
The assembly code is converted into object code by using an assembler. The name of
the object file generated by the assembler is the same as the source file. The
extension of the object file in DOS is '.obj,' and in UNIX, the extension is 'o'.
If the name of the source file is 'hello.c', then the name of the object file would be
'hello.obj'.
Linker
Mainly, all the programs written in C use library functions. These library functions
are pre-compiled, and the object code of these library files is stored with '.lib' (or '.a')
extension. The main working of the linker is to combine the object code of library
files with the object code of our program. Sometimes the situation arises when our
program refers to the functions defined in other files; then linker plays a very
important role in this.
It links the object code of these files to our program. Therefore, we conclude that the
job of the linker is to link the object code of our program with the object code of the
library files and other files.
In DOS, the extension of the executable file is '.exe', and in UNIX, the executable file
can be named as 'a.out'.
For example, if we are using printf() function in a program, then the linker adds its
associated code in an output file.
Loader
Loader is responsible for loading the binary code into system's primary memory
(RAM) and its execution. After completing the execution, the output is shown on
console.
hello.c
#include <stdio.h>
int main()
printf("Hello javaTpoint");
return 0;
o Firstly, the input file, i.e., hello.c, is passed to the preprocessor, and the preprocessor
converts the source code into expanded source code. The extension of the expanded
source code would be hello.i.
o The expanded source code is passed to the compiler, and the compiler converts this
expanded source code into assembly code. The extension of the assembly code
would be hello.s.
o This assembly code is then sent to the assembler, which converts the assembly code
into object code.
o After the creation of an object code, the linker creates the executable file. The loader
will then load the executable file for the execution.
C Character set
As every language contains a set of characters used to construct words, statements, etc., C
language also has 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 set. C language character set
contains the following set of characters...
1. Alphabets
2. Digits
3. Special Symbols
Alphabets
C language supports all the alphabets from the English language. Lower and upper case letters
together support 52 alphabets.
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 verticaltab etc.,
Every character in C language has its equivalent ASCII (American Standard Code for Information
Interchange) value.
individual units. Every smallest individual unit of a c program is called token. Every instruction
in a c program is a collection of tokens. Tokens are used to construct c programs and they are
said to the basic building blocks of a c program.
1. Keywords
2. Identifiers
3. Operators
4. Special Symbols
5. Constants
6. Strings
C Keywords
As every language has words to construct statements, C programming also has words with a
specific meaning which are used to construct c program instructions. In the C programming
language, keywords are special words with predefined meaning. Keywords are also known as
Keywords are the reserved words with predefined meaning which already known to the
compiler
Properties of Keywords
1. All the keywords in C programming language are defined as lowercase letters so they
2. Every keyword has a specific meaning, users can not change that meaning.
3. Keywords can not be used as user-defined names like variable, functions, arrays,
pointers, etc...
The following table specifies all the 32 keywords with their meaning...
C Identifiers
In C programming language, programmers can specify their name to a variable, array, pointer,
function, etc... An identifier is a collection of characters which acts as the name of variable,
function, array, pointer, structure, etc... In other words, an identifier can be defined as the user-
defined name to identify an entity uniquely in the c programming language that name may be
of the variable name, function name, array name, pointer name, structure name or a label.
program execution
Example
int marks;
char studentName[30];
underscore.
3. We should not use any special symbols in between the identifier even whitespace.
5. There is no limit for the length of an identifier. However, the compiler considers the first
31 characters only.
2. Since starting with an underscore may create conflict with system names, so we avoid
3. We start every identifier with a lowercase letter. If an identifier contains more than one
word then the first word starts with a lowercase letter and second word onwards first
letter is used as an UPPERCASE letter. We can also use an underscore to separate
C operators
An operator is a symbol used to perform arithmetic and logical operations in a program. That
means an operator is a special symbol that tells the compiler to perform mathematical or
logical operations. C programming language supports a rich set of operators that are classified
as follows.
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
5. Assignment Operators
6. Bitwise Operators
7. Conditional Operator
8. Special Operators
+ Addition 10 + 5 = 15
- Subtraction 10 - 5 = 5
* Multiplication 10 * 5 = 50
/ Division 10 / 5 = 2
⇒ The addition operator can be used with numerical data types and character data type. When
it is used with numerical values, it performs mathematical addition and when it is used with
character data type values, it performs concatination (appending).
⇒ The remainder of the division operator is used with integer data type only.
< Returns TRUE if the first value is smaller than second value 10 < 5 is
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
Operato
r Meaning Example
⇒ Logical AND - Returns TRUE only if all conditions are TRUE, if any of the conditions is FALSE
then complete condition becomes FALSE.
⇒ Logical OR - Returns FALSE only if all conditions are FALSE, if any of the conditions is TRUE
then complete condition becomes TRUE.
The increment and decrement operators are used infront of the operand (++a) or after the
operand (a++). If it is used infront 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.
Example Program
#include<stdio.h>
#include<conio.h>
void main(){
int i = 5,j;
j = ++i; // Pre-Increment
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.
Example Program
#include<stdio.h>
#include<conio.h>
void main(){
int i = 5,j;
j = i++; // Post-Increment
}
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.
Operato Exampl
r Meaning e
+= Add both left and right-hand side values and store the A +=
result into left-hand side variable 10
⇒A=
A+10
Operato
r Meaning Example
& the result of Bitwise AND is 1 if all the bits are 1 otherwise it is 0 A&B
⇒ 16
(10000)
Operato
r Meaning Example
^ the result of Bitwise XOR is 0 if all the bits are same otherwise it A^B
is 1 ⇒ 13
(01101)
<< the Bitwise left shift operator shifts all the bits to the left by the A << 2
specified number of positions ⇒ 100
(1100100
)
>> the Bitwise right shift operator shifts all the bits to the right by A >> 2
the specified number of positions ⇒6
(00110)
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.
Example
A = (10<15)?100:200; ⇒ A value is 100
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
int main()
{
// Integer value with positive data.
int a = 9;
return 0;
}
Example Programs 2:
// C program to print Integer data types.
#include <stdio.h>
int main()
{
char a = 'a';
char c;
a++;
printf("Value of a after increment is: %c\n", a);
return 0;
}
Example Program 3:
// C Program to demonstrate use
// of Floating types
#include <stdio.h>
int main()
{
float a = 9.0f;
float b = 2.5f;
// 2x10^-4
float c = 2E-4f;
printf("%f\n", a);
printf("%f\n", b);
printf("%f", c);
return 0;
}
Example Program 4:
// C Program to demonstrate
// use of double data type
#include <stdio.h>
int main()
{
double a = 123123123.00;
double b = 12.293123;
double c = 2312312312.123123;
printf("%lf\n", a);
printf("%lf\n", b);
printf("%lf", c);
return 0;
}
Size of Data Types in C
The size of the data types in C is dependent on the size of the architecture, so we cannot
define the universal size of the data types. For that, the C language provides the sizeof()
operator to check the size of the data types.
// C Program to print size of
// different data type in C
#include <stdio.h>
int main()
{
int size_of_int = sizeof(int);
int size_of_char = sizeof(char);
int size_of_float = sizeof(float);
int size_of_double = sizeof(double);
return 0;
}
Expression Example:
c=a+b
a-b+c
a+b-(a*c)
Types of Expressions in C
Arithmetic expressions
Relational expressions
Logical expressions
Conditional expressions
Arithmetic Expressions:
From the given above arithmetic expressions example, let's consider the values of
operands to be a=2,b=3, and c=4.
Z = 2 + 3 - (2 * 4)
Step 2: The next level of precedence is given to + and - operator, so next a+b (2+3
= 5) is evaluated
Step 4: The final value after evaluation of an arithmetic expression will be stored
into the variable Z, according to the example value three is stored into the variable
Z that is z = -3
#include <stdio.h>
void main()
int a=2,b=3,c=4,z;
z=a+b-(a*c);
printf("Result= %d",z);
Relational Expressions
o A relational expression is an expression used to compare two operands.
o It is a condition which is used to decide whether the action should be taken
or not.
o In relational expressions, a numeric value cannot be compared with the
string value.
o The result of the relational expression can be either zero or non-zero value.
Here, the zero value is equivalent to a false and non-zero value is equivalent
to true.
Relational Description
Expressio
n
a+b = = x+y It is used to check whether the expression "a+b" is equal to the
expression "x+y".
#include <stdio.h>
int main()
{
int x=4;
if(x%2==0)
{
printf("The number x is even");
}
else
printf("The number x is not even");
return 0;
}
Logical Expressions
o A logical expression is an expression that computes either a zero or non-zero
value.
o It is a complex test condition to take a decision.
Logical Description
Expression
s
( x > 4 ) && ( It is a test condition to check whether the x is greater than 4 and
x<6) x is less than 6. The result of the condition is true only when
both the conditions are true.
Conditional Expressions
o A conditional expression is an expression that returns 1 if the condition is
true otherwise 0.
o A conditional operator is also known as a ternary operator.
From the given above expressions, the first expression (exp1) is conditional, and if
the condition is satisfied, then expression2 will be executed; otherwise,
expression3 will be performed.
Example:
2<3? 2 : 3
From the given below conditional expressions example, let's consider the values of
operands to be a=5, b=3, and c=1.
After substitution of values into the given expression, we get:
Step 2: Next, it checks whether the condition is satisfied, a*b < c (15 > 1), false.
Step 3: Since the condition is false, expression3 will be executed and return the
value one as an output stored in the variable Z.
void main()
z = (5 * 3) < 1 ? 1 : 0;
printf("Result = %d",z);
Output:
Expressions are evaluated by the ‘C’ compiler based on precedence and associativity
rules.
If an expression contains different priority operators, then the precedence rules are
considered.
Here, 10*2 is evaluated first since ‘*’ has more priority than ‘- ‘and ‘=’
If an expression contains same priority, then associativity rules are considered i.e. left
right (or right to left).
DECLARATION OF VARIABLES
A variable is a name of the memory location. It is used to store data. Its value can be changed,
and it can be reused many times.
It is a way to represent memory location through symbol so that it can be easily identified.
syntax:
int a;
float b;
char c;
Here, a, b, c are variables. The int, float, char are the data types.
We can also provide values while declaring the variables as given below:
2. float f=20.8;
3. char c='A';
✔ Except underscore, No special character is allowed within the variable name.( every
character other than alphabets, digits is a special character)
✔ A variable name must not be any reserved word or keyword, e.g. int, float, etc.
✔ int a;
✔ int _ab;
✔ int a30;
✔ int 2;
✔ int a b;
Variable Declaration in C
✔ variable declaration provides assurance to the compiler that there exists a variable
with the given type and name so that the compiler can proceed for further
compilation without requiring the complete detail about the variable. A variable
definition has its meaning at the time of compilation only, the compiler needs
actual variable definition at the time of linking the program.
The values of some variable may be required to remain constant through-out the program. We
can do this by using the qualifier const at the time of initialization.
Example:
The const data type qualifier tells the compiler that the value of the int variable class_size may
not be modified in the program.
#include <stdio.h>
int main() {
// Create variables
int myNum = 15; // Integer (whole number)
float myFloatNum = 5.99; // Floating point number
char myLetter = 'D'; // Character
// Print variables
printf("%d\n", myNum);
printf("%f\n", myFloatNum);
printf("%c\n", myLetter);
return 0;
}
Assignment statements:
Syntax
The symbol used in an assignment statement is called as an operator.
The symbol is ‘=’.
variable = expression ;
where,
variable = variable name
Example –
int a = 50 ;
float b ;
a = 25 ;
b = 34.25f ;
int RollNo = 25 ;
printf("%d",RollNo);
There are some library functions which are available for transferring the information
between the computer and the standard input and output devices.
These functions are related to the symbolic constants and are available in the header
file.
i) printf
This function is used for displaying the output on the screen i.e the data is moved
from the computer memory to the output device.
Syntax:
printf(“format string”, arg1, arg2, …..);
In the above syntax, 'format string' will contain the information that is formatted. They
are the general characters which will be displayed as they are .
arg1, arg2 are the output data items.
Example: Demonstrating the printf function
printf(“Enter a value:”);
ii) scanf
scanf is used when we enter data by using an input device.
Syntax:
scanf (“format string”, &arg1, &arg2, …..);
Format string consists of the conversion specifier. Arguments can be variables or array
name and represent the address of the variable. Each variable must be preceded by an
ampersand (&). Array names should never begin with an ampersand.
iii) getch
This function is used to input a single character. The character is read instantly and it
does not require an enter key to be pressed. The character type is returned but it does
not echo on the screen.
Syntax:
int getch(void);
ch=getch();
where,
ch - assigned the character that is returned by getch.
iv) putch
this function is a counterpart of getch. Which means that it will display a single
character on the screen. The character that is displayed is returned.
Syntax:
int putch(int);
putch(ch);
where,
ch - the character that is to be printed.
v) getche
This function is used to input a single character. The main difference between getch
and getche is that getche displays the (echoes) the character that we type on the
screen.
Syntax:
int getch(void);
ch=getche();
vi) getchar
This function is used to input a single character. The enter key is pressed which is
followed by the character that is typed. The character that is entered is echoed.
Syntax:
ch=getchar;
vii) putchar
This function is the other side of getchar. A single character is displayed on the screen.
Syntax:
putchar(ch);
Example:
#include <stdio.h>
void main()
{
char line[30];
gets (line);
puts (line);
}
Type conversions:
Type conversion occurs when an expression has a mixed data types. At this time,
the compiler will try to convert from lower to higher type, because converting from
higher to lower may cause loss of precision and value. C has following rules for
type conversion.
● Integer types are lower than floating-point types.
● Signed types are lower than unsigned types.
● Short whole-number types are lower than longer types.
● The hierarchy of data types is as follows: double, float, long, int, short, char.
Conversion Type Casting
Result type of arithmetic expression depends on operand types inside it. When an
expression is consisted of various data types, result type is set by defined casting
rules. There are two ways of casting data types in C:
·Automatic (implicit)
·Given (explicit)
short int ->int ->unsigned int ->long int ->unsigned long int ->float ->double -
>long double
For example:
main()
float a;
a = (float)5 / 3;
gives result as 1.666666 . This is because the integer 5 is converted to floating point value before
division and the operation between float and integer results in float.
main()
long int c = a * b ;
}
Here two integers are multiplied and the result is truncated and stored in variable c
of type long int. But this would not fetch correct result for all. To get a more
desired output the code is written as long int c = (long int) a * b;