0% found this document useful (0 votes)
346 views102 pages

C Notes

The document describes the basic structure of a C program. It explains that a C program consists of several sections including documentation, link, definition, global declaration, main function, and user defined function definition sections. It provides descriptions of each section and their purposes. It also provides an example C program to demonstrate how these sections are implemented in a basic C program.

Uploaded by

baby
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
Download as doc, pdf, or txt
0% found this document useful (0 votes)
346 views102 pages

C Notes

The document describes the basic structure of a C program. It explains that a C program consists of several sections including documentation, link, definition, global declaration, main function, and user defined function definition sections. It provides descriptions of each section and their purposes. It also provides an example C program to demonstrate how these sections are implemented in a basic C program.

Uploaded by

baby
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1/ 102

Basic structure of C program

Structure of C program is defined by set of rules called protocol, to be followed by programmer while
writing C program. All C programs are having sections/parts which are mentioned below.

1. Documentation section
2. Link Section
3. Definition Section
4. Global declaration section
5. Main function
6. User defined function definition section

Description for each section of a C program:

 Let us see about each section of a C basic program in detail below.


 Please note that a C program mayn’t have all below mentioned sections except main function and
link sections.
 Also, a C program structure mayn’t be in below mentioned order.

S.No Sections Description


We can give comments about the program, creation or modified date, author name
etc in this section. The characters or words or anything which are given between
Documentation
1 “/*” and “*/”, won’t be considered by C compiler for compilation process.These
section
will be ignored by C compiler during compilation.
Example : /* comment line1 comment line2 comment 3 */
2 Link Section Header files that are required to execute a C program are included in this section
3 Definition Section In this section, variables are defined and values are set to these variables.
Global declaration Global variables are defined in this section. When a variable is to be used
4
section throughout the program, can be defined in this section.
Every C program is started from main function and this function contains two
6 Main function
major sections called declaration section and executable section.
User defined User can define their own functions in this section which perform particular task as
7
function section per the user requirement.

Example C program

/* C basic structure program Documentation section


Author: fresh2refresh.com
Date : 01/01/2012
*/#include <stdio.h> /* Link section */
int total = 0; /* Global declaration and definition section */
int sum (int, int); /* Function declaration section */
int main () /* Main function */
{
printf (“This is a C basic program \n”);
total = sum (1, 1);
printf (“Sum of two numbers : %d \n”, total);
return 0;
}
int sum (int a, int b) /* User defined function */
NASC-Department of Computer Applications [Computing Fundamentals and ‘C’ Programming] 1
{ /* definition section */
return a + b;
}           

Output:
This is a C basic program
Sum of two numbers : 2 

C – Tokens

 C tokens, Identifiers and Keywords are the basics in a C program.

C tokens:

 C tokens are the basic buildings blocks in C language which are constructed together to write a C program.
 Each and every smallest individual units in a C program are known as C tokens.

 C tokens are of six types. They are,

C Tokens

Keywords Identifiers Constants Strings Special symbols   Operators  

1. Keywords               (eg: int, while),


2. Identifiers               (eg: main, total),

3. Constants              (eg: 10, 20),

4. Strings                    (eg: “total”, “hello”),

5. Special symbols  (eg: (), {}),

6. Operators              (eg: +, /,-,*)

C tokens example program:

int main()
{
int x, y, total;
x = 10, y = 20;
total = x + y;
Printf (“Total = %d \n”, total);
}                                                                                                 .

where,

 main – identifier
 {,}, (,) – delimiter

 int – keyword

NASC-Department of Computer Applications [Computing Fundamentals and ‘C’ Programming] 2


 x, y, total – identifier

 main, {, }, (, ), int, x, y, total – tokens

    Do you know how to use C token in real time application programs? We have given simple real time
application programs where C token is used. You can refer the below C programs to know how to use C
token in real time program.

Keywords in C language:

 Keywords are pre-defined words in a C compiler.


 Each keyword is meant to perform a specific function in a C program.

 Every C word is either keyword or an identifier.

 Fixed meaning and can’t be changed.

 It serves as basic building blocks for program statements.

 It should be written in lower case letters.

C language supports 32 keywords which are given below.

uto double int struct const float  short unsigned

break else long switch continue  for signed void 

case enum register typedef default goto sizeof  volatile 

char extern return union do    if static  while

Identifiers in C language:

 Each program elements in a C program are given a name called identifiers.


 Names given to identify Variables, functions and arrays are examples for identifiers.

 These are user defined names and consists of a sequence of letters and digits.

 Both lower case and uppercase letters are permitted but lowercase is advisable.

Rules for constructing identifier name in C:

1. First character should be an alphabet or underscore.


2. Succeeding characters might be digits or letter.

3. Punctuation and special characters aren’t allowed except underscore.

4. Identifiers should not be keywords.

Constant in C language:
 C Constants are also like normal variables. But, only difference is, their values can not be modified by the
program once they are defined.
 Constants refer to fixed values. They are also called as literals

 Constants may be belonging to any of the data type.

Syntax:
NASC-Department of Computer Applications [Computing Fundamentals and ‘C’ Programming] 3
const data_type variable_name; (or) const data_type *variable_name;

Types of C constant:
1. Integer constants
2. Real or Floating point constants

3. Octal & Hexadecimal constants

4. Character constants

5. String constants

6. Backslash character constants

S.no Constant type data type Example

int 53, 762, -478 etc 


unsigned int 5000u, 1000U etc
1 Integer constants
long int 483,647
long long int 2,147,483,680

float 10.456789
2 Real or Floating point constants
doule 600.123456789

3 Octal constant int 013          /* starts with 0  */

4 Hexadecimal constant int 0×90        /* starts with 0x */

5 character constants  char ‘A’   ,   ‘B’,     ‘C’

6 string constants char “ABCD”   ,   “Hai”

Constants
 C Constants are also like normal variables. But, only difference is, their values can not be modified by the
program once they are defined.
 Constants refer to fixed values. They are also called as literals

 Constants may be belonging to any of the data type.

Syntax:

const data_type variable_name; (or) const data_type *variable_name;

Types of C constant:

Integer constants
Real or Floating point constants
Octal & Hexadecimal constants
Character constants

NASC-Department of Computer Applications [Computing Fundamentals and ‘C’ Programming] 4


String constants
Backslash character constants

S.no Constant type data type Example

int 53, 762, -478 etc 


unsigned int 5000u, 1000U etc
1 Integer constants
long int 483,647
long long int 2,147,483,680

float 10.456789
2 Real or Floating point constants
doule 600.123456789

3 Octal constant int 013          /* starts with 0  */

4 Hexadecimal constant int 0×90        /* starts with 0x */

5 character constants  char ‘A’   ,   ‘B’,     ‘C’

6 string constants char “ABCD”   ,   “Hai”

Rules for constructing C constant:

1. Integer Constants in C:
 An integer constant must have at least one digit.
 It must not have a decimal point.

 It can either be positive or negative.

 No commas or blanks are allowed within an integer constant.

 If no sign precedes an integer constant, it is assumed to be positive.

 The allowable range for integer constants is -32768 to 32767.

2. Real constants in C:
 A real constant must have at least one digit
 It must have a decimal point

 It could be either positive or negative

 If no sign precedes an integer constant, it is assumed to be positive.

 No commas or blanks are allowed within a real constant.

3. Character and string constants in C:


 A character constant is a single alphabet, a single digit or a single special symbol enclosed within single
quotes.
 The maximum length of a character constant is 1 character.

 String constants are  enclosed within double quotes.

4. Backslash Character Constants in C:


 There are some characters which have special meaning in C language.
 They should be preceded by backslash symbol to make use of special function of them.

 Given below is the list of special characters and their purpose.


NASC-Department of Computer Applications [Computing Fundamentals and ‘C’ Programming] 5
 These are also called as escape sequences.

Backslash_character Meaning

\b Backspace

\f Form feed

\n New line

\r Carriage return

\t Horizontal tab

\” Double quote

\’ Single quote

\\ Backslash

\v Vertical tab

\a Alert or bell

\? Question mark

\N Octal constant (N is an octal constant)

\XN Hexadecimal constant (N – hex.dcml cnst)

How to use constants in a C program?

We can define constants in a C program in the following ways.

1. By “const” keyword
2. By “#define” preprocessor directive

1. Example program using const keyword in C:


#include <stdio.h>
void main()
{
const float number = 3.14;   /*Real constant*/
const char letter = ‘A’;           /*char constant*/
printf(“value of number : %f \n”, number );
printf(“value of letter : %c \n”, letter );
}

Output:
value of number : 3.140000
value of letter : A

2. Example program using #define preprocessor directive in C:


#include <stdio.h>

NASC-Department of Computer Applications [Computing Fundamentals and ‘C’ Programming] 6


#define number 3.14
#define letter ‘A’
void main()
{
printf(“value of number : %f \n”, number );
printf(“value of letter : %c \n”, letter );
}

Output:
value of number : 3.140000
value of letter : A

C – Variable

 C variable is a named location in a memory where a program can manipulate the data. This location is used
to hold the value of the variable.
 The value of the C variable may get change in the program.

 C variable might be belonging to any of the data type like int, float, char etc.

Rules for naming C variable:


1. Variable name must begin with letter or underscore.
2. Variables are case sensitive

3. They can be constructed with digits, letters.

4. No special symbols are allowed other than underscore.

5. sum, height, _value are some examples for variable name

Declaring & initializing C variable:


 Variables should be declared in the C program before to use.
 Memory space is not allocated for a variable while declaration. It happens only on variable definition.

 Variable initialization means assigning a value to the variable.

S.No  Type  Syntax Example

1 Variable declaration data_type variable_name; int x, y, z; char flat, ch;

2 Variable initialization data_type variable_name = value; int x = 50, y = 30; char flag = ‘x’, ch=’l’;

There are three types of variables in C program They are,


1. Local variable
2. Global variable

3. Environment variable

C – Data Types

C language is rich in data types


NASC-Department of Computer Applications [Computing Fundamentals and ‘C’ Programming] 7
ANSI – American National Standard Institute
ANSI C Supports Three classes of data type

1. Primary data type(fundamental)


2. Derived data types
3. User defined data types

All “C” compiler supports 5 fundamental data types

1. Integer (int)
2. Character (char)
3. floating point (float)
4. double-precession (double)
5. void

Range of data types:

Data type Bytes in Ram Range of data type


char 1 bytes -128 to 127
int 2 bytes -32, 768 to 32,767
float 4 bytes 3.4c-38 to 3.4 c+ 38
double 8 bytes 1.7C – 308 to 1.7c +308

Integer Types: Integers are whole numbers with a range of variables supported by a particular machine.

In a signed integer uses one bit for sign and 15 bits for magnitude

C has three classes of integer storage


short int
1. int
2. long int

It has a set of qualifiers i.e.,


1. sign qualifier
2. unsigned qualifier

short int uses half the range of storage amount of data, unsigned int use all the bits for the magnitude of the
number and are positive.

short int

int

long int

Datatype Size Range

char or signed char 1 byte -128 to 127

NASC-Department of Computer Applications [Computing Fundamentals and ‘C’ Programming] 8


unsigned char 1 byte 0 to 255

int or signed int 2 byte -32,768 to 32, 767

unsigned int 2 bytes 0 to 65535


Floating Point Datatype: Floating Point numbers are stored with 6 digits of precision. Those are defined
with keyword float. When the accuracy is not sufficient then the datatype double can be used. double gives
a precesion of 14 digits these known as double precesion numbers. Still for a better process we can use
long double which uses 80 bits.
float

double

long double

Type Storage size Value range Precision


float 4 byte 1.2E-38 to 3.4E+38 6 decimal places
double 8 byte 2.3E-308 to 1.7E+308 15 decimal places
long double 10 byte 3.4E-4932 to 1.1E+4932 19 decimal places

Character Datatype : Character are usually stored in 8 bits

Void datatype: A void type has no value this is usually used to specify the return type of function ,
this function does not return any value to calling function

Declaration of variables

 C variable is a named location in a memory where a program can manipulate the data. This
location is used to hold the value of the variable.
 The value of the C variable may get change in the program.
 C variable might be belonging to any of the data type like int, float, char etc

Rules for naming C variable:


1. Variable name must begin with letter or underscore.
2. Variables are case sensitive

3. They can be constructed with digits, letters.

4. No special symbols are allowed other than underscore.

5. sum, height, _value are some examples for variable name

Types of Variable declaration:

o Primary Type Declaration


o User Defined Declaration

No  Type  Syntax Example


NASC-Department of Computer Applications [Computing Fundamentals and ‘C’ Programming] 9
int x, y, z;
1 Primary Type Declaration data_type v1, v2, v3 … vn;
char flat, ch;
typedef int units;
typedef float marks;
2 typedef data_type identifier; units batch1, batch2;
marks sub1, sub2;
User Defined Declaration

enum day {mon, tue, …sun};


enum identifier {v1, v2, …vn}; enum day week_st, week_end;

Assigning values to variables:

The process of giving initial values to variables is called initialization. It can be achieved through

Assignment Statement:

Values can be assigned to variables using the assignment operator = as follows:

Variable_name=constant;

Reading Data from keyboard:

Another way giving values to variables is to input data through keyboard using scanf() function.

Syntax:

scanf (“format string”, argument list);

The format string must be a text enclosed in double quotes. It contains the information for interpreting the
entire data for connecting it into internal representation in memory.
Example: integer (%d) , float (%f) , character (%c) or string (%s).

Example: if i is an integer and j is a floating point number, to input these two numbers we may use
scanf (“%d%f”, &i, &j);

Defining Symbolic Constants

A symbolic constant is name that substitute for a sequence of character that cannot be changed. The
character may represent a numeric constant, a character constant, or a string. When the program is compiled,
each occurrence of a symbolic constant is replaced by its corresponding character sequence. They are
usually defined at the beginning of the program. The symbolic constants may then appear later in the
program in place of the numeric constants, character constants, etc., that the symbolic constants represent.

For example

A C program consists of the following symbolic constant definitions.


#define PI 3.141593

NASC-Department of Computer Applications [Computing Fundamentals and ‘C’ Programming] 10


#define TRUE 1
#define FALSE 0

#define PI 3.141593 defines a symbolic constant PI whose value is 3.141593. When the program is
preprocessed, all occurrences of the symbolic constant PI are replaced with the replacement text 3.141593.

Note that the preprocessor statements begin with a #symbol, and are not end with a semicolon. By
convention, preprocessor constants are written in UPPERCASE.

Operators
Operator: An operator is a symbol that tells the Computer to perform certain
mathematical or logical manipulations.

Expression: An expression is a sequence of operands and operators that reduces to single value

Eg: 10+25 is an expression whose value is 35

C operators can be classified into a no. of categories.

They include:

1. Arithmetic
2. Relational
3. Logical
4. Assignment
5. Increment and Decrement
6. Conditional
7. Bitwise
8. Special
Arithmetic Operators: C provides all the basic arithmetic operators, they are +, -, *, /, % Integer
division truncates any fractional part. The modulo division produces the remainder of an integer division.

Eg: a+b a–b a*b

-a * b a/b a%b

Here „a‟ and „b‟ are variables and are known as operands. % cannot be used for floating point data. C
does not have an operator for exponentiation.

Integer Arithmetic: When the operands in an expression are integers then the expression is an integer
expression and the operation is called integer arithmetic. This always yields an integer value. For Eg. a =
14 and n = 4 then
NASC-Department of Computer Applications [Computing Fundamentals and ‘C’ Programming] 11
a - b = 10 Note : During modulo division,the

a + b = 18 sign of the result is always the sign

a * b = 56 of the first operand (the dividend )

a/b=3 - 14 % 3 = -2

a%b=2 -14 % - 3 = 2

14 % -3 = 2
Real Arithmetic / Floating Pont Arithmetic:

Floating Point Arithmetic involves only real operands of decimal or exponential notation. If
x, y & z are floats, then

x = 6.0/7.0 = 0.857143

y = -1.0/3.0 = 0.333333

z = 3.0/2.0 = 1.500000

% cannot be used with real operands

Mixed mode Arithmetic: When one of the operands is real and the other is integer the expression is
a mixed mode arithmetic expression.

Eg: 15/10.0 = 1.500000

15/10 = 1

10/15 = 0

-10.0/15 = -0.666667

Relational Operator: These are the operators used to Compare arithmetic, logical and character
expressions.the value of a relational express is either one or zero .it is 1 if one is the specified relation is
true and zero if it is false For eg:

10 < 20 is true 20<10 is false

The relational operators in C are

Operator Meaning

< is less than


<= is less than or equal to

NASC-Department of Computer Applications [Computing Fundamentals and ‘C’ Programming] 12


> is greater than or equal to
>= is greater than or equal to
== is equal to
!= is not equal to

O/P

Condition : Return values

10! = 10 : 0
10 = = 10 : 1
10> = 10 : 1
10! = 9 : 1
Logical operator : Logical Operators are used when we want to test more than one
condition and make decisions. here the operands can be constants, variables and expressions
Logical operators are &&, ||, !

Eg:a > b && x = = 10

Logical or compound relational Expression

Truth Table && ||, !

OP1 OP2 OPJ&OP2 OP1 ||OP2 OP !

1 1 1 1 0 1

1 0 0 1 1 0

0 1 0 1

0 0 0 0
Assignment Operator: Used to assign the result of an expression to a variable. „= „is the assignment operator.
In addition C has a set of „short hand‟ assignment operators of the form

Var Op = Exp :

Variable operator shorthand assignment

Binary arithmetic operator

var op = exp;
NASC-Department of Computer Applications [Computing Fundamentals and ‘C’ Programming] 13
is equivalent to
var = var op exp;
Eg: x + = 1; == > x = x+1
x+ = y+1 == > x = x+y+1

Shorthand operator Assignment operator

a+=1 a = a+1
a-=1 a=a-1
a * = n+1 a = a* (n + 1)
a / = n+1 a = a/(n+1)
a%=b a=a%b

Increment and Decrement Operators:

++ and --

The Operator + + adds 1 to the operand while -- subtracts 1, Both are unary operators

Eg : ++x or x ++ == > x+=1 == > x=x+1

. -- x or x- - == > x-=1 == > x=x-1

A Profix operator first adds 1 to the operand and then the result is assigned to the variable on left. A
postfix operator first assigns the value to the variable on the left and the increments the operand.

Eg: 1) m = 5; 2). m = 5

y = ++m; y = m++

O/P m =6, y=6 m=6, y=5


Conditional operator: is used to check a condition and Select a Value depending on the Value of the
condition.
Variable = (condition)? Value 1 : Value 2:

If the Value of the condition is true then Value 1 is e valued assigned to the varable, otherwise
Value2.

Eg: big = (a>b)? a:b;

This exxp is equal to

if (a>b)

NASC-Department of Computer Applications [Computing Fundamentals and ‘C’ Programming] 14


big = a;

else

big = b;

Bitwise operator : are used to perform operations at binary level i. e. bitwise. these operators are used for
testing the bits, or Shifting them right or left . These operators are not applicable to float or double.
Following are the Bitwise operators with their meanings.

Operator Meaning

& Bitwise AND

| Bitwise OR

^ Bitwise Exclusive – OR

<< Left Shift

>> Right Shift

~ Complement

Eg‟ consider a = 13 & b = 6 as 8 bit short int (1byte)


<< Left Shift

a = 13 Binary 00001101

b=6 00000110

Consider a << 2 which Shifts two bits to left , that is 2 zeros are inserted at the right
and two bits at the left are moved out.

00001101

Moved

00110100

Finally the result is 00110100 . Deci 52 (13x4)

Note : when you shift a bit towards left its Decimal Value is multiplied by Two (2).

a =13 13= 00001101

a >>2 00000011

NASC-Department of Computer Applications [Computing Fundamentals and ‘C’ Programming] 15


000000 11 Decimal 3 (13/4)

Special Operators : these are two other operators in c.


sizeof operator : is used to find the on. of bytes occupied by a variable / data type in
computer memory.

eg : sizeof (float) returns 4


int m, x [ 50 ]

sizeof (m) returns 2


