C Notes
C Notes
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
Example C program
Output:
This is a C basic program
Sum of two numbers : 2
C – Tokens
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
int main()
{
int x, y, total;
x = 10, y = 20;
total = x + y;
Printf (“Total = %d \n”, total);
} .
where,
main – identifier
{,}, (,) – delimiter
int – keyword
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:
Identifiers in C language:
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.
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
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
4. Character constants
5. String constants
float 10.456789
2 Real or Floating point constants
doule 600.123456789
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
Syntax:
Types of C constant:
Integer constants
Real or Floating point constants
Octal & Hexadecimal constants
Character constants
float 10.456789
2 Real or Floating point constants
doule 600.123456789
1. Integer Constants in C:
An integer constant must have at least one digit.
It must not have a decimal point.
2. Real constants in C:
A real constant must have at least one digit
It must have a decimal point
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
1. By “const” keyword
2. By “#define” preprocessor directive
Output:
value of number : 3.140000
value of letter : A
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.
2 Variable initialization data_type variable_name = value; int x = 50, y = 30; char flag = ‘x’, ch=’l’;
3. Environment variable
C – Data Types
1. Integer (int)
2. Character (char)
3. floating point (float)
4. double-precession (double)
5. void
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
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
double
long double
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
The process of giving initial values to variables is called initialization. It can be achieved through
Assignment Statement:
Variable_name=constant;
Another way giving values to variables is to input data through keyboard using scanf() function.
Syntax:
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);
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
#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
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.
-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=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
Mixed mode Arithmetic: When one of the operands is real and the other is integer the expression is
a mixed mode arithmetic expression.
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:
Operator Meaning
O/P
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 &&, ||, !
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 :
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
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
++ and --
The Operator + + adds 1 to the operand while -- subtracts 1, Both are unary operators
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++
If the Value of the condition is true then Value 1 is e valued assigned to the varable, otherwise
Value2.
if (a>b)
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 OR
^ Bitwise Exclusive – OR
~ Complement
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
Note : when you shift a bit towards left its Decimal Value is multiplied by Two (2).
a >>2 00000011
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
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.
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.
Eg: int i;
char c;
c = ‘a’;
i = c;
Now the int Variable i holds the ASCII code of the char ‘a’
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.
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.
Y =( int) (a + b)
P = (double)sum/n
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
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
Power functions
pow() Power
sqrt() Square Root
i. Reading a character:
getchar ( ) function is used to read one character at a time from the key board
Syntax ch = getchar ( );
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?
The Computer display the value char of variable „ch‟ i.e M on the Screen.
Formatted Input
5.11 Formatting Input With scanf()
- For example:
- 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.
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:
(“%6d”, 9876) 9 8 7 6
(“%-6d”, 9876) 9 8 7 6
(“%d”06, 9876) 9 8 7 6
%w.pf or %w.pe
%wc
Printing string:
%w.p s
W : field width
(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
5) switch statement
The if statement is a powerful decision making statement and is used to control the flow of execution of
statements.
Syntax:
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.
#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:
Flow chart
# 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
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 */
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:
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:
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 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;
}
Flow chart:
#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:
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.
Syntax:
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.
(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
(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 :
Syntax:
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
Syntax:
Initialization Expression;
while( Test Condition)
{
Body of the loop
}
#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
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
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:
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;
#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
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:
#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
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”.
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
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
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.
Like any other variables, arrays must be declared before they are used. The general form of array declaration
is
Syntax:
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.
number[0]
number[1]
number[2]
number[3]
number[4]
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();
}
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.
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.
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:
Syntax:
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
A list of items can be given one variable name using three subscripts and such a variable is called Three –
dimensional array.
The datatype specifies the type of elements that will be contained in the array, such as int, float, or char.
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.
Syntax:
char string_name[size];
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
K R I S H \0 ? ? ? ?
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
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.
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”);
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
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.
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)
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:
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 ( )
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.
- 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.
-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();
}
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();
}
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();
}
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();
}
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;
};
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
struct student struct student
{ {
int roll_no; int roll_no;
Example
char name[80]; char name[80];
float marks; float marks;
}; };
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”);
}
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;
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);
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;
}
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;
}; };
Declaring
union student report; union student *report, rep;
union variable
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
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
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
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”.
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’.
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;
The process of assigning the address of a variable to a pointer variable is known as initialization.
int *p=NULL;
int *p=0;
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
Pointer expressions
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.
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);
}
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”);
}
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
FILES
1. Naming a file
2. Opening the file
3. Reading data from the file
4. Writing data to the file
5. Closing the 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.
The input output library supports the function to close a file; it is in the following format.
f close(file_pointer);
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 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);
}
#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 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;
}
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);
}
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
Statement Meaning
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
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.
Input devices
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.
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.
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:
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.
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.