Académique Documents
Professionnel Documents
Culture Documents
Unit - 1
Introduction
Computer Systems
Computer is the word which is derived from a Latin word Compute which is nothing but
calculate.
A computer is an independent machine containing:
CPU + ALU + Memory + Input + Output + Storage
Definitions of Computer
1. Computer is an electronic device which can perform arithmetic and logical operations and
stores the data.
2. A Computer is an electronic device that executes the instructions in a program or in other
words.
3. A device that computes especially a programmable electronic machine that performs high-
speed mathematical or logical operations and stores the data.
Beginning Terms of Computers:
• Hardware: the physical parts of the computer
• Software: The programs that tells the computer what to do. The set of Programs is called the
Software
• Data: It is collection of raw facts and figures
• Information: data which has been massaged into a useful form that is the processed data
which is called as Information.
• Program: A set of instructions which are given in a sequence order to perform the specific
operation.
• Output: The information or result which is given by the computer.
• Instruction: It is the command given to the Computer.
A computer system has Four Functions. They are
1. Accepts Data (Accept)
2. Processes Data (Process)
3. Produces Output (Output)
4. Stores Results (Store)
Input:
Everything we tell to the computer is Input
• Data is the raw facts given to the computer.
• Programs are the set of instructions that given to the computer.
A Simple Computer
The above systems are called as Von-Neumann computers, or Serial Computers. Parallel
computers are non Von-Neumann type as they contain more than one processor, RAM.
The following are the different ware’s available.
1. Hardware: Materialistic thing which we can touch and feel.
2. Software: Ideological things which we cannot perceive and feel.
3. Firmware: It is a fixed and small program that internally controls various electronics
devices. POST software is Read only Memory is the example of firmware.
4. Freeware: Software which can use it freely.
5. Shareware: It is software which we can use for some time freely.
Some Novice HW Concepts:
Processor:
The processors are rated as 2.6GHz, 3GHz, etc., These numbers really convey the clock rate
at which the processor can work at most. They do not really convey the actual computational speed
of the computer. That is in terms of operations per second. The actual speed will be much smaller
than these numbers.
Computers use some elementary operations known as micro operations while executing the
user’s instruction. For example to execute the statement a=b+c, the following steps may be needed.
• b value has to be fetched from RAM to CPU
• c value has to be fetched from RAM to CPU
• Plus operation has to be performed.
• Results has to stored back in a, which is in the RAM
Coding:
After developing the algorithm and flow chart then we can start coding for the particular
problem. Here the algorithm and flowchart is common for all the programming languages. But the
coding is different from one programming language to another programming language. So here we
will see how the coding will done using ‘C’ Language.
Coding of program is usually accomplished by one or two possible methods, the most
common being the use of an editor. Some editors are line-oriented, while others are character-
oriented (full-screen editors). Some editors include both full-screen features and line-oriented
commands. UNIX operating system has ed, vi editors and TURBO C gives an menu driven interface
with many options.
Their IDE (Integrated Development Environment) puts all the tools you need for C program
development into a single, convenient screen display. Program files are saved with the extension .c
like test.c, add.c. There are several such IDEs available in the market targeted towards different
operating systems. For example, Turbo C, Turbo C++ and Microsoft C are some of the popular
compilers that work under MS-DOS. And we can use the common editors like notepad, word pad in
Microsoft Windows operating systems.
Using Notepad
Notepad is a basic text editor you can use for simple documents or for creating Web pages.
Here we can create or edit files. To open Notepad, click Start, point to All Programs, point to
Accessories, and then click Notepad.
The above program we have to write in Turbo C editor. That looks like this
So in the above picture it shows that statement missing in function main. Now we need to
give the semicolon after the printf statement then again save the file and compile the file.
Compiling:
After saving the file we need to compile the compile. For compilation in Turbo C editor we
have to press Alt + F9. Then the file will be compiled by the compiler if there are no syntactical
errors in the program. After compiling the file we will get .obj file. If there are any errors in the
program then the file won’t be compiled and it will not be converted into .obj file. So for compiling
the file you need to press Alt + F9 or click on the compile menu on the menu bar then choose the
option called compile to OBJ. See the following picture.
After executing the above program then we will get .exe file. When we are executing the
above program then we will get the output as shown in below picture. To see the output we need to
press Alt + F5. Then the output looks like this.
C Language Usages:
‘C’s ability to communicate directly with hardware makes it a powerful choice for system
programmers. And the popular operating systems such as Unix and Linux are written entirely in C.
Additionally, even compilers and interpreters for other languages such as FORTRAN, Pascal, and
BASIC are written in C. However, C’s scope is not just limited to developing system programs. It is
also used to develop any kind of application, including complex business ones.
The following is a partial list of areas where C language is used:
C Programming Study Material Page No. 19
Unit – 1
• Embedded Systems
• Systems Programming
• Artificial Intelligence
• Industrial Automation
• Computer Graphics
• Space Research
• Image Processing
• Game Programming
‘C’ Language is a Structure Programming Language:
C is a structured programming language, which means that it allows you to develop programs
using well-defined control structures, and provides modularity (breaking the task into multiple sub
tasks that are simple enough to understand and to reuse). C is often called a middle-level
language because it combines the best elements of low-level or machine language with high-level
languages.
Advantages of ‘C’ Language:
The ‘C’ Language is a very powerful language. And it is very easy to learn and write
programs. And the other advantages of the ‘C’ language are
• C is simple.
• There are only 32 keywords so C is very easy to master. Keywords are words that have
special meaning in C language.
• C programs run faster than programs written in most other languages.
• C enables easy communication with computer hardware making it easy to write system
programs such as compilers and interpreters.
• The big plus is that it is possible to do everything in 'C' while other languages make you to
write a procedure, subroutine or function in assembler code.
• 'C' has very good facilities for creating tables of constant data within the source file.
• 'C' is a small language with very few essential operations. All the heavy work is done by
explicit library function calls.
• 'C' allows you directly and conveniently access most of the internals of the machine (the
memory, input output slots, and CPU registers) from the language without having to resort to
assembler code.
• 'C' compilers have an optimization phase which can be invoked if desired. The output code
can be optimized for either speed or memory usage. The code will be just as good as that
produced by an assembly code programmer of normal skill real guru programmers can do
only slightly better.
Preprocessor directives
Global Variables Declaration
void main()
{
Local variables declaration
Executable Statements & Expressions
}
Return type subfunction (arguments)
{
Local variables declaration
Statements & Expressions
}
Preprocessor directives are lines included in the code of our programs that are not program
statements but directives for the preprocessor. These lines are always preceded by a hash sign (#).
The preprocessor is executed before the actual compilation of code begins, therefore the preprocessor
digests all these directives before any code is generated by the statements. Example of this
preprocessor directive is #include<stdio.h>.
These preprocessor directives extend only across a single line of code. As soon as a newline
character is found, the preprocessor directive is considered to end. No semicolon (;) is expected at
the end of a preprocessor directive. The only way a preprocessor directive can extend through more
than one line is by preceding the newline character at the end of the line by a backslash (\).
The variables which we are declaring before the main function are called as global variables.
These variables can be used in all the functions in the entire program.
The function main is very important, and must appear once, and only once in every C
program. This is the point where execution is begun when the program is run. Following the main
program name is a pair of parentheses which are an indication to the compiler that this is a function.
The two curly brackets are called as braces, are used to define the limits of the program itself. The
actual program statements go between the two braces and in this case, there are no statements
because the program does absolutely nothing.
C Tokens:
In a C source program, the basic element recognized by the compiler is the "token." A token
is source-program text that the compiler does not break down into component elements. C tokens
include keywords, identifiers, constants, strings, special symbols & operators. Punctuation characters
such as brackets ([ ]), braces ({ }), parentheses ( ( ) ), and commas (,) are also tokens.
Identifiers
Identifiers, or names, refer to a variety of things: functions, tags of structures, unions, and
enumerations, members of structures or unions, enumeration constants, typedef names, and objects.
An object, sometimes called a variable, is a location in storage, and its interpretation depends on two
main attributes: its storage class and its type.
In the C programming language, an identifier is a combination of alphanumeric characters,
the first being a letter of the alphabet or an underline, and the remaining being any letter of the
alphabet, any numeric digit, or the underline. Two rules must be kept in mind when naming
identifiers.
• The case of alphabetic characters is significant. Using INDEX for a variable name is not the
same as using index and neither of them is the same as using InDeX for a variable name. All
three refer to different variables.
• Don’t give the space in between the identifier. Better to use an underline character instead of
space. Example: don’t give as student no, you have to declare as student_no.
Examples of identifiers:
The size and range of each data type is given in the table below
DATA TYPE RANGE OF VALUES
char -128 to 127
int -32768 to +32767
float 3.4 e-38 to 3.4 e+38
double 1.7 e-308 to 1.7 e+308
Integer Type:
Integers are whole numbers with a machine dependent range of values. C has 3 classes of
integer storage namely short int, int and long int. All of these data types have signed and unsigned
forms. A short int requires half the space than normal integer values. Unsigned numbers are always
positive and consume all the bits for the magnitude of the number. The long and unsigned integers
are used to declare a longer range of values.
Floating Point Types:
Floating point number represents a real number with 6 digits precision. Floating point
numbers are denoted by the keyword float. When the accuracy of the floating point number is
insufficient, we can use the double to define the number. The double is same as float but with longer
precision. To extend the precision further we can use long double which consumes 80 bits of
memory space.
Keywords:
Every word in C language is a keyword or an identifier. Keywords in C language cannot be
used as a variable name. They are specifically used by the compiler for its own purpose and they
serve as building blocks of a c program. The following are the Keyword set of C language.
.auto Double .int .struct
.break .else .long .switch
.case .enum .register .typedef
.char .extern .return .union
.const .float .short .unsigned
.continue .for .signed .void
.default .goto .size of .volatile
.do .if .static .while
The scanf() function is used to read data from the keyboard. And it needs two things.
1. What type of data and how many data it has to take from the keyboard. This is specified with
a format string according to the rules given in the following table. It we want to instruct
scanf() to read four float values then, we have to give “%f %f %f %f” as the first argument.
2. Where to store the values which are read from the keyboard. That is, we are required to
supply memory locations where the data has to stored. This is achieved by using the address
operator &. If we want to read data into variable v, we have to say &v. Here v is a variable,
&v is the address or memory location of that variable. So we have to supply address of the
variable after the format specifier.
The following are the various format specifiers and their meaning:
%c Print a character
%d Print a Integer
%i Print a Integer
%e Print float value in exponential form.
%f Print float value
%g Print using %e or %f whichever is smaller
%o Print actual value
%s Print a string
%x Print a hexadecimal integer (Unsigned) using lower case a – f
%X Print a hexadecimal integer (Unsigned) using upper case A – F
%a Print a unsigned integer.
%p Print a pointer value
%hx hex short
%lo octal long
%ld long
%% Outputs a percent sign.
The /* .... */ and // comments and will not be executed, the compiler simply ignores these
statements. These are essential since it enhances the readability and understandability of the
program. It is a very good practice to include comments in all the programs to make the users
understand what is being done in the program.
Though comments are not necessary, it is a good practice to begin a program with a comment
indicating the purpose of the program, its author and the date on which the program was written.
Any number of comments can be written at any place in the program. For example, a comment can
be written before the statement, after the statement or within the statement.
The normal language rules do not apply to text written within /* .. */. Thus we can type this
text in small case, capital or a combination. This is because the comments are solely given for the
understanding of the programmer or the fellow programmers and are completely ignored by the
compiler.
Comments cannot be nested.
Example: /* Cal of SI /* Author date 01/01/2010 */ */ is invalid.
Operator Meaning
+ Addition or Unary Plus
– Subtraction or Unary Minus
* Multiplication
/ Division
% Modulus Operator for remainder
Output
Please Enter Two Numbers :: 10 5
The sum is = 15
The difference is = 5
The product is = 50
The division is = 2.0
The modulus is = 0
Integer Arithmetic:
When an arithmetic operation is performed on two whole numbers or integers than such an
operation is called as integer arithmetic. It always gives an integer as the result. Let x = 27 and y = 5
be 2 integer numbers. Then the integer operation leads to the following results.
x + y = 32
x – y = 22
x * y = 115
x%y=2
x/y=5
Relational Operators
Often it is required to compare the relationship between operands and bring out a decision
and program accordingly. This is when the relational operator comes into picture. Relational
operators are also binary operators. That is they need two operands. The result of relational operator
will be true or false, numerically 1 or 0. C supports the following relational operators.
Operator Meaning
< is less than
<= is less than or equal to
> is greater than
>= is greater than or equal to
== is equal to
!= is not equal to
If you want to compare a and b for equality then you should write a == b, not a = b because a
= b means you are assigning the value of b to a. It is required to compare the marks of 2 students,
salary of 2 persons then we can use the relational operators. A simple relational expression contains
only one relational operator and takes the following form.
exp1 relational operator exp2
Logical Operators
C has the following logical operators; they compare or evaluate logical and relational
expressions.
A B A && B A || B
Operator Meaning
T T T T
&& Logical AND
T F F T
|| Logical OR
F T F T
! Logical NOT F F F F
Assignment Operators
The Assignment Operator evaluates an expression on the right of the expression and
substitutes it to the value or variable on the left of the expression.
Example Statement with simple Statement with
x=a+b assignment operator shorthand operator
Here the value of a + b is evaluated a=a+1 a += 1
main( )
{
int a,b,c,d;
printf("ENTER VALUES OF a, b, c, d");
scanf("%d %d %d %d",&a,&b,&c,&d);
a += b*c+d;
printf("\n a = %d",a);
}
Input
a = 5, b= 5, c = 7, d = 8.
Output
ENTER VALUES OF a, b, c, d
5578
a = 48
{
int i=10, j, k; First i value is incremented by one and then this
modified value is assigned to k.
j = i++;
printf(“%d %d”, i, j);
k = ++i;
printf(“%d %d”, i, k);
}
Output: i = 11, j = 10, i = 12, k = 12;
Conditional Operators
C language supports another type of operator known as conditional operator or compact if.
This is a ternary operator. So it needs 3 operands. This operator can be used in either of the following
styles.
1. (expr) ? expr1 : expr2;
2. var = (expr) ? expr1 : expr2;
In the first style, expr1 will be evaluated if expr is true else expr2 will be evaluated. Where
as in the second style, expr1 is evaluated if expr is true and its value is assigned to var. otherwise the
value of expr2 will be assigned to var.
Note: In C language any value if it is positive or negative is logically considered as true. And only
zero will be logically considered as false. So true means numerical value is 1 and false is 0.
Example Program:
main()
{
int y;
printf(" ENTER A YEAR ");
scanf("%d",&y);
((y%400==0)||((y%4==0)&&(y%100!=0)))?printf(" LEAP YEAR "):
printf(" NOT A LEAP YEAR ");
}
C Programming Study Material Page No. 37
Unit – 1
Here we used both conditional operator and logical operators also. || and && are the logical
operators we used here. And in that expression if that is true then the first printf() statement will
execute, that means the LEAP YEAR will be displayed on console. Otherwise the second printf()
statement will be executed, that means NOT A LEAP YEAR will be displayed on console.
Output:
ENTER A YEAR 1999
NOT A LEAP YEAR
ENTER A YEAR 2000
LEAP YEAR
COMMA Operator:
You can combine multiple expressions in a single expression using the comma operator.
Example Program:
main()
{
int i,j,k;
k = (i = 4, j = 5);
printf("k = %d",k);
}
Input
i = 4, j = 5.
Output
k = 5.
For example, you can write: k = (i = 4, j = 5). Here the expression is evaluated from left to
right, that is, i = 4 is evaluated first then j = 5 is evaluated. The value of the rightmost expression is
specified as output, thus k will get the value 5.
Evaluation of Expressions:
Expressions are evaluated using an assignment statement of the form
Variable = expression;
Variable is any valid C variable name. When the statement is encountered, the expression is
evaluated first and then replaces the previous value of the variable on the left hand side. All variables
used in the expression must be assigned values before evaluation is attempted.
Example of evaluation statements are
x=a*b–c
y=b/c*a
z = a – b / c + d;
The following program illustrates the effect of presence of parenthesis in expressions.
main ()
{
float a, b, c x, y, z; a = 9; b = 12; c = 3;
x = a – b / 3 + c * 2 – 1;
y = a – b / (3 + c) * (2 – 1);
z = a – ( b / (3 + c) * 2) – 1;
printf (“x = %f \n”,x);
printf (“y = %f \n”,y);
printf (“z = %f \n”,z);
}
output
x = 10.00
y = 7.00
z = 4.00
Type Conversions
Some times it is required to convert the one data type to another data type. That is called as
type conversion. Type conversion occurs when the expression has data of mixed data types, for
example, converting an integer value into a float value, or assigning the value of the expression to a
variable with different data types.
Implicit type conversion:
C permits mixing of constants and variables of different types in an expression. C
automatically converts any intermediate values to the proper type so that the expression can be
evaluated without losing any significance. This automatic type conversion is known as implicit type
conversion
During evaluation it holds to very strict rules and type conversion. If the operands are of
different types the lower type is automatically converted to the higher type before the operation
proceeds. The result is of higher type.
In type conversion, the data type is promoted from lower to higher because converting higher
to lower involves loss of precision and value. For type conversion, C maintains a hierarchy of data
types using the following rules:
1. Integer types are lower than floating-point types.
2. Signed types are lower than unsigned types.
3. Short whole-number types are lower than longer types.
4. The hierarchy of data types is as follows: double, float, long, int, short, char.
The following rules apply during evaluating expressions:
All short and char are automatically converted to int then
1. If one operand is long double, the other will be converted to long double and result will be
long double.
2. If one operand is double, the other will be converted to double and result will be double.
3. If one operand is float, the other will be converted to float and result will be float.
4. If one of the operand is unsigned long int, the other will be converted into unsigned long int
and result will be unsigned long int.
5. If one operand is long int and other is unsigned int then
Conditional expressions
A conditional expression contains the expression with condition. The following is the syntax
of the conditional expression.
var = (expr) ? expr1 : expr2;
The expression expr1 is evaluated first. If it is non-zero (true), then the expression expr2 is
evaluated, and that is the value of the conditional expression. Otherwise expr3 is evaluated, and that
is the value. Only one of expr1 and expr2 is evaluated. Thus to set z to the maximum of a and b, z =
(a > b) ? a : b; /* z = max(a, b) */
It should be noted that the conditional expression is indeed an expression, and it can be used
wherever any other expression can be. For example, if f is a float and n an int, then the expression (n
> 0) ? f : n is of type float regardless of whether n is positive.
Output:
ENTER TWO NUMBERS :: 4 6
THE MAX NO. :: 6
In the above program the conditional expression is denoted with bold letters. In that first a
compare with b and if a is maximum that is a is greater than b then, a value that is the value
contained by a is assigned to max variable. Otherwise the value contained by b is assigned to max.
This is the program to find out the maximum of two numbers only. The below program is for finding
out maximum no among three numbers.
Example Program:
main()
{
int a,b,c,max;
printf(" ENTER THREE NUMBERS :: "); Conditional Expression
scanf("%d %d %d",&a,&b,&c);
max=((a>b)&&(a>c)?a:(b>c)?b:c);
printf(" THE MAX NO. :: %d",max);
}
Output:
ENTER THREE NUMBERS :: 4 6 3
THE MAX NO. :: 6
There are 4 classes of bitwise operators broadly. They are logical operators, shift operators,
rotation operation and mask operations.
Bitwise Logical Operators
The bitwise AND(&), bitwise OR(|), bitwise XOR(^), bitwise complement(~) operators are
called as bitwise logical operators.
For example:
0101 (decimal 5)
(AND) & 0011 (decimal 3)
= 0001 (decimal 1)
In the C programming language family, the bitwise AND operator is "&" (ampersand).
Again, this operator must not be confused with its Boolean "logical and", which treats its operands as
Boolean values, and is written "&&" (two ampersands).
Bitwise OR Operator:
A bitwise OR takes two bit patterns of equal length, and produces another one of the same
length by matching up corresponding bits and performing the logical inclusive OR operation. And it
compares each bit of its first operand to the corresponding bit of its second operand. If either bit is 1,
the corresponding result bit is set to 1. Otherwise, the corresponding result bit is set to 0.
x y x|y
0 0 0
0 1 1
1 0 1
1 1 1
For example:
0101 (decimal 5)
(OR) | 0011 (decimal 3)
= 0111 (decimal 7)
In the C language family, the bitwise OR operator is "|" (pipe). Again, this operator must not
be confused with its Boolean "logical or", which treats its operands as Boolean values, and is written
"||" (two pipes).
For example:
0101 (decimal 5)
(XOR) ^ 0011 (decimal 3)
= 0110 (decimal 6)
In the C programming language family, the bitwise XOR operator is "^" (caret). Assembly
language programmers sometimes use the XOR operation as a short-cut to set the value of a register
to zero. Performing XOR on a value against itself always yields zero, and on many architectures, this
operation requires fewer CPU clock cycles than the sequence of operations that may be required to
load a zero value and save it to the register.
Bitwise NOT Operator:
The bitwise NOT, or complement, is a unary operation that performs logical negation on each
bit, forming the ones' complement of the given binary value. Digits which were 0 become 1, and 1
become 0. It is a unary operator. Because it needs only one operand.
x ~x
0 1
1 0
For example:
(NOT) ~ 0111(decimal 7)
= 1000 (decimal 8)
In many programming languages, the bitwise NOT operator is "~" (tilde). This operator must
not be confused with the "logical not" operator, "!" (exclamation point), the C language makes a
value of 0 to 1 and a value other than 0 to 0. The "logical not" is not a bitwise operation.
main()
{
int c1,c2,c3;
printf("ENTER VAULES OF c1 and c2");
scanf("%d,%d",&c1,&c2);
c3 = c1 & c2;
printf("\n Bitwise AND i.e. c1 & c2 = %d",c3);
c3 = c1 | c2;
printf("\n Bitwise OR i.e. c1 | c2 = %d",c3);
c3 = c1 ^ c2;
printf("\n Bitwise XOR i.e. c1 ^ c2 = %d",c3);
c3 = ~c1;
printf("\n ones complement of c1 = %d",c3);
}
Input
c1 = 4;
c2 = 6;
Output:
Output:
ENTER THE VALUE OF c1
4
left shift by 2 bits c1 << 2 = 16
right shift by 2 bits c1 >> 2 = 1
Here in the AND mask we keep the value of all other bits as 1 except the one which is to be
switched OFF. Therefore, irrespective of whether the first bit is ON or OFF previously, it is switched
OFF. At the same time the value 1 provided in all the other bits of the AND mask keeps the bit
values of the other bits in the first operand unaltered.