sizeof ( x ) returns 100 ( 50 x 2 )

i) comma operator : can be used to link the related expressions together. A comma- linked: list of
expressions are evaluated left to right and the value of right-most exp is the value of combined
expression.

Eg : value = ( x = 10, y = 5, x = y)
First 10 is assigned to x

then 5 is assigned to y

finally x + y i .e. which 15 is assigned to value .

Evaluation of Arithmetic 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;

Precedence of Arithmetic Operators


An arithmetic expression without parenthesis will be evaluated from left to right using the rules of
precedence of operators. There are two distinct priority levels of arithmetic operators in C.

High priority ===> * / %


Low priority ===> + -

Rules for evaluation of expression

 First parenthesized sub expression left to right are evaluated. If parentheses are nested, the
evaluation begins with the innermost sub expression.
NASC-Department of Computer Applications [Computing Fundamentals and ‘C’ Programming] 16
 The precedence rule is applied in determining the order of application of operators in evaluating sub
expressions. The associability rule is applied when two or more operators of the same precedence
level appear in the sub expression.

 Arithmetic expressions are evaluated from left to right using the rules of precedence. When
Parentheses are used, the expressions within parenthesis assume highest priority.

Type Conversions in Expressions:


Normally before an operation takes pace both the operands must have the same type. C converts One or
both the operands to the appropriate date types by “Type conversion”. This can be achieved in 3 ways.
Implicit Type conversion : In this the data type /Variable of lower type (which holds lower range of values or has
lower precision ) is converted to a higher type (which holds higher range of values or has high precision). This type
of conversion is also called “promotion”.

If a Char is converted into int, it is called as Internal promotion

Eg: int i;
char c;
c = ‘a’;
i = c;

Now the int Variable i holds the ASCII code of the char ‘a’

a) An arithmetic operation between an integer and integer yields an integer result.

b) Operation between a real yields a real

c) Operation between a real & an integer always yields a real result

Eg: 5/2 = 2 2/5 = 0

5.0/2 = 2.5 2.0/50. = 0.4

5/2.0 = 2.5 2/5.0 = 0.4

5.0/2.0 = 2.5 2.0/5.0 = 0.4

Assignment Type Conversion: If the two Operands in an Assignment operation are of different data types
the right side Operand is automatically converted to the data type of the left side.

Eg: Let „k‟ is an int var & „a‟ is a float var

int k; yes float a; yes


k= 5/2 2 k=2/5 0 a = 5/2 2.0

k=5.0/2 2 k=2.0/5 0 a = 5.0/2 2.5

NASC-Department of Computer Applications [Computing Fundamentals and ‘C’ Programming] 17


k=55.0/2 2 k=2/5.0 0 a = 5/2.0 2.5
k=5.0/2.0 2 k=2.0/5.0 0 a = 2/5 0.0
a = 2.0/5 0.4
a = 2.0/0.5 0.4
Explicit Type Conversion: When we want to convent a type forcibly in a way that is different from
automatic type conversion, we need to go for explicit type conversion.

(type name) expression;

Type name is one of the standard data type. Expression may be a constant variable Or an expression
this process of conversion is called as casting a value.

Eg: x = (int) 7.5

A = (int) 21.3/(int) 4.5

Y =( int) (a + b)

P = (double)sum/n

Operator - precedence & Associativity

precedence is nothing but priority that indicates which operator has to be evaluated first when there are
more than one operator.

Associativity : when there are more than one operator with same precedence [ priority ] then we consider
associativity , which indicated the order in‟ which the expression has to be evaluated. It may be either
from Left to Right or Right to Left.

eg : 5 * 4 + 10 / 2
1 2
= 20 + 5
3
=25

Operator Description Associativity


() Parentheses (function call) (see Note 1) left-to-right
[] Brackets (array subscript)
. Member selection via object name
-> Member selection via pointer
++ -- Postfix increment/decrement (see Note 2)
++ -- Prefix increment/decrement right-to-left
+- Unary plus/minus
!~ Logical negation/bitwise complement
(type) Cast (convert value to temporary value of type)
* Dereference

NASC-Department of Computer Applications [Computing Fundamentals and ‘C’ Programming] 18


& Address (of operand)
sizeof Determine size in bytes on this implementation
*  /  % Multiplication/division/modulus left-to-right
+  - Addition/subtraction left-to-right
<<  >> Bitwise shift left, Bitwise shift right left-to-right
<  <= Relational less than/less than or equal to left-to-right
>  >= Relational greater than/greater than or equal to
==  != Relational is equal to/is not equal to left-to-right
& Bitwise AND left-to-right
^ Bitwise exclusive OR left-to-right
| Bitwise inclusive OR left-to-right
&& Logical AND left-to-right
|| Logical OR left-to-right
?: Ternary conditional right-to-left
= Assignment right-to-left
+=  -= Addition/subtraction assignment
*=  /= Multiplication/division assignment
%=  &= Modulus/bitwise AND assignment
^=  |= Bitwise exclusive/inclusive OR assignment
<<=  >>= Bitwise shift left/right assignment
, Comma (separate expressions) left-to-right

Mathematical functions:

Trigonometric functions
acos() Arc Cosine
asin() Arc Sine
atan() Arc Tangent
atan2() Arc Tangent of Quotient
cos() Cosine
sin() Sine

Hyperbolic functions
cosh() Hyperbolic Cosine
sinh() Hyperbolic Sine
tanh() Hyperbolic Tangent

Absolute Value functions


Absolute Value of Floating-Point
fabs()
Number

Nearest Integer, Absolute Value, and Remainder functions


ceil() Ceiling
floor() Floor
fmod() Floating Modulus

NASC-Department of Computer Applications [Computing Fundamentals and ‘C’ Programming] 19


Exponential and Logarithmic functions
exp() Exponential
frexp() Split into Fraction and Exponent
ldexp() Combine Fraction and Exponent
log() Natural Logarithm
log10() Common Logarithm
Split into Integer and Fractional
modf()
Parts

Power functions
pow() Power
sqrt() Square Root

Managing Input and Output operations

i. Reading a character:

getchar ( ) function is used to read one character at a time from the key board

Syntax ch = getchar ( );

Where, i. ch is a valid ‘C’ variable


ii. It must be declared as a character data type.
Eg:
char name;
name = getchar();
Eg. Program:
main ( )
{
char ans;
printf(“What do you like to
drink”);
printf(“type ‘y’ for coffee
and ‘n’ for tea”);
ans = getchar();
if (ans==’Y’ || ans==’y’)
printf(“I need a coffee”);
else
printf(“I need a tea”);
getch();

O/P: What do you like to drink?


type ‘y’ for coffee and ‘n’ for tea Y
I need a coffee

When this function is executed, the computer will wait for a key to be pressed and assigns the value to the
variable when the “enter” key pressed.
NASC-Department of Computer Applications [Computing Fundamentals and ‘C’ Programming] 20
C supports other similar functions

Function Test
isalnum(c) Is c an alphanumeric character?
isalpha(c) Is c an alphabetic character?
isdigit(c) Is c a digit?
islower(c) Is c a lower case letter?
isprint(c) Is c a printable character?
ispunct(c) Is c a punctuation mark?
isspace(c) Is c a white space character?
isupper(c) Is c an upper case later?

ii. Writing a character:

putchar ( ): Function is used to display one character at a time on the monitor.

Syntax: putchar (ch); Ex char ch = ‘m’ putchar (ch);

The Computer display the value char of variable „ch‟ i.e M on the Screen.
Formatted Input
5.11 Formatting Input With scanf()

- Used for precise input formatting.


- Every scanf() function contains a format control string that describes the format of the data to be
input.
- The format control string consists of conversion specifications and literal characters.
- Function scanf() has the following input formatting capabilities

1. Inputting all types of data.


2. Inputting specific characters from an input.
3. Skipping specific characters in the input.

- It is written in the following form:

scanf (format-control-string, other-arguments);

- For example:

scanf("%e%f%g", &a, &b, &c);

- The format-control-string describes the formats of the input, and the other-arguments are pointers to variables in
which the input will be stored.

Conversion specifiers for scanf()

Conversion specifier Description


Integers
Read an optionally signed decimal integer. The
corresponding argument
d is a pointer to integer.
Read an optionally signed decimal, octal, or hexadecimal
integer. The
i corresponding argument is a pointer to integer.
NASC-Department of Computer Applications [Computing Fundamentals and ‘C’ Programming] 21
Read an octal integer. The corresponding argument is a
pointer to
o unsigned integer.
Read an unsigned decimal integer. The corresponding
argument is a
u pointer to unsigned integer.
Read a hexadecimal integer. The corresponding argument
is a pointer to
x or X unsigned integer.
Place before any of the integer conversion specifiers to
indicate that a
h or l
short or long integer is to be input.
Floating-point numbers
Read a floating-point value. The corresponding argument
is a pointer to
e, E, f, g or G a floating-point variable
Place before any of the floating-point conversion
specifiers to indicate
l or L
that a double or long double value is to be input.
Characters and strings
Read a character. The corresponding argument is a
c pointer to char, no

null (‘\0’) is added.


Read a string. The corresponding argument is a pointer to
an array of
type char that is large enough to hold the string and a
s terminating null
(‘\0’) character.
Scan set [scan Scan a string for a set of characters that are stored in an
characters] array.
Miscellaneous
Read a pointer address of the same form produced when
an address is
p output with %p in a printf() statement.
Store the number of characters input so far in this scanf().
The
n corresponding argument is a pointer to integer.
% Skip a percent sign (%) in the input.

Formatted outut
Formatting output with printf()

- For precise output formatting, every printf() call contains a format control string that describes the output
format.
- The format control string consists of:

1. Conversion specifiers.
2. Flags.
3. Field widths.
4. Precisions.
5. Literal characters.

- Together with percent sign (%), these, form conversion specifications. Function printf() can perform the
following formatting capabilities:

1. Rounding floating-point values to an indicated number of decimal places.


2. Aligning a column of numbers with decimal points appearing one above the other.
3. Right-justification and left-justification of outputs.
4. Inserting literal characters at precise locations in a line of output.
NASC-Department of Computer Applications [Computing Fundamentals and ‘C’ Programming] 22
5. Representing floating-point number in exponential format.
6. Representing unsigned integers in octal and hexadecimal format.
7. Displaying all types of data with fixed-size field widths and precisions.
Format specification has the following form:
%w.p type_specifier
Here, w : It is an integer number specified total number of columns.
p : Number of digits to the right of the decimal
Output of integer number:
Format:
9 8 7 6
(“%d”, 9876)

(“%6d”, 9876) 9 8 7 6

(“%-6d”, 9876) 9 8 7 6

(“%d”06, 9876) 9 8 7 6

Note: - and 0 are known as “flags”.

Output of real numbers:

%w.pf or %w.pe

Printing single characters:

%wc

Printing string:

%w.p s

W : field width

P: first p characters/ right justified

CONTROL STRUCTURES / STATEMENTS


 A program is nothing but the execution of sequence of one or more instructions.
 Quite often, it is desirable to alter the sequence of the statements in the program
 Depending upon certain circumstances. (i.e., we have a number of situations where we may have to change
the order of execution of statements based on certain conditions) (or)
 Repeat a group of statements until certain specified conditions are met.
 This involves a kind of decision making to see whether a particular condition has
 Occurred or not and direct the computer to execute certain statements accordingly. Based on application, it is
necessary / essential

(i) To alter the flow of a program

(ii) Test the logical conditions

(iii) Control the flow of execution as per the selection these conditions can be placed in the
program using decision-making statements.
NASC-Department of Computer Applications [Computing Fundamentals and ‘C’ Programming] 23
C supports mainly three types of control statements

I. Decision making statements

1) Simple if Statement 2) if – else Statement 3) Nested if-else statement 4) else – if Ladder

5) switch statement

II. Loop control statements

1) for Loop 2) while Loop 3) do-while Loop

III. Unconditional control statements

1) goto Statement 2) break Statement 3) continue Statement

Decision Making Statements


Simple “if” statement:

 The if statement is a powerful decision making statement and is used to control the flow of execution of
statements.

Syntax:

if (Condition or test expression) if (Condition or test expression)


Statement; OR {
Rest of the program Statement;
}
Rest of the program;

 It is basically a “Two-way” decision statement (one for TRUE and other for FALSE)
 It has only one option.
 The statement as executed only when the condition is true.
 In case the condition is false the compiler skips the lines within the “if Block”.
 The condition is always enclosed within a pair of parenthesis ie ( ) .
 The conditional statement should not terminated with Semi-colons (ie ;)
 The Statements following the “if”-statement are normally enclosed in Curly Braces ie { }.
 The Curly Braces indicates the scope of “if” statement.
 The default scope is one statement. But it is good practice to use curly braces even with a single statement.
 The statement block may be a single statement or a group of statements.
 If the Test Expression / Conditions is TRUE, the Statement Block will be executed and executes rest of the
program.
 If the Test Expression / Condition is FALSE, the Statement Block will be skipped and rest of the program
executes next.

Flow chart for “ if ” statement:

NASC-Department of Computer Applications [Computing Fundamentals and ‘C’ Programming] 24


Example:

#include<stdio.h>
Void main()
{
int a=10;
if(a < 20)
{
printf(“a is less than 20”);
}
printf(“value of a is:%d”,a);
}
Output:
a is less than 20.
Value of a is: 10

“if-else” Statement:
 It is observed that the if statement executes only when the condition following if is true.
 It does nothing when the condition is false.
 In if-else either True-Block or False – Block will be executed and not both.
 The “else” Statement cannot be used without “if”.

Syntax:

if ( Test Expression or Condition )


{
Statements; /*true block (or) if block */
}
else
{
Statements; /* false block (or) else block */
}

Flow chart

NASC-Department of Computer Applications [Computing Fundamentals and ‘C’ Programming] 25


Example:

Write a program to print the given number is even or odd.

# include<stdio.h>
#include<conio.h>
Void main()
{
int n;
clrscr();
printf(“Enter a number:”);
scanf(“%d”, &n);
if( (n%2)==0 )
printf(“\n The given number is EVEN ”);
else
printf(“\n The given number is ODD ”);
getch( );
}

Output:
Enter a number: 24
The given number is EVEN

Nested “if–else” Statement:

 Using of one if-else statement in another if-else statement is called as nested if-else control statement.
 When a series of decisions are involved, we may have to use more than one ifelse statement in nested form.

Syntax:

if ( Test Condition 1)
{
if ( Test Condition 2)
{ Statement -1; }
else
{ Statement -2; }
}
else
{
if ( Test Condition 3)
{ Statement -3; }
else
{ Statement -4; }
} /* end of outer if-else */

NASC-Department of Computer Applications [Computing Fundamentals and ‘C’ Programming] 26


 If Test Condition-1 is true then enter into outer if block, and it checks Test Condition- 2 if it is true then
Statement-1 executed if it is false then else block executed i.e Statement-2.
 If Test Condition -1 is false then it skips the outer if block and it goes to else block and Test Condition-3
checks if it is true then Statement-3 executed, else Statement-4 executed

Example:

# include<stdioi.h>
#include<conio.h>
Void main()
{
float a,b,c;
printf(“Enter Three Values:”);
scanf(“%f%f%f ”, &a, &b, &c);
printf(“\n Largest Value is:”) ;
if(a>b)
{
if(a>c)
printf(“ %f ”, a);
else
printf(“ %f ”, c);
}
else
{
if (b>c)
printf(“ %f ”, b);
else
printf(“ %f ”, c);
}
}

Output:

Enter three values: 9.12 5.34 3.87


Largest Value is: 9.12

The “else – if” Ladder:

 This is another way of putting if „s together when multiple decisions are involved.
 A multipath decision is a chain of if ‟s in which the statement associated with each else is an if.
 Hence it forms a ladder called else–if ladder.

Syntax:

if (Test Condition -1)


Statement -1;
else if ( Test Condition -2)
Statement -2;
else if ( Test Condition -3)
Statement -3;
:
:
else if ( Test Condition –n)
Statement –n;
else
default statement;
Rest of the Program Statements-X;

 The above construction is known as else if ladders.


NASC-Department of Computer Applications [Computing Fundamentals and ‘C’ Programming] 27
 The conditions are evaluated from top to bottom.
 As soon as a true condition is found, the statement associated with it is executed and the control is transferred
to the Rest of the Program Statement–X (skipping rest of the ladder).
 When all the „n‟ conditions become false, then the final else containing the default statement will be
executed.

Flow Chart:

Example:

#include<stdio.h>
#include<conio.h>
Void main()
{
int a,b,c;
clrscr();
printf(“Enter the numbers:”);
scanf(“%d %d %d”,&a,&b,&c);
if ((a>b) && (a>c))
printf(“Highest Number is: %d”, a);
else if ((b>a) && (b>c))
printf(“Highest Number is: %d”, b);
else
printf(“Highest Numbers is: %d”, c);
getch();
}

Output:
NASC-Department of Computer Applications [Computing Fundamentals and ‘C’ Programming] 28
Enter the numbers: 12 34 10
Highest number is : 34

The “switch-case” Statement:

 The switch statement causes a particular group of statements to be chosen from several available groups.
 The selection is based upon the current value of an expression which is included within the switch
statement.
 The switch statement is a multi-way branch statement.
 In a program if there is a possibility to make a choice from a number of options, this structured selected is
useful.
 The switch statement requires only one argument of int or char data type, which is checked with number
of case options.
 The switch statement evaluates expression and then looks for its value among the case constants.
 If the value matches with case constant, then that particular case statement is executed.
 If no one case constant not matched then default is executed.
 Here switch, case and default are reserved words or keywords.
 Every case statement terminates with colon “:”.
 In switch each case block should end with break statement, i.e.

Syntax:

switch(variable or expression)
{
case Constantvalue-1: Block -1; (or)
Statement-1;
Break;
case Constantvalue-2: Block -2; ; (or)
Statement-2;
Break;
--- ---- ----
--- ---- ----
case Constantvalue-n: Block -n ; (or)
Statement-n;
Break;
default: default – block; (or) Statement;
}

(i) The switch( ) Organization:


 The entire case structure following switch( ) should be enclosed with pair of curly braces { }.
 In the block the variable or expression can be a character or an integer.
 Each case statement must contain different constant values.
 Any number of case statements can be provided.
 If the case structure contains multiple statements, they need not be enclosed within pair of curly braces.

(ii) The switch( ) Execution:


 When one of the cases satisfies, the statements following it are executed.
 In case there is no match, the default case is executed.

Flow chart:

NASC-Department of Computer Applications [Computing Fundamentals and ‘C’ Programming] 29


Example:

#include<stdio.h>
#include<conio.h>
Void main()
{
char L;
clrscr();
printf(“ \n Enter your Choice( R,r,G,g,Y,y):”);
scanf(“%c”, &L);
switch(L)
{
case ”R‟:
case “r‟: printf(“RED Light Please STOP”);
break;
case ”Y‟:
case “y‟: printf(“YELLOW Light Please STOP”);
break;
case ”G‟:
case “g‟: printf(“GREEN Light Please STOP”);
break;
default: printf(“THERE IS NO SIGNAL POINT ”);
}
getch( );
}

Output:

Enter your Choice(R,r,G,g,Y,y): g


GREEN Light Please GO

Loop Control Statements

NASC-Department of Computer Applications [Computing Fundamentals and ‘C’ Programming] 30


Loop: A loop is defined as a block of statements which are repeatedly executed for certain number of times.

 Depending on the position of the control statements of the loop, a control structure may be classified as:
1) Entry controlled loop (or) pre-test
2) Exit controlled loop (or) post-test
 In the entry controlled loop, the control conditions are tested before the start of the loop execution.
 If the conditions are not satisfied, then the body of the loop will not be executed.
 In the exit controlled loop, the test is performed at the end of the body of the loop and therefore the
statements is executed unconditionally for the first time.

The “for” loop:

 The for loop statement comprises of 3 actions.


 The 3 actions are “initialize expression”, “Test Condition expression” and “updation expression” ”
 The expressions are separated by Semi-Colons (;).
 The loop variable should be assigned with a starting and final value.
 Each time the updated value is checked by the loop itself.
 Increment / Decrement is the numerical value added or subtracted to the variable in each round of the loop.

