C-Notes For Student
C-Notes For Student
C is highly portable i.e., Software written for one computer can be run on
another computer. C language is well suited for structured programming. An
important feature of ‘C’ is its ability to extend itself. A C program is basically a
collection of functions. It encourages us to write out own functions and add to the
C library. Also C is modular, i.e., a unit of task can be performed by a single
function and this unit of task can be reutilized when needed. The large number of
functions makes programming task simple.
Every C program starts with a function called main(). This is the place
where program execution begins. Hence, there should be main() function in
every program. The functions are building blocks of C program. Each function
has a name and a list of parameters ( or arguments).
Documentation section
Linkage section
Definition section optional
Global declaration section
main ()
{
Declaration part
Execution part / statement part
}
Sub program section
Or optional
User defined section
Documentation section:
This section group of comments that explains about program name,
purpose of the program, program logic, programmer name, date of written
program etc.
Comments can be included anywhere into the program. Comments are
enclosed between /* and */.
Linkage Section:
It is the pre processing directive operation section under this we can
include the header files with the # include <header file name. h>
Or
# include “header file name. h”
Whenever we are using standard functions into the main program those
are referred into the header files. When we included header file. Otherwise it
gives error message header file inclusion error
# include < stdio. h> or # include < graphic. h>
Definition section:
It is also the pre-processing directive operation. Under this we can define
the symbolic constant with the # define identifier data.
Example: #define
These symbolic constant calls as macros. These macros are global.
# include <stdio.h>
/* A simple program for printing a message */
main()
{
printf( “ hello , this is a C program.”);
}
# include <stdio.h>
tells the compiler to read the file stdio.h and include its contents in this file.
stdio.h, one of header files, contain the information about input output functions.
The next line is a comment line Comments in the C program are optional and
may appear anywhere in a C program. Comments are enclosed between /* and
*/.
main() is the start of the main program. The word main is followed by a
pair of ordinary parenthesis (), which indicates that main is also a function. The
left brace { represents the beginning of the function where as the right brace }
represents the end of the function. It means, the braces enclose the body of
function. In this program, the body consists of only one statement, the one
beginning with printf. The printf() function is causes its arguments to printed on
the computer screen. The closing (right) brace of the main function is the logical
end of the program.
The following are some of rules to write C programs.
int %d
unsigned int %u
long int %ld
unsigned long int %lu
char %c
float %f
double %lf
long double %Lf
Signed :
It indicates all the bits are positive. Means that it takes only positive values
as well as negative values.
Unsigned:
It indicates all the bits are positive only(all values are positive).
C Datatypes
Integer constants:
An integer constant is an integer-valued number consisting of a sequence
of digits. The following are the rules for constructing integer constants.
1) An integer constant must have at least one digit.
2) It should not contain either a decimal point or exponent.
3) If a constant is positive, it may not be preceded by a plus sign. If it is a
negative, it must be preceded by a minus sign.
4) Commas, blanks and non digit-characters are not allowed in integer
constants.
5) The valid range is –32768 to +32767.
These range my larger for 32 bit computers.
Real constants:
Real constants are often called floating-point constants. These are two
ways to represent a real constant decimal form and exponential form.
Real constants expressed in decimal form must have at least one digit and
one decimal point. As in the case of integers, the real constants can be either
positive or negative. Commas, blanks, and non-digit characters are not allowed
with in a real constant.
In exponential form, a real constant is expressed as an integer number or
a decimal number multiplied by an integral power of 10. This simplifies the writing
of very large and very small numbers. In this representation, letter e is written
instead of 10, the power is written just to the right of e. generally, the part
appearing before e is called mantissa, whereas the part following e is called
exponent.
Rules for constructing real constants are:
1) The mantissa part and the exponential part should be separated by a
letter e.
2) The mantissa part may have a positive or negative sign. Default sign of
mantissa part is positive.
3) Commas, blanks and non-digit characters are not allowed with in a real
constant.
4) The exponent part must be an integer.
5) The mantissa part must have at least one digit.
6) Range of real constants expressed in exponential form is –3.4e38 to
+3.4e38
String constants:
A string constant is a sequence of characters enclosed in double quote.
The characters may be letters, numbers, blank space or special characters.
Example: “welcome”
“this is a sting”
“a+b=8”
““
“a”
Note that ““ is a null string or empty string. And the single string constant “a” is
not equivalent to the single character constant ‘a’.
Each sting constant must end with a special character ‘\0’. This character
is called null character and used to terminate the string. The compiler
automatically places a null ‘\0’ character at the end of every string constant. This
constant is not visible when the string is displayed. The null character is very
much useful in finding the end of a string.
Variables:
A variable can be considered as a name given to the location in memory.
The term variable is used to denote any value that is referred to a name instead
of explicit value. A variable is able to hold different values during execution of a
program.
For example, in the equation 2x+3y=10; since x and y can change, they
are variables, whereas 2,3 and 10 cannot change, hence they are constants.
Rules for constructing variable names:
1) The name of a variable is composed of one to several characters; the first
of which must be a letter.
2) No special characters other than letters, digits, and underscore can be
used in variable name. some compilers permit underscore as the first
character.
3) Commas, or blanks are not allowed with in a variable name.
4) Upper case and lower case letters are significant (different).
5) The variable name should not be a C key word. Also it should not have the
same name as a function.
Examples: income, name, rate, marks, sno, etc.
Operators in C :
There are 9 types of operators in C. They are
1. Arithmetic operators
2. Relational operators
3. Logical operators
4. Assignment operators
5. Compound assignment operators
6. Increment and Decrement operators
7. Bit wise operators
8. Conditional operators (ternary operator)
9. Special operators
1). Arithmetic Operators:-
These are used for the mathematical operations.
Operator Meaning
+ addition
- subtraction
* multiplication
/ division
% modulus
The division operator ( / ) gives the quotient of the division.
The modulus operator ( % ) gives the remainder of the division.
Note:- All operators must works only with two operands. so these are also called
as the "Binary operators". Example:
main()
{
int a =10,b=20,c; /* variable declaration part */
c=a+b;
printf(“%d”, c); /* it displays addition of c value */
c= a-b;
printf(“%d”, c);
c= a*b;
printf(“%d”, c);
c= a/b;
printf(“%d”, c);
c= a%b;
printf(“%d”, c);
getch();
}
Note:
- Compilation of the Program (Alt + F9).
- Program Execution (ctrl + F9).
- Output or Console Screen ( Alt +f5).
Output:
30
-10
200
0
10
2). Relational operators:-
These are the operators, which tell the relation between the values or
operands. In C language all relational and logical operators returns 1 or zero. If
the expression is true then it will gives 1 other wise 0.
Operator Meaning
< Less than
> Greater than
<= Less than or equal to
>= Greater than or equal to
== Equals to
!= Not equals
Examples on relational operators:-
- a=3<4; 1
- a=3>2; 1
- a=2>=3; 0
- a= 5<=5; 1
- a= 5==5; 1
- a= 5!=8; 1
3). Logical operator:-
The logical operators are used to compare more than one condition
Operator Meaning
&& Logical AND
|| Logical OR
! Logical NOT
Truth table for AND (&&) operator:
Expression1 Expression2 Result
T T T
T F F
F T F
F F F
examples:-
1. a = 1&&1; 1
2. a = 7&&5; 1
3. a = 5>4 && 4>10; 0
4. a = 5>4 || 4>10; 1
5. a = 1 || 0 1
6. a = !1 0
7. a = 1 && 4>3 1
8. a = ! (5>5); 1
4). Assignment operator (=):
The assignment operator can be used to store the data into the identifier
(variable).
The nature of storage is that right side of the data stored into left side of
identifier. Ex: a=10;
5). Assignment operators (+=, - =, * =, / =, % =):
The compound assignment operator can be used to minimize the
arithmetic operations.
Example:
a+= 1; it is equal to a= a+1;
b+=a; it is equal to b= b + a;
c-=a; it is equal to c= c-a;
d*= a ; it is equal to d= d*a;
a/=b; it is equal to a=a/b;
b%=a; it is equal to b=b%a;
Increment (++)
Always it increment only one value to the existing identifier. They are two
types.
++a pre-increment.
a++ post-increment
pre- increment:
When ever the pre-increment operators using into the arithmetic
expressions then it is increasing the one value to the adjusting identifier and
participating into the expressions. This can be written ++identifier.
Ex: ++a;
Post- increment:
When ever the post incrimination operators including into the arithmetic
operators then the identifier values directly participating into the arithmetic
expressions. After that the identifier value incrementing by one only.
Syntax:
identifier ++ ;
Ex: a++;
Decrement operator (- - ):
It is always decreased by one value and result stored into the same
identifier. We have two types of decrement operators.
Pre – decrement ex: --a;
Post – decrement ex: a--;
Pre – decrement:
When ever pre – decrement operators using into the arithmetic
expressions then it is decreasing the one value to the adjusting identifier and
processing into the expressions. This can be written as -- identifier.
Ex: --a;
Post decrement:
When ever the post decrement operators including into the arithmetic
operations then the identifier values directly participating into the arithmetic
expressions. After that the identifier values decrement by one only.
Syntax:
Identifier --;
Output:
Enter any number
5
number is odd
if else statement:
The if/else statement extends the idea of the if statement by specifying
another section of code that should be executed only if the condition is false.
Syntax:
If (condition)
Statement 1;
else
statement 2 ;
where condition is an expression which evaluates to true or false value,
statement 1 is the statement to be executed only if the condition is true, and
statement 2 is the statement to be executed only if the condition is false. For
example:
if ( number1 > number2 )
printf(“%d is greater than %d \n”, number1, number2);
else
printf(“%d is not greater than %d \n”, number1, number2);
start
Conditio
n False statements
True statements
false
true
If(condition1)
{
statements
}
else
if(condition )
{
statements
}
else
{
statements
}
Program1:
/* Write a program to check the given value is positive or negative using if-
else statement */
Program2:
/*Write a program to check the given no is even or odd using if-else
statement */
Program 3:
/* Write a program to read student roll number, name and 6 subjects marks
and find the student result, total, average and division. If student is pass
then you display total, average and division other wise no need. */
main()
{
int roll_no,total,s1,s2,s3,s4,s5,s6;
char name[30];
float avg;
clrscr();
printf("enter student roll no:");
scanf("%d",&roll_no);
printf("enter student name:");
scanf("%s",&name);
printf("enter 6 subjects marks");
scanf("%d%d%d%d%d%d",&s1,&s2,&s3,&s4,&s5,&s6);
if( s1>35 && s2>35&&s3>35&& s4>35&&s5>35&&s6>35)
{
printf(" result =pass\n");
total=s1+s2+s3+s4+s5+s6;
avg=total/6;
printf("total=%d",total);
printf("avg=%f",avg);
if(avg>=60)
printf("First division");
else
if(avg>50)
printf("Second division");
else
printf("Third division");
}
else
printf("Result =Fail");
getch();
}
out put:
Enter student roll no 101
Enter student name: kumar
Enter 6 subjects marks: 55 65 85 75 95 44
Result : pass
Total =419 , avg=69.000000
First division.
Program 4:
/* Write a program to read 3 number and find the biggest number */
Program 5:
Write a program to check the given year is leap year or not?
The switch statement
The switch statement is an extension of the if-else statement. The switch
makes one selection when there are several choices to be made. The direction of
the branch taken by the switch statement is based on the value of any int(or int
compatible) variable or expression.
The general form of switch statement is shown bellow.
switch(integer expression)
{
case constant1 : statement1 ; break;
case constant2 : statement2 ; break;
case constant3 : statement3 ; break;
case constant4 : statement4 ; break;
“ “ “ “ “ “
“ “ “ “ “ “
“ “ “ “ “ “
case constant n : statement n ; break;
default : statement;
}
The integer expression following the key word switch is any C expression
that will result an integer value. I.e. is, it could be an integer constant or an
expression that evaluates to an integer. The key word case is followed by an
integer or a character constant .the break statement used inside each case of
the switch, causes an intermediate exit from the switch statement: and continued
onto the next statement outside the switch statement.
When we execute this form of switch statement, first the integer
expression is evaluated. The value of expression is then compared one by one,
with constant1, constant2…constant n. when a match is found, the program
executes the statements following that case. The execution continues from that
point till either a break statement is found or the switch statement is completed.
The break causes an immediate exit from the switch construct. Normally, in every
case, all statements following the default are executed.
Note: if the break statement is not included, all of the statements below the
match will be executed.
Program 1:
Write a program to read any digit and print in words using switch
statement.
main()
{
int digit;
clrscr();
printf("Enter any digit");
scanf("%d",&digit);
switch(digit)
{
case 0 : printf("zero");break;
case 1: printf("one"); break;
case 2: printf("two"); break;
case 3: printf("three"); break;
case 4: printf("four");break;
case 5 :printf("five");break;
case 6: printf("six");break;
case 7: printf("seven");break;
case 8:printf("eight");break;
case 9: printf("nine");break;
default: printf("not a digit");
}
getch();
}
Output:
Enter any digit 3
Three
Program 2:
Write a program to read 2 numbers and find the result based on the user
choice.
Choice operation
1---------------------addition
2--------------------subtraction
3--------------------multiplication
4--------------------division
5-------------------modulo division
LOOPS
A potion of program that is executed repeatedly is called a loop. The C
programming language contains three different program statements for program
looping. They are
while loop.
do-while loop
for loop
WHILE LOOP:
The while loop is best suited to repeat a statement or a set of statements
as long as some condition is satisfied.
The general form of while loop is
While (expression)
{
Statement;
}
Where the statement (body of the loop) may be a single statement or a
compound statement. The expression (text condition) must results zero or non-
zero.
First of all, the expression in the while loop is evaluated. If the result is true
(non-zero), then the statement is executed and the expression is evaluated
again. The statement continues to execute until the expression evaluates to false
(zero). Then the loop is finished and the program execution continues with the
statement that follows the body of while loop.
Flow chart:
Start
Initilization
False
Conditio
True n
true
Output:
1 2 3 4 5 6 7 8 9 10
Program 2:
/* To print the even numbers between 1 to 100 using while loop */
main()
{
int num=1;
clrscr();
while(num<=100)
{
if(num%2==0)
{
printf("%d\t",num);
}
num++;
}
getch();
}
Assignments:
Program 3: Write a program to read any number and find the factorial of the
given number.
Program 4:
Write a program to print the multiplication table of the given number
Program 5:
Write a program to read (accept) any number and print the reverse of the
given number.
main()
{
long int number, reverse=0,rem;
clrscr();
printf(“Enter any number”);
scanf(“%ld”,&number);
while(number>0)
{
rem=number%10;
reverse=reverse*10+rem;
number=number/10;
}
printf(“reverse of the given no=%ld”,reverse);
getch();
}
output:
Enter any number 123
Reverse of the given no =321
Program 6:
Write a program to read any number and check weather it is prime number
or not?
Program 7:
Write a program to read any number and check weather it is a polindrom
number or not?
Program 8: Print the prime numbers between 1 to 100
Do-WHILE LOOP
The structure of do-while loop is similar to while loop. The difference is that in
case of do-while loop the expression is evaluated after the body of loop is
executed. In case of while loop the expression is evaluated before executing
body of loop.
The general form of do-while statement is
do
{
Statements;
}
while(expression);
where statement is a single statement of compound statement. In contrast to
while loop statement (body of loop), do-while loop is executed one or more
times.
In do-while loop, first the statement is executed and then the expression
is tested. If the expression evaluates to false (zero), the loop terminates and the
execution control transfer to the next statement that fallows it. Otherwise, if
expression evaluates to true (non-zero), execution of the statement is repeated
and the iterative process continues.
Flow chart of do-while:
Start
Initilization
Loop statements
Stop
Program 1:
Write a program to display 1 to 10 natural numbers using do-while.
main()
{
int number=1;
clrscr();
do
{
printf("%d\t", number);
number++;
} while(number<=10); /* to check the condition is true or false
getch();
}
Output:
1 2 3 4 5 6 7 8 9 10
Program 2:
/* To print the even numbers between 1 to 100 using do-while*/
program 3:
Write a program to read (accept) any number and print the sum of the
digits. (123 = 1+2+3)
Program 4:
Wap to print multiplication tables from 1 to 10 using do-while loop
Program 5:
To check whether the given no is prime or not using do-while
FOR LOOP
The for loop is most common in major programming languages. The for
loop in C language is very flexible and very powerful. Generally, the for loop is
used to repeat the execution of a statement for some fixed number of times.
The general form of for loop is
for (initial-expression; conditional-expression; increment-expression)
Statement;
Where the statement is single or compound statement.
Initial-expression is the initialization expression, usually an assignment to the
loop-control variable. This is performed once before the loop actually begins
execution.
Conditional –expression is the test expression. Which is evaluated before
each iteration of the loop, which determines when the loop will exist.
Increment-expression is the modifier expression, which changes the value
of loop control variable. This expression is executed at the end of each loop.
These three sections are separated by semi colons. The for loop repeats
the execution of the statement as long as the conditional expression evaluates to
true (1). Once this test condition becomes false, the for loop will terminate and
control resumes to the statement that immediately following for loop.
Program 1:
Write a program to print the multiplication tables from 1 to 10 using for
loop.
main()
{
int tableno, c, i;
clrscr();
for(tn=1;tableno<=10;tableno++) /* incrementing table no number */
{
for(i=1;i<=10;i++) /* printing multiplication table */
{
printf("%d * %d =%d\n",tableno,i,tableno*i);
}
getch();
}
}
Program 2:
/* wap to print ASCII values of characters */
main()
{
int i;
clrscr();
for(i=0;i<256; i++)
{
printf("%c-----------> %d\n",i,i);
getch();
}
getch();
}
Program 3:
/* wap to print following format */
1
12
123
main()
{
int i,j;
clrscr();
for(i=1;i<=5;i++) /* outer loop */
{
for(j=1;j<=i;j++) /* inner loop */
{
printf(" %d",j);
}
printf("\n");
}
getch();
}
main()
{
int i,j;
clrscr();
for(i=65;i<=68;i++) /* outer loop */
{
for(j=65;j<=i;j++) /* inner loop */
{
printf("%c\t",i);
}
printf("\n");
}
getch();
}
Program 5: wap to print following format
333
22
1
Program 6: wap to print following format
CCC
BB
A
Program 7: wap to print the following format
*
**
***
Program 8:
/* To print the even numbers between 1 to 100 using for loop */
program 9:
Write a program to read (accept) any number and print the sum of the
digits. (123 = 1+2+3)
Program 10:
Wap to print multiplication tables from 1 to 10 using for loop
Program 11:
To check whether the given no is prime or not using for loop
Output:
Line 1
Line 6
This is last statement
In the above example, last is the label and when the goto statement is executed,
the execution control transfers to the statement indicated by last followed by
colon ( : )
ARRAYS:
An array is a collection of elements of same type. The elements of an
array referred by a common name and are differentiate from one another by their
position with in an array. The elements of an array can be of any data type but all
elements in an array must be of the same type. (or) An array is a group of
memory location of same type.
Arrays are two types they are
1. one dimensional array (single dimensional array)
2. two dimensional array
One dimensional array:
Elements arranged in the form of single row or column is called one-
dimensional array. The general form of declaring a one-dimensional array is
Datatype array-name[size];
Where datatype means basic datatypes (int ,float, char, double). Array-name is
the name of the array and size is the number of elements that array-name
contains.
The individual elements of an array can be referenced by means of its
subscript (or index). Suppose A is an array of 20 elements, we can reference
each element as
Array name Subscript (index)
Output:
Enter how many elements u want to store 5
Enter 5 elements into array 10 4 88 9 3
The array elements are
A[0]=10
A[1]=4
A[2]=88
A[3]=9
A[4]=3
Example 3: /* to read 5 array elements and display */
main()
{
int a[5],i; /* int array, one variable declaration */
clrscr();
printf("Enter 5 integer elements");
for(i=0;i<5;i++)
{
scanf("%d",&a[i]); /* takes single value from keyboard */
}
printf("The array elements are\n");
for(i=0;i<5;i++)
printf("a[%d]=%d\n",i,a[i]);
getch();
}
Output:
Enter 5 integer elements
10 4 88 9 3
The array elements are
A[0]=10
A[1]=4
A[2]=88
A[3]=9
A[4]=3
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
{
printf("%d\t",c[i][j]);
}
printf("\n");
}
}
else printf("Matrix addition not possible");
getch();
}
Output:
Enter the size of first matrix 2 3
Enter the size of second matrix 2 3
matrix addition possible
Enter elements of first matrix 2 6 3 5 8 9
Enter elements of second matrix 6 8 3 9 1 0
After adding
8 14 6
14 9 9
STRINGS:
String is a special kind of an array. String can be represented as an array of
characters. A string is a one-dimensional array of characters terminated by a null
character (\0). The ASCII value of null character is 0. A string constant can be
represented in C by enclosing its characters inside double quotes without null
character.
For Example, the string “computer” is stored in memory as
Note: The statement, which are starting with ‘#’ are called preprocessor
commands. These commands are processed before compilation of the program.
Example 4: To add 2 given strings using strcat function.
main()
{
char str1[300],str2[300];
clrscr();
printf("Enter first string:);
gets(str1);
printf("Enter second string:);
gets(str2);
getchar()
The getchar() function allows us to read a character from the standard
input. Using the getchar() only one character can be read at time but a string
cannot be read. To read strings using the getchar, we have to use getchar
function within a loop by reading a single character in each iteration. However,
the null character (‘\0’) at the end of the loop to recognize that the input value is
string.
FUNCTIONS
Functions are building blocks of C. functions are self-contained sub
programs of main program and function contains set of instructions. Each
function performs a specific task. Functions support the concept of top-down
modular programming design technique. Each function in C consists of a name,
a return type and a possible parameter list. Variables declared in functions are
called local variables, global variables can be accessed by any function.
Functions are two types. They are
1. Pre-defined functions or library functions
2. User-defined functions
Example for pre-defined functions are scanf(), printf(), clrscr(), getch(), etc.
Example for user-defined functions are sum(), display(), welcome(), address(),
etc.
The general form of C function is
Return-type function-name(parameter list)
Parameter declaration;
{
body of function;
}
If there are no parameters, the parameter declaration part is not needed. Note
that main function also having similar type of structure as shown above. The
body of the function contain local declarations (if any) and statements.
Every function calling from main function and every function returns a
value. But in C, the values returned by many functions are ignored. We can
declare functions of type void, which means that they don’t return any value.
In general, C can return any basic data type such as char, int, float, void
etc.,
Function calling four types they are
1. Function calling without parameters and without return statement.
2. Function calling with parameters and without return statement.
3. Function calling without parameters and with return statement.
4. Function calling with parameters and with return statement.
RECURSION
Recursion is a technique to be used to call itself. In C it is possible for the
functions to call themselves. A function is called recursive if a statement with in
the body of a function calls the same function itself.
Consider a simple example which finds the factorial of a number. A
factorial of a number is the product of all the integers between and that number.
For example 5 factorial is 5*4*3*2*1.
Program 1: write a program to find the factorial of the given number using
recursive function.
Program 3:
/* print the sum of array elements using fun with arg and with return state*/
POINTERS
Pointer is a derived data type and is used to store address of another variable. A
pointer variable in C is declared as follows:
Data-type *pointer-variable-name;
Examples:
Int *ptr; /* pointer- to- int */
float *fptr; /* pointer-to-float */
In the declaration, the asterisk (*) indicates that the pointer-variable and
data-type indicates the type the pointer is pointing to. Thus, when a pointer is
declared, the type of variable the pointer will address has to be specified. If a
pointer is declared address of a floating point number (or address of any type
other than integer).
There are two important operators in C to work with pointers: asterisk (*)
and ampersand (&).
In case of array, once the size of the array is declared, it is not possible to
increase or decrease its size during program execution. But by using pointer, the
memory can be allocated or de-allocated dynamically. Pointers allow to pass
variables, arrays, functions, strings and structures as function arguments.
main()
{
int a=20;
int *ptr1=&a; /* address of a is assigned to ptr1 */
int **ptr2=&ptr1; /* address of ptr1 is assigned to ptr2 */
clrscr();
printf("value of a=%d\n",a); /*display value in a */
printf("address of a=%u\n",&a); /*display address of a */
printf("address in ptr1=%u\n",ptr1); /* display content in ptr1 */
printf("value in that address =%d\n",*ptr1); /* value in that content */
printf("Address of ptr1=%u\n",&ptr1);
printf("address in ptr2=%u\n",ptr2 );
printf("element in **ptr2=%d",**ptr2);
getch();
}
Output:
Value of a = 20
address of a= 65494
address in ptr1= 65494
value in that address = 20
Address of ptr1= 65496
element in **ptr2= 20
Program 2: Addition of two given numbers.
main()
{
int a,b,c, *ptr1,*ptr2,*ptr3;
ptr1=&a,ptr2=&b,ptr3=&c;
clrscr();
printf("Enter values for a,b");
scanf("%d%d",&a,&b);
*ptr3 = (*ptr1) +(*ptr2);
printf("After sum\n");
printf("a=%d\n",a);
printf("b=%d\n",b);
printf("c=%d\n",c);
getch();
}
Output:
Enter values for a,b: 10 33
After sum
a= 10
b= 33
c= 43
main()
{
int a[10][10],*ptr=&a[0][0],m,n,i,j;
clrscr();
printf("Enter the size of the matrix:");
scanf("%d%d",&m,&n);
printf("Enter elements of %d * %d\n",m,n);
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf("%d",&a[i][j]);
printf("The given matrix elements are\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf(" ele=%d\t",*(*(a+i)+j) );
}
printf("\n\n");
}
getch();
}
Output:
Enter the size of the matrix: 2 3
Enter elements of 2 * 3
10 3 6 8 2 0
The given matrix elements are
10 3 6
8 2 0
Call-by-value:
A copy of the argument’s value is made and passed to the called function.
Therefore, changes to the copy do not effect the original variable’s value in the
caller. The function works with a copy of the argument sent to it.
Call-by-reference:
This is also called as pass-by-address or call-by-address. In this instead of
passing the values of the variables as parameters, the addresses of the variables
are passed as arguments. This is achieved by using the pointer.
In this mechanism, the caller gives the called functions the ability to
directly access the caller’s data. The function receives reference to variable and
works directly with the original variable.
#include<stdio.h>
main()
{
struct employee
{
int empno;
char name[30];
char dept[30];
float salary;
}emprec;
emprec.empno=1;
strcpy(emprec.name,"ANIL KUMAR");
strcpy(emprec.dept, "IT");
emprec.salary=10000;
printf("Employee no : %d\n", emprec.empno);
printf("Employee name : %s\n",emprec.name);
printf("Employee designation :%s\n",emprec.dept);
printf(" salary : %f\n", emprec.salary);
}
Output:
Employee code : 1
Employee name : ANIL KUMAR
Employee designation : IT
salary : 10000.000000
Program 2: print the address of structure members(elements).
struct emp
{
int eno;
char *name;
float sal;
}e; /* structure variable declaration */
void main()
{
e.eno=10; /* Assigning structure elements */
e.name="kumar";
e.sal=1000;
clrscr();
printf("address of eno=%u\n",&e.eno);
printf("address of name =%u\n",&e.name);
printf("address of sal=%u\n",&e.sal);
printf("eno=%d\nname=%s\nsal=%f",e.eno,e.name,e.sal);
getch();
}
Output:
address of eno= 1868
address of name = 1870
address of sal= 1872
eno= 10
name = kumar
sal= 10000
main()
{
clrscr();
printf("Enter student sno,name,address:");
scanf("%d%s%s",&s.sno,s.name,s.add);
printf("Enter 3 subjects marks:");
scanf("%d%d%d",&s.m.s1,&s.m.s2,&s.m.s3);
s.m.total=s.m.s1+s.m.s2+s.m.s3;
s.m.avg=s.m.total/3;
printf("STUDENT DETAILS ARE\n");
printf("sno=%d\t name =%s\t address =%s\n",s.sno,s.name,s.add);
printf("s1=%d\t s2=%d\t s3= %d\n",s.m.s1,s.m.s2,s.m.s3);
printf("total=%d\t avg=%f\n",s.m.total,s.m.avg);
getch();
}
Output:
Enter student sno,name,address: 11 jamesbond jublihills
Enter 3 subjects marks: 56 55 35
STUDENT DETAILS ARE
sno=11 name = jamesbond address = jublihills
s1= 56 s2= 55 s3= 35
total= 146 avg= 48.666668
UNIONS
Union is similar to C structure, i.e., it contain members of different types. The
difference is that a C union is used to store different datatypes variables in the
same memory location. In general, the unions are used to save the memory area
occupied by the program.
The general form of union declaration is
union union-name
{
data type variable1;
data type variable2;
data type variable3;
.
.
.
} union-variables;
Note that union declaration has the same form as the structure declaration
except the keyword union. The members of union can be of different types.
The important point in using a union type variable will have only one
member at any time. Hence, any reference to the wrong type of data will produce
meaningless results.
Thus the amount of storage space occupied for a union variable is the
amount of storage required for the largest member of the union. It should be
noted while using unions is that all members are stored in the same memory
space, with the same starting address, but not at the same time.
TYPEDEF
The typedef (type definition ) allows defining a new name for an existing data
type. Once a new name is given to a data type. Then new variables, arrays,
structures can be declared in terms of this new name (user given name to data
type). The general syntax of typedef statement is give bellow:
for example, the following statement defines a name number to the type int
typedef int number;
now, we can declare variables of the type number as
number I, j;
Note that the typedef declaration does not create new data types, but it simply
creates synonyms for existing types. Thus, this declaration is useful to give
meaningful name to the program.
FILE HANDLING
Storage of data in variables and arrays is temporary. Files are used for
permanent storage of large amount of data. Computer stores files on secondary
storage device. C works with files a new datatype called a file pointer.
C provides a data structure called FILE, declared in file stdio.h, to access
the stream of characters from the disk files. An I/O stream that is active, must
have this data type FILE associated with it. C also provides a number of
functions for I/O to perform the basic file operations such as opening a file,
reading data from/ writing data to a file, etc.
FILE POINTER:
The structure ‘FILE’ which is declared in stdio.h acts like a link between
OS and the program and it is used to define a file pointer for use in file
operations. Therefore, a pointer to a FILE type is rewired to work with files on
disk.
The syntax of declaring a file pointer is
FILE * file_ pointer;
Eg: FILE *fp;
Here fp is a file pointer of datatype FILE. The word FILE should be type in capital
letters.
OPENING A FILE
Syntax: fopen (“file_name”, “mode”);
Where the first parameter file_name is the name of the data file on the
disk. Which is to be opened. Mode specified the purpose of opening this file.
FILE *fp;
fp= fopen(“raju.dat”,”r”);
here raju.dat is the name of the data file to be opened and the second
argument r indicates that the file is opening for reading purpose.
Several modes are available in C. The following is the list of these modes
along with their descriptions.
mode Description
open for reading .the precondition is file must exist. Otherwise
fun returns Null value.
open for appending .if file already exist ,the new contents are
appended. Otherwise, a file is created. The fun returns NULL if
it is unable to create the file.
open for both reading and writing. The file must exits.
“w+”
open for both reading and writing .contents written over.
“a+”
open for reading and appending .if file is not existing ,the file is
created.
CLOSING A FILE:
The syntax of fclose function is
fclose(file_pointer);
Input/output operations on files:
The fputc() and fgetc() functions:
These input/output functions are used to read/write a single character
from/ to stream(files). The general forms are
fputc(char,fp);
fgetc(fp);
The fputc() function outputs a character to a stream. The first argument is the
character to be output and the second argument represents the file pointer. The
fgetc() function reads one character from input stream referred to by fp and
returns it.
The fgets() and fputs() functions:
The fgets() and fputs() functions are used to read and write strings
respectively. The general forms are
fputs(string, fp);
fgets(string,length,fp);
The fputs() function outputs a string to a stream pointed to by fp.
The fgets() function requires three arguments. First argument is address of the
string in which the read data is to be placed. Second argument is the length of
the string to be read and the last argument is the file pointer. The fgets() function
reads a string until either a new line character or the number of characters given
in the second argument have been read. If a new line is read, it will be part of the
string. However if gets() is terminated, the resultant string will be null.
The fscanf() and fprintf() functions:
These functions are used for formatted I/O. These can handle mixed data
at the same time and behave exactly like scanf() and printf() except that they
work on disk files rather than on standard input and output. The general syntax of
these functions are:
fscanf(fp, “format string”, argument list);
fprintf(fp, ”format string”, argument list);
int a=10;
clrscr();
fp=fopen("f:\\january.txt","a"); /* file opend with append mode */
if(fp==NULL)
{
printf("file not found");
exit(0);
}
fprintf(fp,"this is append mode"); /* writing to a file */
fprintf(fp,"\n%d",a);
fclose(fp);
getch();
}
Program 5: program to copy the data from existing file to new file.
#include<stdio.h>
#include<process.h>
void main()
{
FILE *fr,*fw;
char str[50];
clrscr();
fw=fopen("d:\\Abhiram.txt","w"); /* writting purpose */
fr =fopen("anil11.c","r"); /* reading purpose */
if(fr==NULL)
{
printf("file does't exsit ");
exit(0);
}
while( (fgets(str,50,fr)) >0) /* reading data from anil11 file */
{
fputs(str,fw); /* writting to a copied file is Abhiram */
}
fclose(fr);
fclose(fw);
getch();
}
Program 6: Write student sno, name ,6 subjects marks, total and average to
a file on the disk.
Program 7: To copy the data from existing file to a new file in the reverse
order.