Syntax:

for(initialize expression; test condition; updation )


{
Statement 1;
Statement 2;
}

1. The initialization sets a loop to an initial value. This statement is executed only once.
2. The test condition is a relational expression that determines the number of iterations desired or it determines
when to exit from the loop.
i. The for loop continues to execute as long as conditional test is satisfied.
ii. When the condition becomes false the control of the program exits from the body of for loop
and
iii. executes next statements after the body of the loop.
3. The updation(increment or decrement operations) decides how to make changes in the loop.
I. The body of the loop may contain either a single statement or multiple statements.

for loop can be specified by different ways as shown

Syntax Output Remarks

(i) for (; ; ) Infinite to loop No arguments

(ii) for (a=0; a< =20;) Infinite loop “a‟ is neither increased nor
decreased.

(iii) for (a=0; a<=10; a++) Displays value “a‟ is increased from 0 to 10 curly

NASC-Department of Computer Applications [Computing Fundamentals and ‘C’ Programming] 31


printf(“%d”, a) from 1 to 10 braces are not necessary default
scope of for loop is one statement.

(iv) for (a=10; a>=0; a--) Displays value “a‟ is decreased from 10 to 0.
printf(„%d”,a); from 10 to 0

Flow chart

Example:

#include<stdio.h>
#include<conio.h>
Void main()
{
int i;
clrscr();
printf(“The numbers of 1 to 25 are:”);
for(i=1; i < =15; i=i+1)
printf(“\n%d ”, i);
}

Output :

The Numbers of 1 to 15 are:


1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

Nested “for” loop:

 We can also use loop within loops.


 i.e. one for statement within another for statement is allowed in C. (or „C‟ allows multiple for loops in the
nested forms).
 In nested for loops one or more for statements are included in the body of the loop.

Syntax:

NASC-Department of Computer Applications [Computing Fundamentals and ‘C’ Programming] 32


for( initialize ; test condition ; updation) /* outer loop */
{
for(initialize ; test condition ; updation) /* inner loop */
{
Body of loop;
}
}

 The outer loop controls the rows while the inner loop controls the columns.

Example:

#include<stdio.h>
#include<conio.h>
Void main()
{
int a,b,sum;
clrscr();
for (a=3; a > =1; a - - )
{
for(b=1;b<=2;b++)
{
sub = a – b;
printf(“a=%d b=%d a-b = %d \n”, a,b, sub);
}
}
getch();
}

Output:

a=3 b =1 a-b =2
a=3 b =2 a-b =1
a=2 b =1 a-b =1
a=2 b =2 a-b =0
a=1 b =1 a-b =0
a=1 b =2 a-b =-1

The “ while ” loop

 The simplest of all the looping structures in C is.

Syntax:

Initialization Expression;
while( Test Condition)
{
Body of the loop
}

 The while is an entry – controlled loop statement.


 The test condition is evaluated and if the condition is true, then the body of the loop is executed.
 The execution process is repeated until the test condition becomes false and the control is transferred out of
the loop
 On exit, the program continues with the statement immediately after the body of the loop.
 The body of the loop may have one or more statements.
 The braces are needed only if the body contains two or more statements.
 It‟s a good practice to use braces even if the body has only one statement.

NASC-Department of Computer Applications [Computing Fundamentals and ‘C’ Programming] 33


Example:

#include<stdio.h>
#include<conio.h>
Void main()
{
int a=1,sum=0;
clrscr();
while(a<=10)
{
sum = sum + a;
a++;
}
printf(“Sum of 1 to 10 numbers is: %d”, sum);
getch();
}

Ouput:
Sum of 10 numbers is: 55

The “ do-while “ loop:

 In do-while, the condition is checked at the end of the loop.


 The do-while loop will execute at least one time even if the condition is false initially.
 The do-while loop executes until the condition becomes false.

Syntax:

Initialization Expression;
do
{
Body of the loop;
} while ( Test Condition);

Example:

#include<stdio.h>
#include<conio.h>
Void main()
{
int a,fact=1;
clrscr();
printf( “ \n Enter the Number:”);
scanf( “ %d”, &a);
do
{
fact = fact * a;
a--;
} while (a >= 1);
printf( “ \n factorial of given number is %d”, fact);
getch();
}

Output:
Enter the number : 5
Factorial of given number is 120.
NASC-Department of Computer Applications [Computing Fundamentals and ‘C’ Programming] 34
Unconditional Control Statements

The “ break ” Statement:

 A break statement terminates the execution of the loop and the control is transferred to the statement
immediately following the loop.
 i.e., the break statement is used to terminate loops or to exit from a switch.
 It can be used within a for, while, do-while, or switch statement.
 The break statement is written simply as break;

Example:

switch (choice = = toupper(getchar( ))


{
case “R‟: printf(“Red”);
break;
case “W‟: printf(“White”);
break;
case “B‟: printf(“Blue”);
break;
default: printf(“Error”);
}

 Notice that each group of statements ends with a break statement, (in order) to transfer control out of the
switch statement.
 The last group does not require a break statement; since control will automatically be transferred out of the
switch statement after the last group has been executed.

Syntax:

break;

NASC-Department of Computer Applications [Computing Fundamentals and ‘C’ Programming] 35


Example:

#include<stdio.h>
int main()
{
float average,num,sum;
int i,n;
printf(“Maximum number of inputs:”);
scanf(“%d”, &n);
for(i=1;i<=n;++i) {
printf(“Enter n%d:”,i);
scanf(“%f”,&num);
if(num < 0.0)
break;
sum=sum+num;
}
average=sum/(i-1);
printf(“Average=%.2f”,average);
return 0;
}

Output:
Maximum number of inputs : 4
Enter n1: 1.5
Enter n2: 12.5
Enter n3: 7.2
Enter n4: -1
Average = 7.07

NASC-Department of Computer Applications [Computing Fundamentals and ‘C’ Programming] 36


Flow chart

The “ continue “ Statement:

 The continue statement is used to bypass the remainder of the current pass through a loop.
 The loop does not terminate when a continue statement is encountered.
 Instead, the remaining loop statements are skipped and the computation proceeds directly to the next pass
through the loop.
 The continue statement can be included within a while, a do-while, a for statement.
 It is simply written as “continue”.
 The continue statement tells the compiler “Skip the following Statements and continue with the next
Iteration”.
 In „while‟ and „do‟ loops continue causes the control to go directly to the test – condition and then to
continue the iteration process.
 In the case of „for‟ loop, the updating section of the loop is executed before test condition, is evaluated.

Syntax:

continue;

Flow chart:

NASC-Department of Computer Applications [Computing Fundamentals and ‘C’ Programming] 37


Example:

#include<stdio.h>
int main()
{
int i,num,prodcuct;
for(i=1,product=1;i<=4;++i){
printf(“Enter num%d:”,i);
scanf(“%d”,&num);
if(num==0)
continue;
product*=num;
}
printf(“Product=%d”,product);
return 0;
}

Output:

Enter num1:3
Enter num2:0
Enter num3:-5
Enter num4:2
Product = -30

The “ goto” Statement:

 C supports the “goto‟ statement to branch unconditionally from one point to another in the program.
 Although it may not be essential to use the “goto” statement in a highly structured language like „C‟, there
may be occasions when the use of goto is necessary.
 The goto requires a label in order to identify the place where the branch is to be made.
 A label is any valid variable name and must be followed by a colon( : ).
 The label is placed immediately before the statement where the control is to be transferred.
 The label can be anywhere in the program either before or after the goto label statement.

Syntax:
NASC-Department of Computer Applications [Computing Fundamentals and ‘C’ Programming] 38
goto label;
-- -- -- -- --
-- -- -- -- --
-- -- -- -- --
label:
statement;

 During running of a program, when a statement like “goto begin;” is met, the flow of control will jump to
the statement immediately following the label “begin:” this happens unconditionally.
 „goto‟ breaks the normal sequential execution of the program.
 If the “label:” is before the statement “goto label;” a loop will be formed and some statements will
be executed repeatedly. Such a jump is known as a “backward jump‟.
 If the “label:” is placed after the “goto label;” some statements will be skipped and the jump is
known as a “forward jump”.

Forward jump Backward jump

Example:

#include<stdio.h>
int main()
{
float average,num,sum;
int i,n;
printf(“Maximum number of inputs:”);
scanf(“%d”, &n);
for(i=1;i<=n;++i) {
printf(“Enter n%d:”,i);
scanf(“%f”,&num);
if(num < 0.0)
goto jump;
sum=sum+num;
}
jump:
average=sum/(i-1);
printf(“Average=%.2f”,average);
return 0;
}

Output:
Maximum number of inputs : 4
Enter n1: 1.5 Enter n2: 12.5 Enter n3: 7.2 Enter n4: -1
Average = 7.07

ARRAYS

NASC-Department of Computer Applications [Computing Fundamentals and ‘C’ Programming] 39


 An array is a fixed size sequenced collection of elements of the same data type.
 It is simply grouping of like type data such as list of numbers, list of names etc.

Some examples where arrays can be used are


1. List of temperatures recorded every hour in a day, or a month, or a year.
2. List of employees in an organization.
3. List of products and their cost sold by a store.
4. Test scores of a class of students
5. List of customers and their telephone numbers.

 An array is collection of same data type elements in a single entity. (or)


 An array is collection of homogeneous elements in a single variable.
 It allocates sequential memory locations
 Individual values are called as elements.

Types of Arrays:

 We can use arrays to represent not only simple lists of values but also tables of data in two or three or more
dimensions.
 One – dimensional arrays
 Two – dimensional arrays
 Multidimensional arrays

ONE – DIMENSIONAL ARRAY:

 A list of items can be given one variable name using only one subscript and such a variable is called a single –
subscripted variable or a one – dimensional array.

Declaration of One-Dimensional Arrays :

 Like any other variables, arrays must be declared before they are used. The general form of array declaration
is

Syntax:

<data type> <array name> [sizeofarray];

 The datatype specifies the type of element that will be contained in the array, such as int, float, or char.
 The size indicates the maximum number of elements that can be stored inside the array.
 The size of array should be a constant value.

Examples:

float height[50];
 Declares the height to be an array containing 50 real elements. Any subscripts 0 to 49 are valid.

int group[10];
 Declares the group as an array to contain a maximum of 10 integer constants.

char name[10];
 Declares the name as a character array (string) variable that can hold a maximum of 10 characters.

Ex: int number[10];


 The subscript should begin with number “0‟.

NASC-Department of Computer Applications [Computing Fundamentals and ‘C’ Programming] 40


i.e. x[0].
 To represent a set of five numbers, say (35, 40, 20, 57, 19) by an array variable “number”.

 We may declare the variable “number” as int number[5];

 Hence the computer reserves five storage locations as shown

number[0]
number[1]
number[2]
number[3]
number[4]

 The values to the array elements can be assigned as


number[0] = 35;
number[1] = 40;
number[2] = 20;
number[3] = 57;
number[4] = 19;
 This would cause the array number to store the values as

35 number[0]
40 number[1]
20 number[2]
57 number[3]
19 number[4]
Valid Statements :

 a = number[0] + 10;
 number[4] = number[0] + number[2];
 number[2] = x[5] + y[10];
 value[6] = number[i] * 3;

Example:

#include<stdio.h>
#include<conio.h>
void main()
{
int i;
float x[10];
printf(“Enter 10 real numbers: \n”); /* reading values into Array */
for (i=0; i<10;i++)
{
scanf(“ %f ”, &x[i]);
}
printf(“The array elements are:”);
for (i=0; i<10;i++)
{
printf(“%d \t”, x[i]);
}
getch();
}

NASC-Department of Computer Applications [Computing Fundamentals and ‘C’ Programming] 41


Output:

Enter 10 real numbers:


1.1 2.2 3.3 4.4 5.5 6.6 7.7 8.8 9.9 10.10
The array elements are:
1.1 2.2 3.3 4.4 5.5 6.6 7.7 8.8 9.9 10.10

Initialization of One – Dimensional Arrays:

 After an array is declared, its elements must be initialized. Otherwise they will contain “garbage”.
 An array can be initialized at either of the following stages.
I. At compile time
II. At run time.

(1) Compile Time Initialization:

 We can initialize the elements of arrays in the same way as the ordinary variables when they are declared.
 The general form of initialization of array is
datatype array_name[size] = { list of values };
 The values in the list are separated by commas.
Example:
int number[3] = {0,0,0};
 i.e., we will declare the variable number as an array of size 3 and will assign zero to each element.
 If the number of values in the list is less than the number of elements, then only that many elements will be
initialized.
 The remaining elements will be set to zero automatically.
Ex:
float total[5] = { 0.0, 15.75, -10};
 The size may be omitted.
 In such cases, the compiler allocates enough space for all initialized elements.
Ex:
int counter [ ] = {1,1,1,1};
 This will declare the counter array to contain four elements with initial values 1.
 Character arrays may be initialized in a similar manner.
char name[ ] = { „J‟, „o‟, „h‟, „n‟, „\0‟};
 This declares the name to be an array of five characters initialized with the string “John” ending with a null
character.
 Alternative declaration is char name[ ] = “John”;
 Compile time initialization may be partial. i.e., the number of initializers may be less than the declared size.
In such cases the remaining elements are initialized to zero, if the array type is numeric.And NULL if the type
is char.
Ex: int number[5] = {10,20};
Will initialize the first two elements to 10 & 20 respectively and the remaining elements to zero.
Similarly
char city[5] = {„B‟};
will initialize the first element to „B‟ and the remaining four to NULL.
 If we have more initializers than the declared size, the compiler will produce an error.
int number[3] = {10,20,30,40};
will not work. It is illegal in C.

(2) Run Time Initialization:


 An array can be explicitly initialized at run time.
 This approach is usually applied for initializing long arrays.

Example:

#include<stdio.h>
#include<conio.h>
NASC-Department of Computer Applications [Computing Fundamentals and ‘C’ Programming] 42
void main()
{
int i;
float x[10];
printf(“Enter 10 real numbers: \n”); /* reading values into Array */
for (i=0; i<10;i++)
{
scanf(“ %f ”, &x[i]);
}
printf(“The array elements are:”);
for (i=0; i<10;i++)
{
printf(“%d \t”, x[i]);
}
getch();
}

Output:

Enter 10 real numbers:


1.1 2.2 3.3 4.4 5.5 6.6 7.7 8.8 9.9 10.10
The array elements are:
1.1 2.2 3.3 4.4 5.5 6.6 7.7 8.8 9.9 10.10

TWO DIMENSIONAL ARRAYS:

 There could be situations where a table of values will have to be stored.


 A list of items can be given one variable name using two subscripts and such a variable is called a two –
subscripted variable or a two – dimensional array.

Syntax:

<data type> <array name>[row size][column size];


Representation of two Dimensional array in memory.
column -0 column-1 column -2
[0] [0] [0] [1] [0] [2]

Row 0
89 77 84
[1] [0] [1] [1] [1] [2]
Row 1
98 89 80
[2] [0] [2] [1] [2] [2]
Row 2
75 70 82
[3] [0] [3] [1] [3] [2]
Row 3
60 75 80
[4] [0] [4] [1] [4] [2]
Row 4
84 80 75
Initializing Two- Dimensional Arrays:

 Like the one-dimensional arrays, two-dimensional arrays may be initialized by following their declaration
with a list of initial values enclosed in braces.
int table[2] [3] = {0,0,0,1,1,1};
NASC-Department of Computer Applications [Computing Fundamentals and ‘C’ Programming] 43
 This initializes the elements of first row to zero and the second row to one.
 This initialization is done row by row.
 The above statement can be equivalently written as
int table[2][3] = {{0,0,0},{1,1,1}};
 we can also initialize a two – dimensional array in the form of a matrix as shown.
int table[2][3] = {
{0,0,0},
{1,1,1}
};
Commas are required after each brace that closes of a row, except in case of last row.
 If the values are missing in an initializer, they are automatically set to zero.
Ex: int table [2] [3] = {
{1,1}, 110
{2} 200
};
 This will initialize the first two elements of the first row to one,
 The first element of the second row to two and all other elements to zero.
 When all the elements are to be initialized to zero, the following short-cut method may be used.
int m[3][5] = { {0}, {0}, {0}};
 The first element of each row is explicitly initialized to zero while the other elements are automatically
initialized to zero.
 The following statement will also achieve the same result
int m[3][5] = { 0, 0 };

Example:

#include<stdio.h>
#include<conio.h>
void main()
{
int i,j;
int a[3][3] = { { 1,2,3}, {4,5,6}, {7,8,9}};
clrscr();
printf(“elements of an array \n \n”);
for( i=0; i<3;i++)
{
for ( j=0; j<3;j++)
{
printf (“%d\t”, a[ i ][ j ]);
} /* end of inner for loop */
printf(“\n”);
} /* end of outer for loop */
getch( );
} /* end of main() function */

Output:

Elements of an Array
1 2 3
4 5 6
7 8 9

Three Dimensional Array:

 A list of items can be given one variable name using three subscripts and such a variable is called Three –
dimensional array.

NASC-Department of Computer Applications [Computing Fundamentals and ‘C’ Programming] 44


Declaration of Three-Dimensional Arrays :

<datatype> <array name> [sizeofno.oftwoDimArray] [sizeofrow] [sizeofcolom];

 The datatype specifies the type of elements that will be contained in the array, such as int, float, or char.

Initializing Three- Dimensional Arrays:

 Like the one-dimensional arrays, three-dimensional arrays may be initialized by following their declaration
with a list of initial values enclosed in braces.
int table[2][2][3] = {0,0,0,1,1,1,6,6,6,7,7,7};
 This initializes the elements of first two dimensional(matrix) first row to zero‟s and the second row to one‟s
and second matrix elements are first row to six‟s and the second row to seven‟s.
 This initialization is done row by row.
 The above statement can be equivalently written as
int table[2][3] = { {{0,0,0},{1,1,1},{0,0,0},{1,1,1}} }
we can also initialize a two – dimensional array in the form of a matrix as shown
int table[2][3] = {
{
{0,0,0},
{1,1,1}
},
{
{6,6,6},
{7,7,7}
}
};

Dynamic Arrays
 An array created at compile time by specifying size in the source code has fixed size and cannot be modified
at runtime.
 The process of allocating memory at compile time is known as static memory allocation and the arrays that
receive static memory allocation are called static arrays.
 It is possible to allocate memory to arrays at runtime.
 This feature is known as dynamic memory allocation and the arrays created at runtime are called dynamic
arrays.

Character arrays and strings

 A string is a sequence of characters that is treated as a single data item.


 A group of characters define between double quotation marks is a string constant.
Ex: “Hello World:
 If we want to include a double quote in the string to be printed, then we may use it with a back slash
Ex: printf(“\” Well Done”\”);
Output: “Well Done”
 Character strings are often used to build meaningful and readable programs. The common operations
performed on character strings include:
1) Reading and writing strings
2) Combining strings together
3) Copying one string to another
4) Comparing strings for equality
5) Extracting a portion of a string

Declaring and initializing string variables:

 C does not support strings as a data type


 It allow us to represent strings as character arrays.
NASC-Department of Computer Applications [Computing Fundamentals and ‘C’ Programming] 45
 String variable is any valid c variable name and is always declared as an array of characters

Syntax:

char string_name[size];

Size determines the number of characters

Ex: char city[10];

 When the compiler assigns a character string to a character array, it automatically supplies a null character at
the end of the string.
 The size should be equal to maximum number of character in the string plus one.
 It may be initialized when they are declared.
 Two forms of initialization:
char city[9]=”New York”; (or)
char city[9]={‘n’,’e’,’w’,’ ‘,’y’,’o’,’r’,’k’,’\0’};
 Character array can be initialized without specifying the number of elements. The size will be determine
automatically, based on the number of elements initialized.
char string[]={‘G’,’O’,’O’,’D’,’\0’};
 We can also declare the size much larger than the string size in the initialize
char str[10]=”GOOD”;
the computer creates a character array of size 10, places the value “GOOD”, terminates with the null
character and initializes all other elements to NULL.

G O O D \0 \0 \0 \0 \0 \0

char str2[3]=”GOOD”; //compile time error


 We cannot separate initialization from declaration.
char str3[5];
str3=”GOOD”;
it is not allowed.
 An array name could not be used as an left operand of an assignment operator.
char s1[4]=”abc”;
char s2[4];
s2=s1;

Reading strings from terminal

Using scanf function:


 Can be used with %s format specification to read in a string of characters
Eg: char address[10];
scanf (%s”,address);
 Problem with scanf function is that it terminates its input on the first white space it finds.
Eg: NEW YORK
 Only the string “NEW” will be read in to the array address, the blank space after the word “NEW: will
terminate the reading of string.
 scanf automatically terminates the string that is read with a null character.
 If we want to read entire line “NEW YORK” then use two character arrays appropriate sizez.
char adr1[5], adr2[5];
scanf(%s%s”,adr1,adr2);
will assign the string adr1=NEW adr2= YORK.
 We can also specify the field width using the form %ws in the scanf statement for reading a specified
number of characters from the input string
scanf(“%ws”,name);
 Two things may happen:
1) Equal or greater - entire string will be stored
2) Less than - the excess characters will be truncated
char name[10];
NASC-Department of Computer Applications [Computing Fundamentals and ‘C’ Programming] 46
scanf(“%5s”,name);
 The input KRISHNA will be stored as

K R I S H \0 ? ? ? ?

Reading a line of text:


 Scanf read only strings without whitespaces. They cannot be used for reading a text containing more than one
word.
 C supports a format specification known as the edit set conversation code %[…] that can be used to read a
line containing variety of characters including whitespaces.
Eg: char line[80];
scanf(“%[^\n]”,line);
printf(“%s”,line);
will read a line of input from the keyboard and display the same on the screen.

Using getchar and gets function:


 getchar function is used to read successive single character from the input and place them into a
character array.
 An entire line of text can be read and stored in an array.
 The reading is terminated when the newline character(\n’) is entered.
char ch;
ch=getchar();
has no arguments or parameters.

Example:
main()
{
char line[81], character;
int c;
c=0;
do
{
character=getchar();
line[]=character;
c++;
}
while(character!=’\n’);
c=c-1;
line[c]=’\0’;
printf(“%s”,line);
}

gets function:
 Reading a string of test containing whitespaces
gets(str);
it reads character into str from the keyboard until a newline character is encountered and then appends a
null character to the string.
char line[80];
gets(line);
printf(“%s”,line);
reads a line of text from keyboard and displays a=it on the screen. The last two statements may be
combined into
printf(“%s”,gets(line));
 C does not provides operator that work on strings directly. We cannot assign one string to another directly.
string “ABC”;
string1=string2; // illegal

NASC-Department of Computer Applications [Computing Fundamentals and ‘C’ Programming] 47


Writing strings to screen

Using printf statement:


 It is used to print strings to the screen
 The format %s can be used to display an array of characters that is terminated by null character.
printf(“%s”,name);
can be used to display the entire contents of the array name.
 We can also specify the precision with which the array is displayed.
Eg: %10.4
indicates that the first four characters are to be printed in a field width of 10 columns.

Using putchar and puts function:

 putchar function is to output the values of character variables.


char ch=’A’;
putchar(ch);
requires one parameter.
Ex: char name[b]=”PAY”;
for(i=0;i<5;i++)
putchar(name[i]);

puts function:
 Another way of printing string values.
 Takes one parameter.
puts(str);
str is a string variable containing a string value.
 This prints the value of the string variable str and then removes the cursor to the beginning of the
next line of the screen.
char line[80];
gets(line);
puts(line);
reads a line of text from the keyboard and displays it on the screen.

Arithmetic operators on characters


 Whenever a character constant or variable is used in an expression, it is automatically converted into a integer
value by the system.
 The integer value depends on a local character set of the system.
 Eor ex, if the machine uses the ASCII representation then,
x=’a’;
printf(“%d\n”,x);
 It is also possible to perform arithmetic operations on the character constants and variables.
x=’z’-1; //valid statement
 In ASCII, the value of ‘z’ is 122, the statement will assign the value 121 to the variable x.
 Also use character constants is relational expression
ch>=’A’&&ch<=’z’;
would test whether the character contained in the variable ch is an upper case letter.
 We can convert a character digit to its equivalent integer value using the following relationships.
x=character – ‘0’;
where x is assigned as an integer variable and character contains the character digit.
 Let us assume that the character contains the digit 7.
x=ASCII value of ‘7’ – ASCII value of ‘0’
=55-48 =7
 The C library supports a function that converts a string of digits into their integer values.
x=atoi(string);
 x is an integer variable and string is a character array containing a string of digits.

Putting strings together


NASC-Department of Computer Applications [Computing Fundamentals and ‘C’ Programming] 48
 We cannot assign one string to another directly, we cannot join two strings together by the simple arithmetic
addition.
String3=string1+string2; //not valid
 The character from string1 and string2 should be copied into string3 one after the other. The size of the array
string3 should be large enough to hold the total characters.
 The process of combining two strings together is called concatenation.

Comparison of two strings


 To compare the two strings to be tested, character by character.
 The comparison is done until there is a mismatch or one of the string terminates into a null character, which
ever occurs first.

i=0;
while(str1[i]==str2[i]&&str1[i]!=’\0’&&str2[i]!=’\0’)
i=i+1;
if(str1[i]==’\0’&&str2[i]==’\0’)
printf(“stings are equal”);
else
printf(“stings are not equal”);

String handling functions


 There are four important string Handling functions in C language.
i. strlen( ) function
ii. strcpy( ) function
iii. strcat( ) function
iv. strcmp( ) function

strlen( ) Function:
 strlen( ) function is used to find the length of a character string.
Syntax:
n=strlen(string);
where i is an integer variable, which receives the value of the length of the string.
Ex: int n;
char st[20] = “Bangalore”;
n = strlen(st);

 This will return the length of the string 9 which is assigned to an integer variable n.
 Note that the null charcter „\0‟ available at the end of a string is not counted.

strcpy( ) Function:
 strcpy( ) function is used to copy from one string to another string.
Ex :
char city[15];
strcpy(city, “BANGALORE”) ;
 This will assign the string “BANGALORE” to the character variable city.
 Note that character value like
city = “BANGALORE”; cannot be assigned in C language.
Syntax:
strcpy(string1, string2);
assigns the contents of string2 to string1.

strcmp( ) Function:
 strcmp ( ) function is used to compare two character strings.
 It returns a 0 when two strings are identical. Otherwise it returns a numerical value which is the different in
ASCII values of the first mismatching character of the strings being compared.
Syntax:
strcmp(string1,string2);
Eg:
NASC-Department of Computer Applications [Computing Fundamentals and ‘C’ Programming] 49
strcmp(name1,name2);
strcmp(name1,”John);
strcmp(“Rom”,”ram”);
strcmp(“their”,”there”);
will return value -9 which is numeric difference between ASCII “I” and ASCII “r”. that is “I” minus
“r”.

strcat() Funcion:
 joins two strings together.
Syntax:
strcat(string1,string2);
 when function strcat is executed, string2 is appended to string1.
 By removing the null character at the end of the string1 and placing string2 from there.
 The string at string2 remains unchanged.
Part1 =
V E R Y \0
Part2 = G O O D \0
Part3= B A D \0
Executing of the statement
strcat(part1,part2);
will result in

Part1=
V E R Y G O O D \0

Part2 = G O O D \0
 Make sure that the size of the string1 is large enough to accommodate the final string.
 It may be also append a string constant to a string variable.
strcat(part1,part2);
 permits nesting of strcat function
strcat(strcat(string1,string2),string3);
the resultant string is stored in string1.

strncpy() Function:
 copies only the left most n character of the source string to the target string variable.
 This is three parameter function.
strncpy(s1,s2,5);
this statement copies the first 5 characters of the source string s2 into the target string s1.
 The first 5 characters may not include the terminating null character, we have to place it explicitly in
the 6th position of s2.

strncmp Function:
 This is three parameter function.
strncmp(s1,s2,n);
this compares the left most n characters of s1 to s2 and returns
a) 0 if they are equal
b) Negative number, if s1 sub string is less than s2 and
c) Positive number, otherwise
strncat Function:
 This is three parameter function.
strncat(s1,s2,n);
this cocatenate the left most n characters of s2 to end of s1
NASC-Department of Computer Applications [Computing Fundamentals and ‘C’ Programming] 50
s1:
B A L A \0
s2: G U R U S A M Y

After strncat(s1,s2,4) execution:

s1: B A L A G U R U \0

strstr Function:
 It is a two parameter function that can be used to locate a sub-string in a string.
Syntax:
strstr(s1,s2);
strstr(s1,”ABC”);
searches the string s1 to see whether the string s2 is contained in s1.
 If yes, the function returns the position of the first occurrence of the sub-string. Otherwise, it returns
a NULL pointer.
if(strstr(s1,s2)=NULL)
printf(“substring is not found”);\
else
printf(“s2 is a substring of s1);
 We also have function to determine the existence of a character in a string.
strrchr(s1,’m’);
will locate the last occurrence of character ‘m’ in the string s1.

Table of strings:
 A list of names can be treated as a table of strings and a two-dimensional character array can be used
to store the entire array.
 For example: a character array student[30][15] may be used to store a list of 30 names, each of
length not more than 15 characters.

C h a n d i g a r h
M a d r a s
A h m e d a b a d
H y d e r a b a d
B o m b a y

 This table can be conveniently stored in a character array city by using the following declaration:
char city[][]={“Chandigarh”,
“Madras”,
“Ahemedabad”,
“Hyderabad”,
“Bombay”
};
 To access the name of the ith city in the list, we write
City[i-1]
 And therefore city[10] denotes “Chandigarh”, city[1] denotes “Madras” and so on.

UNIT – IV

FUNCTIONS

Introduction :

 Functions are subprograms which are used to compute a value or perform a task.
NASC-Department of Computer Applications [Computing Fundamentals and ‘C’ Programming] 51
 They cannot be run independently and are always called by the main ( ) function or by some other
function.
 There are two kinds of functions
1. Library or built–in functions 2. User–designed functions
Library or built-in functions
 are used to perform standard operations.
 eg: squareroot of a number sqrt(x), absolute value fabs(x), scanf( ), printf( ).
 These functions are available along with the compiler and are used along with the required header
files such as math.h, stdio. h, string.h and so on at the beginning of the program.

User defined functions


 are self–contained blocks of statements which are written by the user to compute a value or to
perform a task.
 They can be called by the main() function repeatedly as per the requirement.

USES OF FUNCTIONS:
1. Functions are very much useful when a block of statements has to be written/executed again and
again.
2. Functions are useful when the program size is too large or complex.Functions are called to
perform each task sequentially from the main program. It is like a top-down modular programming
technique to solve a problem
3. Functions are also used to reduce the difficulties during debugging a program

DEFINITION OF FUNCTIONS:
 Afunction definition, also known as function implementation.
 It includes the following elementsL
1. Function name
2. Function type
3. List of parameters
4. Local variable declaration
5. Function statements and
6. A return statement.
 All six elements are grouped into two parts, namely,
 Function header(first three elements) and
 Function body(second three elements)

The general form of a function declaration is


type name (type arg1, type arg2 …….. type argn)
{
<local declaration >
--------------------
< statement block>
--------------------
return (variable or expression)
}

Function header:
 type is the data type of the value return by the function and arguments expected.
 arg1, arg2…. argn are the arguments (or) parameters which are variables which will receive values
form the calling program.
 They receive actual input values, they are often called as formal parameters.
 name is the name of function by which the function is called by the calling program.

Function body:

NASC-Department of Computer Applications [Computing Fundamentals and ‘C’ Programming] 52


 There is a local declaration of variables. These variables are referred as local variables, are used
only inside the function.
 The statement block consists of a set of statements and built-in functions which are executed when
the function is called.
 The result is return to the calling program through a return statement that normally appears at the
end of a function block.
 This function block starts and ends with braces { }.
 When a function reaches its return statement, the control is transferred back to the calling program.
 In the absence of a return statement, the closing brace acts as a void return.
 A local variable is a variable that is defined inside a function and used without having any role in the
communication between functions.
Examples:
float mul(float x, float y)
{
float result; /* local variable*/
result = x * y;
return(result); /* returns the result*/
}

RETURN VALUES AND THEIR TYPES


 A return statement that returns the value evaluated by the function.
 It is possible to pass to the called function any number of values, the called function can only return
only return one value per call, at the most.
 Syntax:
return;
OR
return(expression)
 The first return does not return any value.
 The control is immediately passed back to the callinf function.
 Example:
if(error)
return;
 The second form of return with an expression returns the value of the expression.
int mul(intx, int y)
{
int p;
/* p=x*y;
return(p); */
return(x*y);
}
 A function may have more than one return statements.
if(x<=0)
return(0);
else
return(1);
 All functions by default return integer data type.
 We can force a function to return a particular type of data by using a type specifier in the function
header.
 When a value is returned, it is automatically cast to the functions type.
int product(void)
{
return(2.5*3.0);
}
 Will return the value 7.
NASC-Department of Computer Applications [Computing Fundamentals and ‘C’ Programming] 53
FUNCTION CALLS:
 A function can be called by simply using the function name followed by a list of actual parameters
main()
{
int y ;
y = mul (10,5); / * function call * /
--------
}

int mul(int x,int y)


{
int p ; / * local variables x=10, y=5 * /
p= x * y ;
return(p);
}

 When the compiler encounters a function call the control is transferred to the function mul().
 This function is then executed line by line.
 The value of p is returned when the return statement is encountered.
 This value is assigned to y.
 There are many different ways to call a function.
mul(10,5);
mul(m,5);
mul(10,n);
mul(m,n);
mul(10,m+n);
mul(10,mul(m,n));
mul(expression1,expression2);
 A function which returns a value can be used in expressions like any other variable.
printf(“%d”,mul(p.q)); //valid
y=mul(p,q); //valid
if(mul(m,n)>total) printf(“large”); //valid
mul(a,b)=15; //invalid
 The declaration of parameter variables cannot be combined int sum (int a,b) is invalid.
 A function need not always receive values form the calling program.
 In such cases, functions have no formal parameters,
 To indicate that the parameter list is empty we use the keyword void between parenthesis as
void printline(void)
{
}
 This function neither receives any input values nor returns back any value.
 Many compilers accept an empty set of parenthesis without specifying anything as void printline ( )

Function declaration or prototypes:


 Like variables, all functions must be declared, before they are invoked.
 A function declaration provides the following information to the compiler
- The name of the function
- The Type of the value returned (return type)
- The number and the type of arguments that must be supplied in a call to the function.
- Terminating semicolon.
 When a function call is encountered, the compiler checks the function call with its declaration.
 A function declaration has the following syntax:
return type function name (type, type ….. type);
NASC-Department of Computer Applications [Computing Fundamentals and ‘C’ Programming] 54
 Ex: double cube(double);
 Parameter name do not need to be the same in the prototype declaration and the function definition.
 The types must match the types of parameters in the function definition, in number and order
otherwise compiler will produce an error.
 Use of parameter names is optional.
 If the function has no arguments, the list is written as void.
 The return type is optional, when the function returns integer type data.
 The return must be void if no value is returned.
int mul(int,int);
mul(int a, int b);
mul(int,int);
void mul(void);
 A prototype declaration may be placed in two places in a program.
1. Above main function. //global prototype
2. Inside a function definition. //local prototype

Category of functions:
 A function, depending on whether arguments are present or not and whether a value is returned or
not may belong to one of the following categories.

1. Function with no arguments and no return values:


-when a function has no arguments, it does not receive any data from the calling function
-when a function does not return a value, the calling function does not receive any data from the
called function.
-There is no data transfer between the calling function and the called function.

2. Function with arguments but no return values:

- The main function has no control over the way the functions receive input data.
- This type of function can accept data from calling function.
- In other words, you send data to the called function from calling function but you cannot send
result data back to the calling function.
-The arguments in the calling function are called actual arguments.
-The arguments in the called function are called formal arguments.
- The actual and formal arguments should match in number, type and order.
-The values of actual arguments are assigned to the formal arguments on a one to one basis, starting
with the first argument.
-When a function call is made, only a copy of the values of actual arguments is passed into the called
function.
-What occurs inside the function will have no effect on the variables used in the actual arguments.

NASC-Department of Computer Applications [Computing Fundamentals and ‘C’ Programming] 55


Example:
#include<stdio.h>
#include<conio.h>
void add(int x, int y) called function
{
    int result;
    result = x+y;
    printf("Sum of %d and %d is %d.\n\n",x,y,result);
}
void main()
{
    clrscr();
    add(30,15);
    add(63,49); calling function
    add(952,321);
    getch();
}

3. Function with arguments with Return values

-This type of function can send arguments (data) from the calling function to the called function
and wait for the result to be returned back from the called function back to the calling function.
- And this type of function is mostly used in programming world because it can do two way
communications; it can accept data as arguments as well as can send back data as return value.
- The data returned by the function can be used later in our program for further calculations.
- A self contained and independent function should behave like a “black box‟ that receives a
predefined form of input and output a desired value

Example:
#include<stdio.h>
#include<conio.h>
 int add(int x, int y)
{
NASC-Department of Computer Applications [Computing Fundamentals and ‘C’ Programming] 56
    int result;
    result = x+y;
    return(result);
}
 void main()
{
    int z;
    clrscr();
     z = add(952,321);
    printf("Result %d.\n\n",add(30,55));
    printf("Result %d.\n\n",z);
     getch();
}

4. Functions with no arguments but returns a value


-We may need a function which does not take any argument but only returns values to the calling
function then this type of function is useful.
- The best example of this type of function is “getchar()” library function which is declared in the
header file “stdio.h”.
- We can declare a similar library function of own.

Example:
#include<stdio.h>
#include<conio.h>
int send()
{
    int no1;
    printf("Enter a no : ");
    scanf("%d",&no1);
    return(no1);
}
void main()
{
    int z;
    clrscr();
    z = send();
    printf("\nYou entered : %d.", z);
    getch();
}

5. Function that returns multiple values


-So far, we have learned and seen that in a function, return statement was able to return only
single value.
NASC-Department of Computer Applications [Computing Fundamentals and ‘C’ Programming] 57
-That is because; a return statement can return only one value.
-We have used arguments to send values to the called function, in the same way we can also use
arguments to send back information to the calling function.
- The arguments that are used to send back data are called Output Parameters.
- It is a bit difficult because this type of function uses pointer.
-The mechanism of sending back information through arguments is achieved using what are
known as the address operator(&) and indirection operator(*).
-Instead of passing values we are passing directly the address of the variables from the calling
function to the called function.
- What occurs inside the function will have effect on the variables used in the actual arguments.

Example:
#include<stdio.h>
#include<conio.h>
 void calc(int x, int y, int *add, int *sub)
{
    *add = x+y;
    *sub = x-y;
}
void main()
{
    int a=20, b=11, p,q;
    clrscr();
    calc(a,b,&p,&q);
    printf("Sum = %d, Sub = %d",p,q);
    getch();
}

PASSING ARRAYS TO FUNCTIONS

Passing One-dimensional Array In Function


 Like the values of simple variables, it is also possible to pass the values of an array to a function.
 To pass one-dimensional array to a called function, it is sufficient to list the name of the
array, without any subscripts, and the size of the array as arguments.
 The name of the array represents the address of the first element.
 By passing the array name, we are passing the address of the array to the called function.
 The array in the called function refers to the same array stored in the memory.
 Any changes in the array in the called function will be reflected in the original array.
 Passing address of parameters to the functions is referred to as pass by address.
Example:
void main()
{
float largest(float a[], int n);
float value[4]={2.5,-4.75,1.2,3.46};
printf(“%f”, largest(value,4));
}
float largest(float a[], int n)
{
int n;
float max;
max=a[0];
for(i=1;i<n;i++)
if(max<a[i])

NASC-Department of Computer Applications [Computing Fundamentals and ‘C’ Programming] 58


max=a[i];
return(max);
}

Passing Two-dimensional Arrays to Function


 We can also pass multi-dimensional arrays to functions.
 The function must be called by passing only the array name.
 In the function definition, we must indicate that the array has two-dimensions by including two
sets of brackets.
 The size of the second must be specified.
 The prototype declaration should be similar to the function header.
Example:
double average(int x[][n], int m, int n)
{
int i,j;
double sum=0.0;
for(i=0;i<m;i++)
for(j=1;j<n;j++)
sum+=x[i][j];
return(sum/(m*n));
}
-The function can be used in the main function as
main()
{
int m=3, n=2;
double average(int[][n], int, int);
double mean;
int matrix[m][n] ={{1,2}, {3,4}, {5,6}};
mean=average(matrix,m,n)
____
____
}

PASSING STRINGS TO FUNCTIONS


 The strings are treated as character arrays and therefore the rules for passing strings are very
similar to those for passing arrays to functions.
 The strings to be passed must be declared as a formal argument of the function when it is defined.
void display(char item_name[])
{
____
____
}
 The function prototype must show that the argument is a string.
void display(char str[]);
 A call to the function must have a string array must without subscripts as its actual argument.
display(name);

THE SCOPE, VISIBILITY AND LIFETIME OF VARIABLES


 Variables differ in behavior in different languages.
 In C not only do all variables have a data type, they also have a storage class. They are
1. Automatic variables
2. External variables
3. Static variables
4. Register variables

NASC-Department of Computer Applications [Computing Fundamentals and ‘C’ Programming] 59


 Scope of a variable determines over what region of the program a variable is actually available for
use. (Active)
 Lifetime refers to the period during which a variable retains a given value during execution of a
program. (Alive)
 Visibility refers to the accessibility of a variable from the memory.
 The variables are classified, depending on the place of their declaration,
1. Internal (local) - declared within particular functions.
2. External (global) – declared outside of any function.

Automatic variables
 Declared inside a function in which they are to be utilized.
 They are creates when the function is called and destroyed automatically when the function is
exited, hence the name automatic.
 They are local to the function in which they are declared.
 Also called local or internal variables.
 It is the default storage class for all local variables.
 The keyword auto is explicitly used to declare automatic variables.
main() main()
{ {
int number; (or) auto int number;
___ ___
___ ___
} }

Register variables
 The register storage class is used to define local variables that should be stored in a register
instead of RAM.
 A variable can be kept in one of the machine’s registers, instead of keeping in the memory.
 It is faster than a memory access, keeping the frequently accessed variables in the register will
lead to faster execution of program.
 Only a few variables can be placed in the register.
 C will automatically convert the register variable into non-register variables once the limit is
reached.
 Keyword register is used to declare the register variables.
register int count;

Static variables
 The value of the variable remains constant until the end of the program.
 A variable can be declared using the keyword static
static int x;
 It may be either internal or external type depending on the place of declaration.
 Internal static variables are declared inside a function.
 The scope of a variable is extended up to end of the function in which they are defined.
 It is used to retain values between function calls.

Example:
void stat(void);
main()
{
int i;
for(i=1;i<3;i++)
stat();
}
void stat(void)
NASC-Department of Computer Applications [Computing Fundamentals and ‘C’ Programming] 60
{
static int x=0;
x=x+1;
printf(“x=%d”, x);
}

OUTPUT:
x=1 x=2 x=3
 An external static variable is declared outside of all functions and is available to all functions in
that program.
 The static external variables is available only within the file where it is defined while simple
external variable can be accessed by other files.

External variables
 Variables that are both alive and active throughout the entire program are known as external
variables.
 Also called as global variables.
 Declared outside the function and can be accessed by any function in the program.
 Once a variable has been declared as global, any function can use it and change its value.
 Global variables are accessed in the program where it is declared. We cannot access the global
variables from one file to another file.
Example:
int a=2 Global variable
void main()
{
int a=10; Local variable
printf(“a=%d”,a);
}
 If we want to access the global variables from one file to another file we have to define that
variable using extern keyword.
 The extern storage class is used to give a reference of a global variable that is visible to
ALL the program files.
 extern  is used to declare a global variable or function in another file.
 The extern modifier is most commonly used when there are two or more files sharing the
same global variables or functions.
Example: First File: main.c
#include<stdio.h>
int count;
extern void write_extern();
main()
{
count=5;
write_extern();
}

Second File: support.c


#include<stdio.h>
int count;
void write_extern(void)
{
Printf(“count is %d”, count);
}

S. Storage Storage Initial / Scope Life


No. Specifier place default value
NASC-Department of Computer Applications [Computing Fundamentals and ‘C’ Programming] 61
1 auto CPU Garbage local Within the function only.
Memory value
2 extern CPU Zero Global Till the end of the main
memory program.
Variable definition might be
anywhere in the C program
3 static CPU Zero local Retains the value of the
memory variable
between different function
calls.
4 register Register Garbage local Within the function
memory value

NESTED BLOCKS
 A set of statements in a set of braces is known as block or a compound statement.
 A block can have its own declarations and other statements.
 It is also possible to have a block of such statements inside the body of a function or another block,
thus creating what is known as nested blocks.
Example:
main()
{
int a=20;
int b=10;
{ Outer
int a=0; Inner Block
int c=a+b; Block
____
}
b=a;
}
STRUCTURES
 A collection of variables that are functionally related to each other.
 Each variable that is a member of the structure has a specific type.
Defining a structure
 C arrays allow you to define type of variables that can hold several data items of the same kind.
 Structure is user defined data type, which allows you to combine data items of different kinds.
 Structures are used to represent a record, Suppose you want to keep track of your books in a
library. You might want to track the following attributes about each book:
Title, Author, Subject, Book ID, etc.
 To define a structure, you must use the struct statement.
 The struct statement defines a new data type, with more than one member for your program.
Syntax:
struct tag_name
{
data_type member 1;
data_type member 2;
------------
-------------
data_type member m;
};
 The data fields are called structure elements or members.
 Tag_name is the name of the structure and it is optional.
 The structure is terminated with a semicolon.
 Each member is declared independently for its name and type in a separate statement inside the
NASC-Department of Computer Applications [Computing Fundamentals and ‘C’ Programming] 62
structure.
 The tag name can be used to declare structure variables.
Tag name (optional)
struct student
{
char name [80];
int roll_no; structure elements or members
float marks;
};

Declaring structure variables


 A structure variable declaration is similar to the declaration of variables of any other data types.
 It includes the following elements:
1. The keyword struct.
2. The structure tag name.
3. List of variable names separated by comma.
4. A terminating semicolon.
Example:
struct student s1, s2;
 declares s1, s2 as variables of structure type struct student.
 Each one of these variables have three members as specified by the structure.
 It is allowed to combine both the structure definition and variables declaration in one statement.
struct student
{
char name [80];
int roll_no;
float marks;
}s1, s2;
 Members of the structures are not variables.
 They do not occupy any memory until they are associated with the structure variables.
Accessing structure members
 We can access and assign values to the members of a structure in number of ways.
 The link between a member and a variable is established using the member operator ‘.’ Which
is also known as ‘dot operator’ or ‘ period operator’
 Syntax:
variable.member name.
 Example:
S1.name;
S1.marks;
 We can assign values to the members like
S1.name=”abc”;
S1.marks=67;
 We can also use scanf to give the values through the keyboard.
scanf(“%s”, s1.name);
scanf(“%f”, s1.marks);

Structure Initialization
 Like any other data type, a structure variable can be initialized at compile time.
 The compile time initialization of a structure variable must have the following elements:
1. The keyword struct
2. The structure tag name.
3. The name of the variable to be declared.
4. The assignment operator =
5. A set of values for the members of the structure variable, separated by commas and

NASC-Department of Computer Applications [Computing Fundamentals and ‘C’ Programming] 63


enclosed in braces.
6. A terminating semicolon.
struct student struct student
{ {
char name [80]; (OR) char name [80];
int roll_no; int roll_no;
float marks; float marks;
} };
S1={“abc”, 123, 65}; S1={“abc”, 123, 65};
S2={“xyz”, 234, 76};
 Another method is to initialize a structure variable outside the function as
struct student
{
char name [80];
int roll_no;
float marks;
} S1={“abc”, 123, 65};
main()
{
struct student s2=={“xyz”, 234, 76};
--------
--------
}
Type Using normal variable Using pointer variabe

struct tag_name struct tag_name


{ {
data type var_name1; data type var_name1;
Syntax
data type var_name2; data type var_name2;
data type var_name3; data type var_name3;
}; };

struct student struct student
{ {
int roll_no; int  roll_no;
Example
char name[80]; char name[80];
float marks; float marks;
}; };

Declaring structure variable struct student s1; struct student *s1, s2;

struct student s1 = {100, “Mani”, struct student s2 = {100, “Mani”, 99.5};


Initializing structure variable
99.5}; s1 = &s2;

S1.roll_no S1  -> roll_no


Accessing structure members s1.name s1 -> name
s1.marks s1 -> marks

Copying and comparing structure variables


 Two variables of the same structure type can be copied the same way as ordinary variables.
 Example:
s1=s2; or s2=s1; //valid
NASC-Department of Computer Applications [Computing Fundamentals and ‘C’ Programming] 64
 s1 and s2 belongs to the same structure student.
 We cannot compare structure variables directly.
 We may compare members individually.
s1==s2; // in valid

struct student
{
char name [80];
int roll_no;
float marks;
}s1;
main()
{
struct student s2=={“xyz”, 234, 76};
s2=s1; copying
if((s2.name==s1.name))&&(s2.marks==s1.marks)) comparing
{
printf(“s1 and s2 are same”);
}
else
{
printf(“s1 and s2 are same”);
}

Operations on individual members


 The individual members are identified using the member operator, the dot.
 It can be treated like a normal variable. So we can perform operations.
if(s1.roll_no==111)
s1.marks+=20.00;
float sum=s1.marks+s2.marks;
 We can also apply increment and decrement operators to numeric type members.
s1.marks++;
++s1.marks;
 The precedence of the member operator is higher than all arithmetic and relational operators
and therefore no parentheses are required.
Array of structures
 C Structure is collection of different datatypes ( variables ) which are grouped together.
 Whereas, array of structures is nothing but collection of structures. This is also called as
structure array in C.
struct student
{
int roll_no;
char name[80];
float marks;
};
void main()
{
int i;
struct student s1[3];
s1[0].roll_no=1;
strcpy(s1[0].name,"Raju"); 1st student record
s1[0].marks = 86.5;

s1[1].roll_no=2;
strcpy(s1[1].name,"Raja"); 2nd student record
NASC-Department of Computer Applications [Computing Fundamentals and ‘C’ Programming] 65
s1[1].marks = 86;

s1[2].roll_no=3;
strcpy(s1[2].name,"Raj"); 3rd student record
s1[2].marks = 85;

for(i=0; i<3; i++)


{
printf(" Records of STUDENT : %d \n", i+1);
printf(" Roll_no is: %d \n", s1[i].roll_id);
printf(" Name is: %s \n", s1[i].name);
printf(" Marks is: %f\n\n",s1[i].marks);
}
}
Example program for declaring many structure variable in C:
struct student
{
int id;
char name[30];
float percentage;
};
void main()
{
int i;
struct student record1 = {1, "Raju", 90.5};
struct student record2 = {2, "Mani", 93.5};

printf("Records of STUDENT1: \n");


printf(" Id is: %d \n", record1.id);
printf(" Name is: %s \n", record1.name);
printf(" Percentage is: %f \n\n", record1.percentage);

printf("Records of STUDENT2: \n");


printf(" Id is: %d \n", record2.id);
printf(" Name is: %s \n", record2.name);
printf(" Percentage is: %f \n\n", record2.percentage);
}
Arrays within structures
 C permits the use of arrays as structure members.
 Example:
struct marks
{
int number;
float subject[3];
}s1[2];
 Member subject contain three elements, subject[0], subject[1], subject[2].
s1[1].subject[2];
 would refer to the marks obtained in the third subject by the second student.
Structures within structures
 Nested structure in C is nothing but structure within structure.
 One structure can be declared inside other structure as we declare structure members inside
a structure.
struct student_college_detail
{
NASC-Department of Computer Applications [Computing Fundamentals and ‘C’ Programming] 66
int college_id;
char college_name[50];
};

struct student_detail
{
int id;
char name[20];
float percentage; structure within structure
struct student_college_detail clg_data;
}stu_data;

int main()
{
struct student_detail stu_data = {1, "Raju", 90.5, 71145,
"Anna University"};
printf(" Id is: %d \n", stu_data.id);
printf(" Name is: %s \n", stu_data.name);
printf(" Percentage is: %f \n\n", stu_data.percentage);

printf(" College Id is: %d \n",


stu_data.clg_data.college_id);
printf(" College Name is: %s \n",
stu_data.clg_data.college_name);
return 0;
}

Structures and Functions


 C supports the passing of structure values as arguments to functions.
 There are three methods by which the values of a structure can be transferred from one function
to another.
1. Passing structure to a function by value(sending a copy of the structure)
2. Passing structure to a function by address(reference)(sending original structure)
3. No need to pass a structure – Declare structure variable as global
 The general format of sending a copy of a structure to the called function is:
function_name(structure_variable_name);
 The called function takes the following form:
data_type function_name(struct_type st_name)
{
------
------
return(expression);
}
 The called function must be declared for its type, appropriate to the data type it is expected to return.
 For example, if it is returning a copy of the entire structure, then it must be declared as struct with
an appropriate tag name.
 The structure variable used as the actual argument and the corresponding formal argument in the
called function must be of the same struct type.
 The return statement is necessary only when the function is returning some value.
 When a function returns a structure, it must be assigned to a structure of identical type in the calling
function.
 The called functions must be declared in the calling function appropriately.

struct student
{
NASC-Department of Computer Applications [Computing Fundamentals and ‘C’ Programming] 67
int id;
char name[20];
float percentage;
};
void func(struct student record);

int main()
{
struct student record;

record.id=1;
strcpy(record.name, "Raju");
record.percentage = 86.5;

func(record);
return 0;
}

void func(struct student record)


{
printf(" Id is: %d \n", record.id);
printf(" Name is: %s \n", record.name);
printf(" Percentage is: %f \n", record.percentage);
}

UNIONS
 C Union is also like structure, i.e. collection of different data types which are grouped together.
 Each element in a union is called member.
 Union and structure in C are same in concepts, except allocating memory for their members.
 Structure allocates storage space for all its members separately.
 Whereas, Union allocates one common storage space for all its members
 We can access only one member of union at a time. We can’t access all member values at the same
time in union.
 But, structure can access all member values at the same time. This is because; Union allocates one
common storage space for all its members. Whereas Structure allocates storage space for all its
members separately.
 Many union variables can be created in a program and memory will be allocated for each union
variable separately.
 Below table will help you how to form a C union, declare a union, initializing and accessing the members of
the union.
Type Using normal variable Using pointer variable

union tag_name union tag_name
{ {
data type var_name1; data type var_name1;
Syntax
data type var_name2; data type var_name2;
data type var_name3; data type var_name3;
}; };

Example union student union student


{ {
int  mark; int  mark;
char name[10]; char name[10];

NASC-Department of Computer Applications [Computing Fundamentals and ‘C’ Programming] 68


float average; float average;
}; };

Declaring
union student report; union student *report, rep;
union variable

Initializing union student report = {100, “Mani”, union student rep = {100, “Mani”,


union variable 99.5}; 99.5};report = &rep;

report.mark report  -> mark


Accessing
report.name report -> name
union members
report.average report -> average

Example program for C union:


union student
{
char name[20];
char subject[20];
float percentage;
};
void main()
{
union student record1;
union student record2;
strcpy(record1.name, "Raju");
strcpy(record1.subject, "Maths"); assigning values to record1
record1.percentage = 86.50;
printf("Union record1 values example\n");
printf(" Name : %s \n", record1.name);
printf(" Subject : %s \n", record1.subject);
printf(" Percentage : %f \n\n", record1.percentage);
printf("Union record2 values example\n");
strcpy(record2.name, "Mani");
strcpy(record2.subject, "Physics"); assigning values to record2
record2.percentage = 99.50;
printf(" Name : %s \n", record2.name);
printf(" Subject : %s \n", record2.subject);
printf(" Percentage : %f \n", record2.percentage);
}
Difference between structure and union in C:
S.no C Structure C Union

Union allocates one common storage space for all its members.
1 Structure allocates storage space Union finds that which of its member needs high storage space over
for all its members separately. other members and allocates that much space

Structure occupies higher


2 Union occupies lower memory space over structure.
memory space.

We can access all members of


3 We can access only one member of union at a time.
structure at a time.

4 Structure example: Union example:


NASC-Department of Computer Applications [Computing Fundamentals and ‘C’ Programming] 69
struct student union student
{ {
int mark; int mark;
char name[6]; char name[6];
double average; double average;
}; };

For above structure, memory


allocation will be like below.
For above union, only 8 bytes of memory will be allocated since
int mark – 2B
double data type will occupy maximum space of memory over other
 5 char name[6] – 6B
data types. 
double average – 8B 
Total memory allocation = 8 Bytes
Total memory allocation = 2+6+8
= 16 Bytes

Size of structures
 We use structures, unions, and arrays to create variables of large size.
 The actual size of these variables in terms of bytes may change from machine to machine.
 We may use the unary operator sizeof to tell us the size of a structure.
sizeof(struct x)
 will evaluate the number of bytes required to hold all the members of the structure of x.
 If y is a simple structure variable of type struct x, then the expression
sizeof(y)
 would also give the same answer.
 If y is an array variable of type struct x, then
sizeof(y)
 would give the total number of bytes the array y requires.

BIT FIELDS
 In C, we can specify size (in bits) of structure and union members.
 The idea is to use memory efficiently when we know that the value of a field or group of fields will
never exceed a limit or is within a small range.
 The basic reason is to reduce the size used. Bit fields do save space.
 A bit field is a set of adjacent bits whose size can be from 1 to 16 bits in length.
 A word can be divided into a number of bit fields.
 The name and size of bit fields are defined using a structure.
 The general form of bit field definition is:
struct tag_name
{
data_type name1: bit-length;
data_type name2: bit-length;
-----
-----
data_type nameN: bit-length;
}
 The data_type is either int or unsigned int or signed int.
 The bit-length is the number of bits used for the specified name.
 Signed bit should have at least 2 bits(one bit for sign).
 The variables defined with a predefined width are called bit fields.
 A bit field can hold more than a single bit for example if you need a variable to store a value from 0
to 7 only then you can define a bit field with a width of 3 bits 
struct

NASC-Department of Computer Applications [Computing Fundamentals and ‘C’ Programming] 70


{
unsigned int age : 3;
}Age;
void main()
{
Age.age=4;
printf(“Size(Age) : %d”, size(Age));
printf(“Age.age : %d”, Age.age);
Age.age=7;
printf(“Age.age : %d”, Age.age);
Age.age=8;
printf(“Age.age : %d”, Age.age);
}

UNIT V

POINTERS
 Pointer is derived data type.
 It contains memory addresses as their values.
 C Pointer is a variable that stores/points the address of another variable. 
 C Pointer is used to allocate memory dynamically i.e. at run time. 
 The pointer variable might be belonging to any of the data type such as int, float, char, double, etc.
 Benefits of pointers are:
1. Efficient in handling arrays and data tables.
2. Used to return multiple values from a function.
3. Support dynamic memory management.
4. Reduce length and complexity of programs.
5. Increase the execution speed and thus reduce the program execution time.
6. Permits references to functions.
7. Use of pointer arrays result in saving of data storage space in memory.

Understanding pointers

 The computer’s memory is a sequential collection of storage cells.


 Each cell, commonly known as a byte, has a number called address associated with it.
 The address is numbered, starting from zero.
 The last address depends on the memory size.
 A computer system having 64k memory will have its last address as 65,535.
Address Memory cell
0
1
2
-
-
65,535
Fig: Memory organization
 Consider the following statement:
int quantity=179;
 This statement instructs the system to find a location for the integer variable quantity and puts the
value 179 in that location.
quantity variable
NASC-Department of Computer Applications [Computing Fundamentals and ‘C’ Programming] 71
179 value

5000 Address
Fig: Representation of variables
What are Pointers?

 Different from other normal variables which can store values, pointers are special variables that can
hold the address of a variable.
 Since they store memory address of a variable, the pointers are very commonly said to “point to
variables”.

 Let’s try to understand the concept.

As shown in the above diagram:


 A normal variable ‘var’ has a memory address of 1001 and holds a value 50.
 A pointer variable has its own address 2047 but stores 1001, which is the address of the variable
‘var’

Accessing the address of a variable

 The actual location of a variable in the memory is system dependent and the address of a variable is
not known to us immediately.
 The & operator immediately preceding a variable returns the address of the variable.
p=&quantity;
 The & operator can be remembered as ‘address of’.

Declaring pointer variables

 Syntax:
data_type *pt_name;
 This tells the compiler three things about the variable
1. The asterisk (*) tells that the variable is a pointer variable.
2. pt_name needs a memory location.
3. pt_name points to a variable of type data_type.
 Example:
int *p;

Initialization of pointer variables

 The process of assigning the address of a variable to a pointer variable is known as initialization.

NASC-Department of Computer Applications [Computing Fundamentals and ‘C’ Programming] 72


 Once the pointer variable has been declared we can use the assignment operator to initialize the
variable.
 We must ensure that the pointer variable always point to the corresponding type of data.
 Example:
int quantity;
int *p;
float *q;
p=&quantity; // legal
q=&quantity; // illegal

int x, *p=&x; // legal


int *p=&x, x; //illegal
 We could also define a pointer variable with an initial value of NULL or 0.
 This variable is called NULL pointer.

int *p=NULL;
int *p=0;

Accessing a variable through its pointer

 This is done by using unary operator * (asterisk), usually known as indirection operator (or)
dereferencing operator.
void main()
{
int a,c;
int *b;
a=100;
b=&a; equivalent to c=*&a; equal to c=a;
c=*b;
printf(“The value of c is:%d”, c);
}

Chain of pointers

 A pointer to a pointer is a form of multiple indirection, or a chain of pointers.


 Normally, a pointer contains the address of a variable.
 When we define a pointer to a pointer, the first pointer contains the address of the second pointer,
which points to the location that contains the actual value as shown below.

 A variable that is a pointer to a pointer must be declared as such.


 This is done by placing an additional asterisk in front of its name.
 For example, following is the declaration to declare a pointer to a pointer of type int:
int **var;
 When a target value is indirectly pointed to by a pointer to a pointer, accessing that value requires
that the asterisk operator be applied twice.
void main()
{
int x, *p1, **p2;
x=100;
p1=&x;
p2=&p1;

NASC-Department of Computer Applications [Computing Fundamentals and ‘C’ Programming] 73


printf(“%d”, **p2);
}

Pointer expressions

 Pointer variables can be used in expressions.


 If p1 and p2 are pointers, then the following statements are valid.
y=*p1 * *p2; same as (*p1) * (*p2)
sum=sum + *p1;
z=5*-*p2/ *p1; same as (5 * (- (*p2)))/(*p1)
*p2=*p2 +10;
 The following statement is invalid
z=5*-*p2 /*p1; //invalid because /* is comment line.

 We can also use shorthand operators with the pointers.


p1++;
p2--;
sum+=*p2;
 Pointers can also be compared using the relational operators.

Pointer increments and scale factors

 The pointers can be incremented like:


p1=p2 +2;
 An expression like:
p1++;
 will cause p1 to point to the next value of its type.
 For example, if p1 is an integer pointer with an initial value say, 2800, after the operation p1++, the
value of p1 will be 2802.
 That is when we increment a pointer; its value is incremented by the ‘length’ of the data type that it
points to.
 The length called the scale factor.
 The number of bytes used to store various data types depend on the system and can be found by
making use of the sizeof operator.

Pointers and arrays

 When an array is declared, compiler allocates sufficient amount of memory to contain all the
elements of the array.
NASC-Department of Computer Applications [Computing Fundamentals and ‘C’ Programming] 74
 Base address which gives location of the first element is also allocated by the compiler.
 Suppose we declare an array arr,
int arr[5]={1,2,3,4,5};
 Assuming that the base address of arr is 1000 and each integer requires two byte, the five element
will be stored as follows

 Here variable arr will give the base address, which is a constant pointer pointing to the
element, arr[0]. Therefore arr is containing the address of arr[0] i.e 1000.
arr is equal to &arr[0] // by default
 We can declare a pointer of type int to point to the array arr.
int *p;
p=arr;
or p=&arr[0]; // both the statements are equal
 Now we can access every element of array arr using p++ to move from one element to another.
 You cannot decrement a pointer once incremented. p--won't work.
 We can use a pointer to point to an Array, and then we can use that pointer to access the array.
int i;
int a[5]={1,2,3,4,5};
int *p=a; //same as int *p=&a[0];
for(i=0;i<5;i++)
{
Printf(“%d”, *p);
P++;
}
 In the above program, the pointer *p will print all the values stored in the array one by one. We can
also use the Base address (a in above case) to act as pointer and print all the values.

NASC-Department of Computer Applications [Computing Fundamentals and ‘C’ Programming] 75


 Pointers can also used to manipulate two-dimensional arrays.
 An element in a two-dimensional array can be represented by the pointer expression:
*(*(a+i)+j) or (*(p+i)+j)

Pointers and character strings

 C supports an alternative method to create strings using pointer variables of type char.
Char *str=”good”;
 This creates a string and then stores its address in the pointer variable str.
 The compiler automatically inserts the null character ‘\0’ at the end of the string.
 The pointer str points to the first character of the string “good”.
 We can also use the run-time assignment for giving valus to a string pointer.
char *string1;
string1=”good”;
 We can print the content of the string string1 using either printf or puts function:
printf(“%s”, string1);
puts(string1)
main()
{
char *name;
int length;
char *cptr=name;
name=”DELHI”;
printf(“%s”, name);
while(*cptr!=’\0’)
{
printf(%c is stored at address %u”, *cptr, cptr);
cptr++;
}
length=cptr-name;
printf(“Length of the string=%d”, length);
}

NASC-Department of Computer Applications [Computing Fundamentals and ‘C’ Programming] 76


Array of pointers

 One important use of pointers is in handling of a table of strings.


char name[3][25];
 This says thus the name is a table containing three names, each with a maximum length of 25
characters including null characters.
 This declaration allocates 75 bytes.
 Instead of making each row a fixed number of characters, we can make it a pointer to a string of
varying length.
char *name[3]={
“New Zealand”,
“Australia”,
“India”
};
 Declares name to be an array of three pointers to characters, ach pointer pointing to a particular
name as:
name[0]= New Zealand
name[1]= Australia
name[2]= India
 This declaration allocates only 28 bytes, sufficient to hold all the characters.
 The following statements would print out all the three names:
for(i=0;i<=2;i++)
printf(“%s”, name[i]);
 To access the jth character in the ith name,
*(name[i]+j)
 The character arrays with the rows of varying length are called “ragged arrays”.
 *p[3] declares p as an array of 3 pointers.
 (*p)[3] declares p as a pointer to an array of three elements.
 Since * has a lower precedence than [].

Pointers as function arguments

 C programming language allows you to pass a pointer to a function.


 To do so, simply declare the function parameter as a pointer type.
 The process of calling a function using pointers to pass the address of variables is known as “call by
reference”.
 The function which is called by reference can change the value of the variable used in the call.
 This mechanism is also called as “call by address” or “call by pointers”.
 Example:
void exchange(int *, int *); //function prototype
main()
{
int x,y;
x=100;
y=200;
printf(“Before Exchange: x=%d y=%d”, x,y);
exchange(&x,&y); //function call
printf(“After Exchange: x=%d y=%d”, x,y);
}
exchange(int *a, int *b)
{
NASC-Department of Computer Applications [Computing Fundamentals and ‘C’ Programming] 77
int t;
t=*a; //Assign the value at address a to t
*a=*b; // put b into a
*b=t; // put t into b
}
 Output:
Before exchange: x=100 y=200
After exchange: x=200 y=100

Functions returning pointers

 Since pointers are data types in C, we can also force a function to return a pointer to the calling
function.
 Example:
int *larger(int *, int *);
main()
{
int a=10;
int b=20;
int *p;
p=larger(&a, &b); //function call
printf(“%d”, *p);
}
int *larger(int *x, int *y)
{
if(*x>*y)
return(x); //address of a
else
return(y); //address of b
}

Pointers to functions

 A function, like a variable, has a type and an address location in the memory.
 It is possible to declare a pointer to a function, which can then be used as an argument in another
function.
type (*fptr) (); //pointer to a function
 This tells the compiler that fptr is a pointer to a function, which returns type value.
 The parentheses around *fptr are necessary.
type *gptr();
 would declare gptr as a function returning a pointer to type.
 We can make a function pointer to point to a specific function by simply assigning the name of the
function to the pointer.
double mul(int, int);
double (*p1) ();
p1=mul;
 declare p1 as a pointer to a function and mul as a function and then make p1 to point to the function
mul.
 To call the function mul, we may now use the pointer p1 with the list of parameters.
(*p1)(x,y); //function call
 is equivalent to
mul(x,y);
 Example:
NASC-Department of Computer Applications [Computing Fundamentals and ‘C’ Programming] 78
void dislay();
int main()
{
void *(*ptr) ();
ptr=&display;
(*ptr) ();
return(0);
}
void display()
{
printf(“Hello World”);
}

Pointers and structures

 Pointers can be accessed along with structures.


 A pointer variable of structure can be created as below:
struct name{
member1;
member2;
----
};
struct name *ptr;

 Here, the pointer variable of type struct name is created.


 Structure's member through pointer can be used in two ways:
1. Referencing pointer to another address to access memory
2. Using dynamic memory allocation
 Example:
struct name{
int a;
float b;
};
void main()
{
struct name *ptr, p;
ptr=&p; //referencing pointer to memory address of p
printf(“Enter integer:”);
scanf(“%d”, &(*ptr).a);
printf(“Enter number:”);
scanf(“%d”, &(*ptr).b);
printf(“Displaying:”);
printf(“%d %f”, (*ptr).a, (*ptr).b);
}

 In this example, the pointer variable of type struct name is referenced to the address of p.
 Then, only the structure member through pointer can can accessed.
 Structure pointer member can also be accessed using -> operator.
(*ptr).a is same as ptr->a
(*ptr).b is same as ptr->b
 The operators ‘->’ ‘.’ () and [] have the highest priority among the operators.

struct{
int count;
float p; //pointer inside the struct
NASC-Department of Computer Applications [Computing Fundamentals and ‘C’ Programming] 79
}ptr; // struct type pointer

 The following statements:

++ptr->count; //increments count not ptr


(++ptr)->count; // increments ptr and then links count
Ptr++->count; //access count and increment ptr

*ptr->p //fetches whatever p points to


*ptr->p++; //increments p after accessing whatever it points to
(*ptr->p)++; // increments whatever p points to.
*ptr++->p //increments ptr after accessing whatever it points to

FILES

 A file is a place on disk where group of related data are stored.


 C supports a number of functions that have the ability to perform basic file operations, which
include:

1. Naming a file
2. Opening the file
3. Reading data from the file
4. Writing data to the file
5. Closing the file

 There are two distinct ways to perform file operations in C.


 The first one is known as the low level I/O and uses UNIX system calls.
 The second method is referred to as the high level I/O operation and uses functions in C's standard I/O
library.
Function name Operations
fopen() Creates a new file for use
Opens an existing file for use
fclose() Closes a file which has been opened for use
getc() Reads a character from a file
putc() Writes a character to a file
fprintf() Writes a set of data values to a file
fscanf() Reads a set of data values from a file
getw() Reads an integer from a file
putw() Writes an integer to a file
fseek() Sets the position to a desired point in the file
ftell() Gives the current position in the file
rewind() Sets the position to the beginning of the file

Defining and opening a file

 C communicates with files using a new data type called a file pointer.
 This type is defined within stdio. h, and written as FILE *.
 A file pointer called output_file is declared in a statement like e
FILE *output_file;
 If we want to store data in a file into the secondary memory, we must specify certain things about
the file to the operating system.
 They include the filename, data structure, purpose.
 The general format of the function used for opening a file is
NASC-Department of Computer Applications [Computing Fundamentals and ‘C’ Programming] 80
FILE *fp;
fp = fopen("filename", "mode");
 The first statement declares the variable fp as a pointer to the data type FILE.
 As stated earlier, File is a structure that is defined in the I/O Library.
 The second statement opens the file named filename and assigns an identifier to the FILE type
pointer fp.
 This pointer, which contains all the information about the file, is subsequently used as a
communication link between the system and the program.
 The second statement also specifies the purpose of opening the file. The mode does this job.
r open the file for read only.
w open the file for writing only.
a open the file for appending data to it.
r+ open an existing file for update (reading and writing)
w+ create a new file for update. If it already exists, it will be overwritten.
a+ open for append; open for update at the end of the file
 Consider the following statements:
FILE *p1, *p2;
p1=fopen(“data”,”r”);
p2=fopen(“results”,”w”);

 In these statements the p1 and p2 are created and assigned to open the files data and results
respectively the file data is opened for reading and result is opened for writing.
 In case the results file already exists, its contents are deleted and the files are opened as a new file.
 If the data file does not exist error will occur.

Closing the File:

 The input output library supports the function to close a file; it is in the following format.
f close(file_pointer);

 A file must be closed as soon as all operations on it have been completed.


 This would close the file associated with the file pointer.

FILE *p1 *p2;


p1=fopen(“Input”, “w”);
p2 = fopen ("Output" ,"r");
……
……
fclose(p1);
fclose(p2);

 The above program opens two files and closes them after all operations on them are completed,
once a file is closed its file pointer can be reversed on other file.
Input/Output operations on files

The getc() and putc() functions

 The getc and putc functions are analogous to getchar and putchar functions and handle one character
at a time.
 The putc function writes the character contained in character variable c to the file associated with the
pointer fp1.
putc(c,fpl);
 similarly getc function is used to read a character from a file that has been open in read mode.
c=getc(fp2)
NASC-Department of Computer Applications [Computing Fundamentals and ‘C’ Programming] 81
 The getc will return an end-of-file marker EOF, when end of the file has been reached.
 The reading should be terminated when EOF is encountered.

main()
{
FILE *f1;
char c;
f1=fopen(“INPUT”, “w”);
while((c=getchar())!=EOf)
putc(c,f1);
fclose(f1);
f1=fopen(“INPUT”, “r”);
while((c=getc(f1))!=EOF)
printf(“%c”, c);
fclose(f1);
}

The getw and putw functions

 These are integer-oriented functions.


 They are similar to getc and putc functions and are used to read and write integer values.
 These functions would be useful when we deal with only integer data.
 The general forms of getw and putw are:
putw(integer,fp);
getw(fp);

#include<stdio.h> 
main()
{
FILE *f1;
int number,i;
int c;
printf("Contents of the data file\n\n");
f1=fopen("database.txt","w");
for(i=1;i<3;i++)
{
scanf("%d",&number);
if(number==-1)
break;
putw(number,f1);
}
fclose(f1);
f1=fopen("database.txt","r");
while((number=getw(f1))!=EOF)
printf("%d",number);
fclose(f1);
getch();
}

The fprintf and fscanf functions

 The fprintf and fscanf functions are identical to printf and scanf functions except that they work on
files.
 The first argument of theses functions is a file pointer which specifies the file to be used.
 The general form of fprintf is
NASC-Department of Computer Applications [Computing Fundamentals and ‘C’ Programming] 82
fprintf(fp, “control string”, list);
 Where fp id a file pointer associated with a file that has been opened for writing.
 The control string is fiJe output specifications list may include variable, constant and string.
fprintf(fl ,%s%d%f",name,age,7 .5);
 Here name is an array variable of type char and age is an int variable.
 The general format of fscanf is
fscanf(fp,"controlstring" ,list);
 This statement would cause the reading of items in the control string.
 Example:
fscanf( f2,"%s%d" ,item, &quantity");
 Like scanf, fscanf also returns the number of items that are successfully read.

#include <stdio.h>
#include <io.h>
#include <stdlib.h>
int main(void)
{
FILE *fp;
char s[80];
int t;
if((fp=fopen("test", "w")) == NULL) {
printf("Cannot open file.\n");
exit(1);
}
printf("Enter a string and a number: ");
fscanf(stdin, "%s%d", s, &t); /* read from keyboard */
fprintf(fp, "%s %d", s, t); /* write to file */
fclose(fp);
if((fp=fopen("test","r")) == NULL) {
printf("Cannot open file.\n");
exit(1);
}
fscanf(fp, "%s%d", s, &t); /* read from file */
fprintf(stdout, "%s %d", s, t); /* print on screen */
return 0;
}

Error handling during I/O operations

 It is possible that an error may occur during I/O operations on a file.


 Typical en-or situations include:
1. Trying to read beyond the end of file mark.
2. Device overflow
3. Trying to use a file that has not been opened.
4. Opening a file with an invalid file name.
5. Attempting to write to a write protected file.
6. Trying to perform an operation on a file when the file is opened for another type of operation.
he standard I/O functions maintain two indicators with each open stream to show the end-of
file and en-or status of the stream. These can be interrogated and set by the following
functions: .
 We have two status-inquiry library functions:

1. feof: returns non-zero if the stream's EOF indicator is set, zero otherwise.
if(feof(fp))
printf(“End of data”);

NASC-Department of Computer Applications [Computing Fundamentals and ‘C’ Programming] 83


2. ferror: returns non-zero if the stream's error indicator is set, zero otherwise.

if(fp == NULL)
printf(“File could npt be opened”);
main()
{
char *filename;
FILE *fp1, fp2;
int i, number;
fp1=fopen(“TEST”, “w”);
for(i=10;i<=100;i+=10)
putw(i,fp1);
fclose(fp1);
printf(“Input filename”);
open_file:
scanf(“%s”, filename);
if((fp2=fopen(filemname,”r”))==NULL)
{
printf(“cannot open the file”);
printf(“Type filename again”);
goto open_file;
}
else
{
for(i=1;i<=20;i++)
{
number=getw(fp2);
if(feof(fp2))
{
printf(“Ran out of data”);
break;
}
else
printf(“%d”, number);
}
fclose(fp2);
}

Random access files

 When we are interested in accessing only a part of file and not in reading the other parts.
 This can be achieved with the help of the functions fseek, ftell, and rewind.
 Ftell takes a file pointer and return a number of type long, that corresponds to the current position.
 This function in saving the current position of a file, which can be used later in the program.
n=ftell(fp);
 rewind takes a file pointer and resets the position to the start of the file.
rewind(fp);
n=ftell(fp);
 This function help us in reading a file more than once, without having to close and open the file.
 Whatever a file is opened for reading or writing, a rewind is done implicitly.
 fseek function is used to move the file position to a desired location within the file.
fseek(file_ptr, offset, position);
 file_ptr is a pointer to the file concerned
 offset specifices the number of positions to be moved from the location specified by position.
 Offset may be positive (moves forward) and negative (moves backward).
NASC-Department of Computer Applications [Computing Fundamentals and ‘C’ Programming] 84
 The position can take one of the following three values:

Value Meaning
0 Beginning of file
1 Current position
2 End of file

Operations of fseek function

Statement Meaning

fseek(fp,oL,0); Go to the beginning.


fseek(fp,0L,1); Stay at the current position
fseek(fp,0L,2) Go to the end of the file, past the character of file
fseek(fp,m,0) Move to (m+1)th byte in the file
fseek(fp,m,1) Go forward by m bytes
fseek(fp,-m,1) Go backward by m bytes from the current position
fssek(fp,-m,2) Go backward by m bytes from the end

 When the operation is successful, fseek returns a zero.


 If we attempt to move the file pointer beyond the file boundaries, an error occurs and returns -1
main()
{
FILE *fp;
long n;
char c;
fp=fopen(“RANDOM”, “w”);
while((c=getchar())!=EOF)
putc(c,fp);
printf(“%d”, ftell(fp));
fclose(fp);
fp=fopen(“RANDOM”, “r”);
n=0L;
while(feof(fp) == 0)
{
fseek(fp, n, 0); //position to the n+1th character
printf(“%c %ld”, getc(fp), ftell(fp));
n=n+5L;
}
putchar(‘/n’);
fseek(fp, -1L, 2); // position to the last character
do
{
putchar(getc(fp));
}
while(!fseek(fp, -2L, 1))
fclose(fp);
}

Command line arguments

 It is a parameter supplied to a program supplied to a program when the program is invoked.


 This parameter may represent a filename the program should process.
 For example, if we want to execute a program to copy the contents of a file named X_FILE to
another one named Y_FILE, then we may use a command line like:
NASC-Department of Computer Applications [Computing Fundamentals and ‘C’ Programming] 85
C>PROGRAM X_FILE Y_FILE
 Every C program should have one main function and that it marks the beginning of the program.
 In fact main can take two arguments called argc and argv.
 The variable argc is an argument counter that counts the number of arguments on the command line.
 The argv is an argument vector and represents an array of character pointers that point to the
command line arguments.
 The size of the array will be equal to the value of argc.
 For instance, for the command line given above, argc is three and argv is an array of three pointers to
strings
argv[0]-> PROGRAM
argv[1]-> X_FILE
argv[2]-> Y_FILE

 in order to access the command line arguments, we must declare the main function and its
parameters as follows:
main(int arge, char *argv[])
{
----------
----------
}

UNIT I
 The term computer is derived from the word compute.
 A computer is an electronic device that takes data and instructions as an input from the user, process
data and provides useful information known as output.
 This cycle of operations of a computer is known as the input-process-output cycle.

INPUT OUTPUT
PROCESS
Data Information

Instructions

 The electronic device is known as hardware and the set of instructions is known as software.
 Modern computers possess certain characteristics and abilities.
1. Perform complex and repetitive calculations rapidly and accurately.
2. Store large amounts of data and information for manipulations.
3. Hold a program of a model which can be explored in many different ways.
4. Compare items and make decisions.
5. Provide information to the user in many different forms.
6. Automatically correct or modify the parameters of a system under control.
7. Draw and print graphs
8. Converse with users interactively and
9. Receive and display audio and video signals.
 Application areas may broadly be classified into the following major categories.
1. Data processing (commercial use)
2. Numerical computing (scientific use)
3. Text processing (office and educational use)
4. Message communication (e-mail)
5. Image processing (animation and industrial use)
6. Voice recognition (multimedia)
NASC-Department of Computer Applications [Computing Fundamentals and ‘C’ Programming] 86
History of computers
 Increasing need for numerical calculations, storage of data and information etc. with minimum of
mental and manual efforts led to invention of computers.
 ABACUS, used for calculations, was the earliest devise that qualifies as a computer widely used
6000 years ago. The ABACUS was built using the idea of place values.
 John Napier developed Logarithm, a tabular system of numbers through which many arithmetical
calculations were simplified, in 1617.
 Napier also invented a set of rods which were carved from bones and used for multiplication. These
were called Napier Bones.
 Slide Rule, based on the principle of logarithm, a calculating device was invented by William in
1620.
 Blaise Pascal, a Frenchman, invented a mechanical unit in 1642 that could add and subtract, using a
set of toothed wheels. This ‘calculator’ was the first digital machine.
 Pascal’s machine was further improved by a German mathematician Gottfried that could add,
subtract, multiply, divide and extract roots.
 In 1822, Charles Babbage built the ‘Difference Engine’. This could do only one kind of
calculations.
 In 1833, Charles Babbage designed and worked on Analytical Engine. It was a general purpose
computer designed to solve almost any type of problem. It contained most of the elements we find in
modern digital computer systems. Hence, Charles Babbage is considered as Father of modern
computer.
 Joseph Jacquard invented punch cards in 1801. Punch card had holes punched in it. These were used
by him to produce weaving pattern on the cloths.
 In 1880, Dr.Herman Hollerith used punched cards for data processing by building a tabulating
machine that could punch holes in cards and read them as well. This machine worked on electricity
and had mechanical parts and could handle 50 to 75 cards per minute. The system was very slow and
card jams and data destruction were common problems. Punching machine, Verifying machine,
Interpreter, Sorter, Collators, Tabulator were some of the machines used in this system.
 In 1944, Howard Alken built MARK1, the first digital computer, at Harvard University. It lacked
speed but had the ability to continuously perform complex arithmetic functions without frequent
human intervention. It was partly electronic and partly mechanical machine.
 In 1936, Alan Turing from Cambridge University submitted his brilliant logical analysis on
‘Artificial Intelligence’. His contribution on the development of electronic computers remains the
single biggest contribution ever made to the science.
In 1930, Germans developed a mechanical machine called as ‘ENIGMA’ for coding military
messages.
 In 1939, Britain initiated to build machines that could decipher Enigma’s codes. The world’s first
giant computer using values was built called the ‘Colossus’.
 In 1942, USA started to develop an electronic computer. In 1946, it could put to operation ‘ENIAC’
(Electronic Numerical Integrator and Calculator), made in University of Pennsylvania. John
Mauchly and J.Presper Eckert were the two people involved in its development. This computer was
made of 18,000 vacuum tubes. ENIAC could process the data at great speeds (though not
comparable to today’s computers).
 UNIVAC-1 was the first business oriented computer developed in 1952 used by US Bureau of
Census.

Generations of computers

 Computer can be categorized into five generations:


1. First generation (1940 – 1956)
2. Second generation (1956 – 1963)\
3. Third generation ( 1964 – 1971)
4. Fourth generation ( 1971 – till date)

NASC-Department of Computer Applications [Computing Fundamentals and ‘C’ Programming] 87


5. Fifth generation ( 1980s - - )
First generation computers
 Vacuum tubes were used to build the circuitry for the computers and magnetic drums was used for
the memory of the computer.
 Used to perform calculations in milliseconds.
 They were the fastest known computers of their time.
 Size of computers is very large, and covers the space of the entire room.
 Consume a great deal of electricity and generated a large amount of heat.
 Use machine language to perform operations and were capable of performing one operation at a
time.
 Take inputs from punch cards and paper tapes and displayed the results on paper as printouts.
 ENIAC, EDVAC and UNIVAC are first generation of computers
 Used to perform scientific calculations
Second generation computers
 Transistors were used instead of vacuum tubes.
 Invented in 1947 by John Bardeen, William Shockley, and Walter Brattain.
 Faster and more reliable.
 Size of the transistors was smaller than vacuum tubes and they generated less heat.
 Processing speed had increased and more reliable.
 Use assembly language. It helps the programmer to specify instructions in the form of words.
 The task of the programmer thus becomes easier with the development of high-level languages like
COBOL and FORTRAN.
 Main characteristic was that they used the stored program concept, i.e, the instructions were stored in
the memory of the computer.
 Accepts input from punch cards and magnetic tapes.
 The output was stored either in punch cards or printed on a paper.
 Use magnetic tapes and magnetic disks for external storage.
 IBM 1620, PDP8 and CDC1604 are examples of second generation computers.
Third generation computers
 The third generation computers were characterized by the development of the Integrated Circuit(IC),
which was developed by Jack Kilby, in 1958.
 An IC is a silicon chip that embeds an electronic circuit, which comprises several components, such
as transistors, diodes, and resistors.
 Increased the speed and efficiency of the computers.
 Use keyboard, which is an input device, for accepting data from users and displaed the output on the
monitor, which is an output device.
 Execute more than one application at the same time on a computer.
 The cost of the computers decreased.
Fourth generation computers
 Is characterized by the use of Large Scale Integration (LSI) circuits and Very Large Scale
Integration (VLSI) circuits.
 Further integrated on a silicon chip, termed as microprocessor, containing control logic and memory.
 Replace magnetic core memories by semiconductor memories.
 Two types of high-speed computer networking were used for connection and communication among
multiple computers at one time.
1. Local Area Network (LAN) – multiple computers in local area, such as home, office or a small
group of buildings are connected and allowed to communicate among them.
2. Wide Area Network (WAN) – connection and communication of hundreds of computers of
computers located across multiple locations.
 An example of a fourth generation computer is the Personal Computer(PC).
 A special characteristic is the Graphical User Interface (GUI) – user friendly interface that
provides icons and menus to users to interact with the various computer applications.
 Various other characteristics are:
NASC-Department of Computer Applications [Computing Fundamentals and ‘C’ Programming] 88
1. Smaller and cheaper.
2. Did not require proper air conditioning.
3. More reliable.
4. Had larger memory and secondary storage memory.
5. Use high-level programming languages, which allowed a program written for one computer to be
easily executed in another computer.
 The Intel 4004 chip, developed in 1971, was the first microprocessor for the computers.
 In 1981, IBM introduced its first computer for the home user.
 In 1984, Apple introduced the Macintosh.
 It was possible to connect the computers to from networks, which in the long run led to the
development of the Internet.
Fifth generation computers
 Is characterized by the Ultra Large Scale Integration (LSI) technology, which is more powerful and
faster than the microprocessors used by the computers of the fourth generation.
 Optical disks – popular portable mass storage medium.
 These optical disks are popularly known as Compact Disk-Read Only Memory (CD-ROM).
 They are primarily used for storing data, which is only readable.
 The following are the characteristics:
1. Portable, which are smaller and handy. Users can use them while travelling.
2. Several times more powerful.
3. No need for air-conditioning.
4. More reliable.
5. Provide user-friendly interfaces with multimedia features, which help in making the system more
useful in every occupation.
 An example of the fifth generation of computing devices is Intel Pentium Microprocessor Chip.

Classification of computers
 Computers are classified into several categories depending on their computing ability and processing
speed.
 These include:
1. Microcomputer
2. Minicomputer
3. Mainframe computers
4. Supercomputers
Microcomputers
 A microcomputer is defined as a computer that has a microprocessor as its CPU.
 It can perform the following basic operations:
1. Inputting: It is the process of entering data and instructions into the microcomputer system.
2. Storing: It is the process of saving data and instructions in the memory of the microcomputer
system, so that they can be use whenever required.
3. Processing: It is the process of performing arithmetic or logical operations on data, where data
can be converted into useful information.
4. Outputting: It provides the results to the user, which could be in the form of the visual display
or printed reports.
5. Controlling: It helps in directing the sequence and manner in which all the above operations are
performed.
Microcomputers
 Is a medium-sized computer that is more powerful than a microcomputer.
 An important distinction between a microcomputer and a minicomputer is that a minicomputer is
usually designed to serve multiple users simultaneously.
 A system that supports multiple users is called a multiterminal, time-sharing system.
 Popular among research and business organization.
 More expensive.
Mainframe computers
NASC-Department of Computer Applications [Computing Fundamentals and ‘C’ Programming] 89
 Which help in handling the information processing of various organizations like banks, insurance
companies, hospitals and railways.
 It is placed on a central location and are connected to several user terminals, which can act as access
stations and may be located in the same building.
 Larger and expensive.
Supercomputers
 Most powerful and expensive computers.
 Fastest computers
 Primarily used for complex scientific applications, which need a higher level of processing.
 Some of the applications include weather forecasting, climate research, molecular modeling used for
chemical compounds, airplane simulations and nuclear fusion research.
 The multiprocessor can enable the user to dive a complex problem into smaller problems.
 Supports multiprogramming where multiple users can access the computer simultaneously.

Basic anatomy of a computer system


 A computer system comprises of hardware and software components.
 Hardware refers to the physical parts of the computer system and software is the set of instructions
or programs that are necessary for the functioning of a computer to perform certain tasks.
 Hardware includes following components:
1. Input Devices: Used for accepting data on which the operations are to be performed.
Eg: keyboard, mouse.
2. Processor: Also known as CPU, it is used to perform the calculations and information
processing on the data that is entered through the input device.
3. Output Devices: They are used for providing the output of a program that is obtained after
performing the operations specified in a program.
Eg: monitor and printer.
4. Memory: It is used for storing the input data as well as the output of the program that is
obtained after performing the operations specified in a program. Memory can
be primary and secondary memory. Primary memory includes Random
Access Memory (RAM) and secondary memory includes hard disks and
floppy disks.
 Software supports the functioning of a computer internally and cannot be seen.
 It is stored on the secondary memory and can be an application software as well as system
software.
 The application software is used to perform a specific task according to the requirements.
Eg: Excel and MS Word
 The system software is mandatory for running application software.
Eg: operating system and networking system.
 All hardware components interact with each other as well as with the software.

Input devices

 Input devices are connected to the computer system using cables.


 The most commonly used input devices are:
1. Keyboard
2. Mouse
3. Scanner
Keyboard
 A standard keyboard includes alphanumeric keys, function keys, modifier keys, cursor movement
keys, spacebar, escape key, numeric keypad.
 Some special keys such as Page Up, Page Down, Home, Insert, Delete and End.
 Alphanumeric keys include the number keys and the alphabet keys.
 The function keys helps to perform a specific task.
 The modifier keys such as Shift and Control keys.
NASC-Department of Computer Applications [Computing Fundamentals and ‘C’ Programming] 90
 The cursor movement keys includes up, down, left and right are used to modify the direction of the
cursor on the screen.
 The spacebar key moves the cursor to the right by one position.
 Numeric keypad uses separate keypads for numbers and Mathematical operations.
Mouse
 The mouse allows the user to select elements on the screen such as tools, icons, and buttons by
pointing and clicking them.
 Use a mouse to draw and paint on the screen of the computer system.
 It is also known as a pointing device because it helps change the position of the pointer on the
cursor.
 It consists of two buttons, a Wheel at the top and a Ball at the bottom of the mouse.
 When the ball moves the cursor on the screen moves in the direction in which the ball rotates.
 Left button is used to select the element.
 Right button performs special options such as open, explore and shortcut menus.
Scanner
 Converts documents and images as the digitized images understandable by the computer system.
 The digitized images can be produced as black and white images, gray images, or colored images.
 In colored images, an image is considered as a collection of dots with each dot representing a
combination of red, green, and blue colors.
 The proportions of red, green and blue colors assigned to a dot are together called as color
description.
 Types of scanners:
1. Flatbed scanner: It contains scanner head that moves across a page from top to bottom to read
the page and converts the image or text available on the page in digital form. Used to scan
graphics, oversized documents, and pages from book.
2. Drum scanner: A fixed scanner head is used and the image to be scanned is moved across the
head. Used for scanning prepress materials.
3. Slide scanner: Scan photographic slides directly to produce files understandable by the
computer.
4. Handheld scanner: That is moved by end user across the page to be scanned. Inexpensive and
small in size.

Processor
 The part of a computer that executes program instructions is known as processor or central
processing unit.
 The CPU has two parts:
1. Control Unit (CU)
2. ALU
 CU stores the instruction set, which specifies the operations to be performed by the computer.
 CU transfers data and instructions to the ALU for an arithmetic operation.
 ALU performs arithmetical or logical operations.
 The CPU registers store the data to be processed by the CPU and the processed data also.
 CPU seeks help from the following hardware devices to process the data:
1. Motherboard:
 Device used for connecting the CPU with the input and output devices.
 The components are connected to all parts of a computer.
 Some of the components are:
1. Buses: Electrical pathway that transfer data and instructions among different parts
of a computer. Eg: data bus, address bus.
2. System clock: Used for synchronizing the activities performed by the computer.
The electrical signals that are passed inside a computer are timed, based on the
tick of the clock.

NASC-Department of Computer Applications [Computing Fundamentals and ‘C’ Programming] 91


3. Microprocessor: CPU component that perform the processing and controls the
activities performed by the different parts of the computer. The microprocessor is
plugged to the CPU socket placed on the motherboard.
4. Rom: Chip that contains the permanent memory of the computer that stores
information, which cannot be modified by the end user.
2. RAM
 It refers to the primary memory of a computer that stores information and programs until
the computer is used.
 RAM is available as a chip that can be connected to the RAM slots in the motherboard.
3. Video Card/Sound card
 Video cards are an interface between the monitor and the CPU.
 Can also include their own RAM and microprocessors that are used for speeding up the
processing and display of a graphic.
 Placed on the expansion slots, that allows us to connect the high-speed graphic display
cards to the motherboard.
 A sound card is a circuit board placed on the motherboard and is used to enhance the
sound capabilities of the computer.
 They are plugged to Peripheral Component Interconnect (PCI) slots.

Output devices
 The data processed by the CPU, is made available to the end user by the output devices.
 The most commonly used output devices are:
1. Monitor
2. Printer
3. Speaker
4. Plotter
Monitor
 Most commonly used output device that produces visual displays generated by the computer.
 The monitor, also known as a screen, is connected as an external devices using cables or connected
either as a part of the CPU case.
 The monitors are classified as
1. Cathode Ray Tube (CRT)
2. Liquid Crystal Display (LCD)
 The CRT monitors are large; occupy more space in the computer.
 The quality of visual display produced is better.
 The inner side of the screen contains the red, green and blue phosphors.
 The LCD monitors are thin, light weighted and occupy lesser space.
 It consists of a number of color or monochrome pixels arrayed in front of a light source or reflector.
 Consume a very small amount of electric power.
 A monitor can be categorized by its monitor size and resolution.
 The monitor size is the length of the screen that is measured diagonally.
 The resolution of the screen is expressed as the number of picture elements or pixels of the screen.
Printer
 It transfers the text displayed on the screen, onto paper sheets that can be used by the end user.
 The various types of printers used in the market are generally categorized as
1. Dot matrix printers
2. Inkjet printers and
3. Laser printer.
 The printer is an external device connected to the computer system using cables.
 The computer needs to convert the document that is to be printed to data that is understandable by
the printer.
 The printer driver software or print driver software is used to convert a document to a form
understandable by the computer.

NASC-Department of Computer Applications [Computing Fundamentals and ‘C’ Programming] 92


 The performance of the printer is measured in terms of dots per inch (DPI) and pages per minute
(PPM) produced by the printer.
1. Dot matrix printers:
 They are impact printers that use perforated sheet to print the text.
 The process to print a text involves striking a pin against a ribbon to produce its
impression on the paper.
 As the striking motion of the pins help in making carbon copies of the text, dot matrix
printers are used to produce multiple copies of a print out.
2. Inkjet printers:
 Slower than dot matrix printer.
 Used to generate high quality photographic prints.
 They are not impact printers.
 The ink cartridges are attached to the printer head that moves horizontally, from left to
right.
3. Laser printers:
 It may or may not be connected to a computer, to generate an output.
 These printers consist of a microprocessor, ROM and RAM, which can be used to store
the textual information.
 It uses a cylindrical drum, a toner and the laser beam.
 The toner stores the ink that is used in generating the output.
 The fonts used for printing are stored in the ROM or in the cartridges that are attached to
the printer.
 It is available as gray scale, black and white or color models.
 To print high quality pages thy use PageMarker Software.
Speaker
 It is an electromechanical transducer that converts an electrical signal into sound.
 They are attached to a computer as output devices, to provide audio output, such as warning sounds
and Internet audios.
 We can have built-in speakers or attached speakers in a computer to warn ene users with error audio
messages and alerts.
 The audio drives need to be installed in the computer to produce the audio output.
 The sound card being used in the computer system decides the quality of audio that we listen using
music CDs or over the internet.
Plotter
 Connected to a computer to print large documents, such as engineering or constructional drawings.
 Uses multiple ink pens or inkjets with color cartridges for printing.
 A computer transmits binary signals to all the print heads of the plotter.
 Each binary signal contains the coordinates of where a print head needs to be positioned for printing.
 Plotters are classified on the basis of their performance:
1. Drum plotter:
 They are used to draw perfect circles and other graphic images.
 They use a drawing arm to draw the image.
 The drum plotter moves the paper back and forth through a roller and the drawing arm
moves across the paper.
2. Flat-bed plotter:
 It has a flat drawing surface and the two drawing arms that move across the paper sheet,
drawing an image.
 The plotter has a low speed of printing and is large in size.
3. Inkjet plotter:
 Spray nozzles are used to generate images by spraying droplets of ink onto the paper.
 The spray nozzles can get clogged and require cleaning, thus resulting in a high
maintenance cost.
4. Electrostatic plotter:

NASC-Department of Computer Applications [Computing Fundamentals and ‘C’ Programming] 93


 It produces high quality print with highest seed.
 It uses charged electric wires and special dielectric paper for drawing.
 The electric wires are supplied with high voltage that attracts the ink in the toner and
fuses it with the electric paper.

Memory management
 It is used to store data, instructions for processing data, intermediate result of processing and final
processed information.
 Classified as:
1. Primary memory
2. Secondary memory
Primary memory
 It is available in the computer as a built-in unit of the computer.
 It is represented as a set of locations with each location occupying 8 bits.
 Each bit in the memory is identified by a unique address.
 The data is stored in the machine-understandable binary form in these memory locations.
 The commonly used primary memories are:
1. ROM:
 Read Only Memory that stores data and instructions, even when the computer is turned
off.
 It is the permanent memory of the computer where the contents cannot be modified by
the end user.
 ROM is a chip that is inserted into the motherboard.
 It is generally used to store the Basic Input/Output system (BIOS), which performs Power
On Self (POST).
2. RAM:
 Read Write Memory unit in which the information is retained only as long as there is a
regular power supply.
 When the power supply is interrupted or switched off, the information stored in the RAM
is lost.
 RAM is a volatile memory that temporarily stores data and applications as long as they
are in use.
 When the use of data or the application is over, the content in RAM is erased.
3. Cache memory:
 It is used to store that data and the related application that was last processed by the CPU.
 When the processor performs processing, it first searches the cache memory and then the
RAM, for an instruction.
 The cache memory can be either soldered into the motherboard or is available as a part of
RAM.
Secondary memory
 It represents the external storage devices that are connected to the computer.
 They provide a non-volatile memory soured used to store information that is not in use currently.
 A storage device is either located in the CPU easing of the computer or is connected externally to the
computer.
 It can be classified as:
1. Magnetic storage device:
 It stores information that can be read, erased and rewritten a number of times.
 These include floppy disk, hard disk and magnetic tapes.
2. Optical storage device:
 It use laser beams to read the stored data.
 These includes CD-ROM, rewritable compact disk (CD-RW), digital video disks with
read only memory (DVD-ROM).
3. Magneto-optical storage device:

NASC-Department of Computer Applications [Computing Fundamentals and ‘C’ Programming] 94


 Generally used to store information, such as large programs, files and back up data.
 The end user can modify the information stored in magneto-optical storage devices
multiple times.
 These devices provide higher storage capacity as they use laser beams and magnets for
reading and writing data to the device.

Types of Software
 Software : Computer cannot work on its own. It must be given instructions in sequence to work.
Such instructions in any computer language are called a computer programme.
 Software refers to the set of programs that control the activity of processing by the computer. The
computer software is classified into two broad categories –
a) Application software : Also known as application packages. This is a set of one or
more programs that are developed or written to do a specific job. Eg. An application
package of a company to process its sales data and to generate various sales reports.
b) System software : Set of one or programmes which are developed to control the
operation of the computer system. These programs do not solve specific problems but
they are general programs which help the user in the use of the computer system.
 Hardware and software of a computer are interdependent on each other. They are like the two sides
of the same coin. The hardware cannot work on its own and the software cannot be used without the
hardware.

Overview of operating system


 It acts as an interface between the computer and its application programs.
 It is a system software that helps in managing the resources of a computer as well as provides a
platform for the application programs running in the computer.
 Eg: MS DOS, MS Windows and UNIX.
 The primary task includes the allocating various resources of the computer, scheduling process,
managing storage, controlling input and output, tracking files and directories on the disk, and
handling communications with the peripheral devices such as disk drives and printers.
Types of Operating System
 Batch operating system: This is the earliest one, where only one program is allowed to run at one
time. We cannot modify any data used by the program while it is being run. Eg: MS DOS.
 Interactive operating system: Only one program can run at one time. Modification and entry of
data are allowed while the program is running. Eg: Multics (Multiplexed Information and computing
service).
 Multiuser operating system: It allows more than one user to use a computer system either at the
same time or at different times. Eg: Linux, Windows 2000.
 Multi-tasking operating system: It allows more than one program to run at the same time.
Eg: Unix, Windows 2000.
 Multithreading operating system: It allows the running of different parts of a program at the same
time. Eg: UNIX and Linux.
MS DOS Operating System [Microsoft Disk Operating System]
 It is marketed by Microsoft Corporation and is one of the most commonly used members of DOS
family of operating system.
 MS DOS is a command line user interface, which is known as MS DOS prompt.
 It was first introduced in 1981 for IBM computers.
 We can perform various commands to perform the operations in MS DOS operating system.
 The commands are broadly classified into the following three classes:
 Environment command: These commands usually provide the information on operating system
environment. Some of the commands are:
1. CLS: To clear the complete content of the screen.
2. TLME: To view and edit the time of the computer.
3. DATE: To view the current date and change the date.
4. VER: To view the version of the MS-DOS.
NASC-Department of Computer Applications [Computing Fundamentals and ‘C’ Programming] 95
 File manipulation command: These commands help in manipulating files.
1. COPY: To copy one or more files from one specified location to a alternate location.
2. DEL: Deleting the file from the computer.
3. TYPE: To view the contents of the file in the command prompt.
4. DIR: To view the files available in the current and parent directories.
 Utilities: These are special commands that perform various useful functions.
1. FORMAT: To erase all the content from a computer diskette.
2. EDIT: To view a computer file in the command prompt. Allows the user to create
and modify the computer files.
MS Windows Operating System
 It was introduced by Microsoft Corporation in 1985.
 The first independent version is Microsoft Windows 1.0.
 In 1987, a Windows 2.0 was introduced.
 In 1990, Microsoft released the Windows 3.0, which was the first windows operating system to get
broad commercial success.
 Some of the popular operating system include:
 Windows 95: Released in August 24, 1995. It was known as Windows 4.0. various new features are:
1. Plug and play: Allows automatic installation of hardware devices into the computer
with proper software.
2. 32-bit operating system: To perform in a faster and more efficient way.
3. Registry: Allows easier location of system configuration files.
4. Right mouse click: Allows the use of the both buttons instead of one to provide new
access and text manipulation.
 Windows 98: Released in June 1998. It use the device driver framework, Windows Driver Model
(WDM). The WDM allows the driver developers to write device drivers, which are source-code
compatible across all Microsoft Windows operating system. In 1999 second version of Windows 98
was released which was known as Windows 98 Second edition (SE).
1. Protection: Additional protection for import files in the computer.
2. Improved device support: Provides improved support for various new devices.
Eg: USB, DVD.
3. FAT32: Convert a drive to FAT32 without having the risk of losing any information.
4. Internet Explorer: It includes IE 4.0
5. Customizable taskbar: Provides new feature.
 Windows 2000: Introduced in Feb 2000. Windows 2000 is based on Windows kernel and it is
referred as Windows NT 5.0. some of the significant features include:
1. Supports NTFS along with the support for both FAT16 and FAT 32.
2. Protects memory of individual applications and process so that failure of a single
application cannot bring the system down.
3. Protect sensitive data by encrypted feature.
4. Allows personalization of the menus.
5. Include greater support for high-speed networking devices.
 Windows Millennium: Released in September 2001. Popularly known as Windows Me. It was
mainly used for professional versions of operating system only. Some of the features are:
1. Allows automatic restoring of an old backup.
2. Allows a user to protect important system files, which cannot be modified by any
type of other software.
3. Includes Windows Media Player 7 to provide an advanced and improved way of
listening and organizing media files.
 Windows XP: Released in October 2000. It is a general-purpose computer systems. XP stands for
experience. The most common editions are:
1. Windows XP Home Edition: It is targeted for home users.
2. Windows XP Professional: Targeted for the power users as well as business clients.
3. Windows XP Media Center Edition: Includes features such as multimedia.
4. Windows XP Tablet PC Edition: Ability to run the ink-aware Tablet PC platform.
5. Windows XP 64-bit Edition: Released for Itanium-64 processors.
NASC-Department of Computer Applications [Computing Fundamentals and ‘C’ Programming] 96
6. Windows XP Professional x64 Edition: Released for personal computers.
 Windows Vista: Released in January 2007. Some of the features are:
1. A completely new GUI and Visual style known as Windows Aero.
2. Improved searching features.
3. New multimedia creation tools, such as Windows DVD Maker.
4. Newly redesigned networking system, audio, and display sub-system.
5. 3.0 version of the .NET architecture for developers.
6. Ability to automatically detect and correct problems that are encountered on the
computer.
UNIX Operating System
 It was developed by a group of AT & T employees at Bell Labs in 1969.
 Primarily designed to allow multiple users access the computer at the same time and share resources.
 For example, it can allow one user to create a document while another to format a document.
 It controls all the commands generated from the user keyboards.
 It is written using C Language.
 In this everything is treated as a file and its core part is known as the Kernel.
 This operating system is most popular among engineers, scientists and software professionals due to
its properties.
 The properties include:
1. Multi-user capability: It allows more than one user to access different resources
of the computer at the same time.
2. Multitasking capability: It allows a user to run multiple programs concurrently,
which can share both CPU time as well as resources of the computer.
3. Portability: It allows a user to execute the operating system code on any machine
having minimum hardware requirements for running the operating system.
4. Flexibility: It uses modular programming.
5. Security: It supports a strong security system that maintains security at various
levels and helps in securely execute a program on the Internet.
Architecture of UNIX
 UNIX has a hierarchical architecture consisting of several layers, where each layer provides unique
functions as well as maintains interaction with its lower layers.
 The layers of UNIX are:
1. Kernel
2. Service
3. Shell
4. User applications
 Kernel: It is the core of the UNIX operating system and it gets loaded into memory whenever we
switch on the computer. It contains three components, which are:
1. Scheduler: It allows scheduling the processing of various jobs.
2. Device driver: It helps in controlling the I/O devices attached to the computer.
3. I/O buffer: It controls the I/O operations in the computer.
Various functions:
1. Initializing and executing different programs at the same time.
2. Allocating memory to various user and system processes.
3. Monitoring the files that reside on the disk.
4. Sending and receiving information to and from the network.
 Service: in this layer, requests are received from the shell and they are then transformed into
commands to the kernel. To access the facilities of the service layer, it uses system calls. It is also
known as the resident module layer. These service include:
1. Providing access to various I/O devices, such as keyboard and monitor.
2. Providing access to storage devices, such as disk drivers.
3. Controlling different file manipulation activities, such as reading from a file and
writing to a file.

NASC-Department of Computer Applications [Computing Fundamentals and ‘C’ Programming] 97


 Shell: It acts as an interface between a user and the computer for accepting the requests and
executing programs. It is also known as command interpreter that helps in controlling the interaction.
The primary function is to read the data and instructions from the terminal, and then execute
commands and finally display the output on the monitor. It is also termed as the utility layer as it
contains various library notations for executing routine tasks. The various shells are:
1. Bourne shell: It is the default shell, which is initiated when a Unix user logs into the
Unix computer. The executable file is sh and command prompt is $.
2. C shell: It is named after the C programming language; syntax is similar to that of C.
It allows a user to provide short names for long command sequences. The executable
file is csh and its command prompt is %.
3. Korn shell: This feature is same to that of Bourne shell. The executable file is ksh
and its command prompt is $.
4. Restricted shell: It is used in secure installation where users need to be restricted to
work in a specific environment. The executable file is rsh and command prompt is $.
 User application: Which are used to perform several tasks and communicating with other users of
UNIX. Some of the examples of user applications are include test processing, software development,
database management and electronic communication.

Programming languages

 The operations of a computer are controlled by a set of instructions called a computer program.
 These instructions are written to tell the computer:
1. What operation to perform
2. Where to locate data
3. How to present results
4. When to make certain decisions.
 The language used in the communication of computer instructions is known as the programming
languages.
 Computer has its own language.
 Three levels of programming languages are available. They are:
1. Machine languages (low level languages)
2. Assembly languages
3. Procedure-oriented languages (high level languages)
Machine language
 As computers are made of two-state electronic devices they can understand only pulse and no-pulse
conditions.
 All instructions and data should be written using binary codes 1 and 0.
 The binary code is called the machine code or machine language.
 Computers respond only to machine language.
 It has two problems for the users.
 First, it is very difficult to understand and remember. Writing error-free instructions is a slow
process.
 Secondly, every machine has its own machine language; the user cannot communicate with other
computers.
 Machine languages are usually referred to as the first generation languages.
Assembly language
 Introduced in 1950s, reduced programming complexity and provide some standardization to build an
application.
 Also referred to as the second-generation programming language, is also a low-level language.
 It uses mnemonic code.
 Advantages:
1. It is easy to debug it.
2. Easier to develop a computer application.
3. It is very efficient.
NASC-Department of Computer Applications [Computing Fundamentals and ‘C’ Programming] 98
 It consists of a series of instructions and mnemonics that corresponds to a stream of executable
instructions.
 The mnemonic code is called the operation code or opcode, which specifies the operation to be
performed on the given arguments.
 Consider the following machine code:
10110000 01100001
 Its equivalent assembly language is:
mov a1, 061h
 The opcode move is used to move the hexadecimal value 61 into the processor register named ‘a1’.
 During execution, the assembly language program is converted into the machine code with the help
of an assembler.
High-level languages
 It is more abstract, easier to use, and more portable across platforms.
Eg: COBOL, Pascal, FORTRAN, C.
 Instead of using registers, memory addresses, we can use variables, arrays or Boolean expressions.
LOAD A
ADD B
STORE C
 Using the high-level language the above code can be written as:
C=A + B
 High-level language code is executed by translating it into the corresponding machine language code
with the help of a compiler or interpreter.
 Classified into three categories:
1. Procedure-oriented languages (third generation)
2. Problem-oriented languages (fourth generation)
3. Natural languages (fifth generation)
Procedure-oriented languages
 High level languages designed to solve general-purpose problems are called procedural languages or
third generation languages.
 BASIC, COBOL, FORTRON, C, C++ and JAVA which are designed to express the logic and
procedure of a problem.
 They use English-like commands and they are portable.
Problem-oriented languages
 Used to solve specific problems and are known as the fourth-generation languages.
 These include query languages, Report Generators and Application Generators which have simple,
English-like syntax rules.
 Use either a visual environment or a text environment for program development.
 A single statement in a fourth-generation language can perform the same task as multiple lines of a
third-generation language.
 The programmer just needs to drag and drop from the toolbar, to create various items like buttons,
textboxes, labels.
Natural languages
 Designed to make a computer to behave like an expert and solve problems.
 The programmer just needs to specify the problem and the constraints for problem-solving.
 LISP AND PROLONG are mainly used to develop artificial intelligence and expert systems.

Translator programs
Assembler
 It is a computer program that translates assembly language statements into machine language codes.
 The assembler takes each of the assembly language statements from the source code and generates a
corresponding bit stream using 0’s and 1’s.
 The output of the assembler in the form of 0’s and 1’s is called object or machine code.
 This machine code is finally executed to obtain the results.

NASC-Department of Computer Applications [Computing Fundamentals and ‘C’ Programming] 99


 The modern assemblers like Sun SPARC and MIPS based on RISC architectures, optimizes
instruction scheduling to attain efficient utilization of CPU.
 The modern assemblers generally include a macro facility and are called macro assemblers.
 Assemblers can be classifies as:
1. Single-pass assemblers.
2. Two-pass assemblers.
Single-pass assemblers:
 It was the first assembler that processes the source code once to replace the mnemonics with
the binary code.
 It was unable to support advanced source-code optimization.
Two-pass assemblers:
 It was developed to read the program twice.
 During the first pass, all the variables and labels are read and placed into the symbol table.
 On the second pass, the label gaps are filled from the table by replacing the label name with
the address.
 This helps to attain higher optimization of the source code.
 The translation process of an assembler consists of the following tasks:
5. Replacing the symbolic address by numeric address.
6. Replacing symbolic operation code by machine operation codes.
7. Reserving storage for the instructions and data.
8. Translating constants into their machine representation.
Compiler
 It is a computer program that translates the source code written in a high-level language into the
corresponding object code of the low-level language.
 This translation process is called compilation.
 The entire high-level program is converted into the executable machine code file.
 A program that translates from a low-level language to a high-level language one is a decompiler.
 In 1952, Grace Hopper wrote the first compiler for the A-0 programming language.
 In 1957, John Backus at IBM introduced the first complete compiler.
 Compilers are also classified as single-pass compilers and multi-pass compilers.
 Single-pass compilers are generally faster than multi-pass compilers.
 Multi-pass compilers are required to generate high-quality code.
Interpreter
 The interpreter is a translation program that converts each high-level program statement into the
corresponding machine code.
 Instead of the entire program, one statement at a time is translated and executed immediately.
 Commonly used language is BASIC and PERL.
 Interpreters are easier to create as compared to compilers, the compiled languages can be executed
more efficiently and are faster.

Problem solving techniques


 A computer is used to solve various types of problems because it takes very less time as compared to
a human being.
 The following steps are performed while solving a problem:
1. Analyze the given problem.
2. Divide the process into a series of elementary tasks.
3. Formulate the algorithm.
4. Express the algorithm as a precise notation, which is known as a computer program.
5. Feed the program in the computer. CPU interprets the program, process the data and generates
the result.
6. Send the result to the output unit.
Algorithms
 An algorithm is a complete, detailed and clear step-by-step method for solving a problem
independently of the software or hardware of the computer.
NASC-Department of Computer Applications [Computing Fundamentals and ‘C’ Programming] 100
 It is essential, as they instruct the computer what specific steps it needs to perform to carry out a
particular task or to solve a problem.
Top-down approach of algorithm
 It is also known as divide and conquer.
 The given problem is divided into two or more sub problems, each of which resembles the original
problem.
 The solution of each sub problem is taken out independently.
 Finally, the solution of all sub problems is combined to obtain the solution of the main problem.
 Eg: binary search.
Program verification
 It refers to the use of formal, mathematical techniques to debug a program and its specification.
 Consider an array of 11 elements
X[11]={8,18,26,40,47,69,84,115,126,136,177}
 Now use binary search technique to find weather the element 26 is present in the list or not.
 Divide the list into two half. During first iteration the values of
Low = 1 High = 11 Mid = 6
 The element at the sixth position is 69, which is not the required element.
 The value of element 6th position is greater than 26, so the algorithm searches the left half of the
array.
 During second iteration the values of
Low = 1 High = 5 Mid =3.
 The element at the 3rd position is 26, which is the required element. Thus the search is successful.
 If the search is successful, then it is verified that the program is correct.
Efficiency of an algorithm
 It means how fast it can produce the result for the given problem.
 The efficiency of an algorithm depends upon its time complexity and space complexity.
 Two important factors for judging the complexity of an algorithm are as follows:
1. Space complexity
2. Time complexity
Space complexity
 It refers to the amount of memory required by the algorithm for its execution and generation
of the final output.
Time complexity
 It refers to the amount of computer time required by an algorithm for its execution.
 This time includes both compile time and run time.
 The compile time of an algorithm does not depend on the instance characteristics of the
algorithm.
 The runtime of an algorithm is estimated by determining the number of various operations,
executed by it.
Analysis of algorithm
 It determines the amount of resources, such as time and space required by it for its execution.
 The complexity of an algorithm is estimated in asymptotic notations.
 These notations are used to represent the asymptotic run time of an algorithm.
 These notations represented in terms of function T(n), where n is the set of natural numbers.
 The basic notations used to represent the complexity of an algorithm are:
ᴏ- used to provide the upper boundary constraints over a given function.
Ω- used to provide as asymptotic lower bound on the given function.
ᴏ- used to denote asymptotic loose upper bound.
ω- used to denote asymptotic loose lower bound.
Flowcharts
 It is the pictorial representation of the algorithm depicting the flow of the various steps.

NASC-Department of Computer Applications [Computing Fundamentals and ‘C’ Programming] 101


NASC-Department of Computer Applications [Computing Fundamentals and ‘C’ Programming] 102

You might also like