Professional Documents
Culture Documents
Ans:An algorithm is a step by step description of how to arrive at a solution. It is finite set of instructions which
when followed in sequence solves a particular task. Start
Once algorithm is written, it can be implemented in any high level language.
Algorithm to add two numbers
Step 1: Input the first number as A Read A, B
Step2: Input the second number as B
Step3: Set Sum = A + B
Step4: Print Sum Sum=A+B
Step 5: End
Flow chart is a graphical or symbolic representation of an algorithm. Print Sum
Flow chart to add two numbers and display the sum is as shown in the figure
Start
Q) What is Token and explain?
Ans: Tokens are basic building blocks of C Programming. Each and every smallest individual units in a C
program are known as C tokens.
No Token Type Example
1 Keyword Keywords are reserved words by compiler. while
2 Variables Variables are named locations in memory. sum
3 Constants Constants are assigned to variables 89
4 Special Symbols Used in different declarations in C ( ), {}
5 Operators Used in expressions /,*,+
6. String Sequence of characters “hello”
Q) Difference between while and do-while Flow chart for while loop
Flow chart for do-while loop
Body of loop
False
Condition
?
False
Conditio
n? True
True
True Body of loop
False
StatementX StatementX
Q) What is software?
Ans:
Software is a set of programs. A program is a set of instructions arranged in a sequence to guide a computer to
solve a problem.
Computer software is written by programmers using a programming language. Computer software is divided
into 2 categories
• System software
• Application software
System software allows a user to interact with the computer hardware.and provides a platform for running
application software. System software is responsible for controlling and managing hardware components of a
computer system. Ex: Operating System, Compiler, BIOS, Device Drivers.
Application Software performs specific task with the help of system software. Ex: Word processors, Image
editors, Spread sheets etc..
character data char 1 -128 to 127 To store characters char gender = ‘m’;
type
Integer data type int 2 -32767 to 32768 To store integers int num=10;
Double data type double 8 1.7E-308 to To store big floating double sal = 1234567.12345;
1.7E+308 point numbers
There are 4 type modifiers that can be applied to the basic data types. They are:
unsigned, signed, short and long.
All the modifiers (long, short, unsigned and signed) can be applied to integer data type.
Only signed and unsigned can be applied to character data type.
Only long can be applied to double data type.
a) If statement: The if statement is used to control the flow of execution of statements. The syntax and flowchart of is
statement is as shown below.
Example:
#include <stdio.h>
output: Total amount to be paid = 5500
void main()
amount = amount-500;
if-else statement: In if else control statement, group of statements are executed when condition is true. If condition is
false, then else part statements are executed.
Example:
#include <stdio.h>
int main()
Output:
{
m and n are not equal
int m=40,n=20;
if (m == n)
else
Switch statement:
The switch makes one selection when there are several choices to be made.
If there is no match the statements in the default case gets executed. Syntax of switch is as follows
Switch(test expression)
default: defaultblock;
#include<stdio.h>
#include<conio.h>
void main()
{
int ch;
float a,b,res;
clrscr();
printf(“Enter two numbers:”);
scanf(“%f%f”,&a,&b);
printf(“\nMenu\n1.Addition\n2.Subtraction\n3.Multiplication\n4.Division”);
printf(“\nEnter your choice:”);
scanf(“%d”,&ch);
switch(ch)
{
case 1: res=a+b;
break;
case 2: res=a-b;
break;
case 3: res=a*b;
break;
case 4: res=a/b;
break;
default: printf(“Wrong choice!!nPress any key…”);
}
printf(“nResult=%f”,res);
getch();
}
b) ROM: ROM is a non- volatile memory as data in the ROM is not lost when the power is switched off.
ROM can also be accessed randomly.
Secondary memories are used to store large amounts of data. They are inexpensive than primary memories.
They are also non-volatile.
A drive is used to read the contents of a hard disk, CD , DVD or a floppy.
a) hard disk drive (HDD)
Accessing the hard drive for information takes time.
b) CD ROM drive– A device used to read CD-ROMs. CD-RW drive is used to read data/ write data from/to
CD-RW disks.
c) DVD ROM drive – A device that is used to read DVDs. DVD-RW drive is used to read data/ write data
from/to DVD-RW disks.
• Motherboard – A circuit board that allows the CPU to interact with other parts of the computer.
• Power Supply – Gives your computer power by converting alternating current (AC) supplied by the wall
connection to direct current (DC).
• Expansion Cards – Used to add/improve functionality to the computer.
a. Sound Card – Used to input and output sound under program control. Sound cards provide better sound
quality than the built in sound control provided with most computers.
b. Graphics Card – Used to convert the logical representation of an image to a signal that can be used as input
for a monitor.
c. Network Card – Used to provide a computer connection over a network. Transmit data at 10/100/1000 Mb/s.
• Fan – Keeps your computer cool. If the inside of your computer becomes too hot, then the computer can
overheat and damage parts.
• Heatsink – Used to disperse the heat that is produced inside the computer by
the CPU and other parts by increasing surface area.
• Ports – Means of connecting peripheral devices to your computer.
Q) Explain different sections of a C program. (or) Explain the structure of C
Ans:
Documentation section
pre-processor directives
global declarations
main()
{
local variables to function main ;
statements associated with function main ;
}
f1()
{
local variables to function 1 ;
statements associated with function 1 ;
}
f2()
{
local variables to function f2 ;
statements associated with function 2 ;
}
Preprocessor Directives: It is not possible to write our own output functions every time we wanted to
communicate with the computer. So we use header files that have standard functions which can be included in
our programs.
All pre-processor directives begin with a # and the must written in the beginning of the c program
#include <stdio.h>
Documentaion section contains a set of comments giving the name of the program, the author and other
details which the programmer would like to use later. Comments are non-executable
Single Line Comment Starts with ‘//’ . used to comment out just Single Line in the Code written after //.
Multi line comments starts with /* and ends with */.
Multi line comments comment out multiple lines written between /* and */
main()
All C programs will consist of at least one function. The only function that has to be present is the function
called main. Execution of a C program starts with main().
User Defined Functions
Any number of user defined functions can be written. All functions including main() are divided into 2 parts.
1. declaration section
2. statement section
declaration section is used to describe the data that will be used in the function. The data declared within a
function will be visible only within the function and will be removed from memory once the control goes out of
the function.
statement section contains the code that manipulates the data to perform a specified task.
Global declarations : globally declared variables are accessed through out the program and will be in memory
until the program runs.
Ans:
S.no Types of Operators Description
1 Arithmetic operators These are used to perform mathematical calculations like addition,
subtraction, multiplication, division and modulus
2 Assignment operators These are used to assign values to variables.
(=)
3 Relational operators These are used to compare the values of two variables
4 Logical operators These operators are used to perform logical operations on expression.
5 Bit wise operators These operators are used to perform bit operations on variables.
6 Conditional (ternary) Conditional operators return one value if condition is true and returns
operators another value if condition is false.
7 Increment/decrement These operators are used to either increase or decrease the value of the
operators variable by one.
8 Special operators &, *, sizeof( )
Arithmetic Operators in C:
S.no Arithmetic Operators Operation Example
1 + Addition A+B
2 - Subtraction A-B
3 * multiplication A*B
4 / Division A/B
5 % Modulus A%B
Assignment operators in C:
Operators Example Explanation
Simple assignment operator = sum = 10 10 is assigned to variable sum
Compound assignment operators += sum += This is same as sum = sum + 10
(+=, *=, /=, %=, etc.. 10
Relational operators in C:
S.no Operators Example Description
1 > x>y x is greater than y
2 < x<y x is less than y
3 >= x >= y x is greater than or equal to y
4 <= x <= y x is less than or equal to y
5 == x == y x is equal to y
6 != x != y x is not equal to y
Logical operators in C:
There are 3 logical operators in C language. They are, logical AND (&&), logical OR (||) and logical NOT (!).
S.no Operators Name Example Description
1 && logical AND (x>5)&&(y<5) It returns true when both conditions are true
2 || logical OR (x>=10)||(y>=10) It returns true when at-least one of the condition is true
3 ! logical NOT ! It reverses the state of the operand
((x>5)&&(y<5))
Bit wise operators in C:
Decimal values are converted into binary values and bit wise operators work on these bits.
Bit wise operators in C language are & (bitwise AND), | (bitwise OR), ~ (bitwise OR), ^ (XOR), << (left shift)
and >> (right shift).
Truth table for bit wise operation Bit wise operators
x y x|y x & y x ^ y Operator_symbol Operator_name
0 0 0 0 0 & Bitwise_AND
0 1 1 0 1 | Bitwise OR
1 0 1 0 1 ~ Bitwise_NOT
1 1 1 1 0 ^ XOR
<< Left Shift
>> Right Shift
Do while loop:
/* Program to print the natural numbers from 1 to 5 using do - while loop*/
#include <stdio.h>
void main() Syntax of do while loop is as follows:
{
int i=1;
do
{ do {
printf(“%d\n”,i); statements;
i++; Syntax of for loop is as follows:
} while(i < 5); }
for (exp1; exp2; expr3)
{ while (condition);
}
statements;
For loop:
}
/* Program to print the natural numbers from 1 to 10 using for loop*/
Where,
#include <stdio.h> exp1 – variable initialization
( Example: i=0, j=2, k=3 )
void main()
exp2 – condition checking
{ ( Example: i>5, j<3, k=3 )
exp3 – increment/decrement
( Example: ++i, j–, ++k )
int i;
for(i=1;i < 5;i++)
{
printf(“%d\n”,i);
}
}
Output: 1
2
3
4
5
Q) Whys is clrscr() used?
clrscr() will clear the output of previous execution. It is defined in conio.h header file.
Source code
is the program written by user.
ex: factorial.c
Compiler
converts the c program into
machine level language
Object code
ex: factorial.obj
Executable
ex: factorial.exe
Functions
Definition: Functions are self contained and independent block of statements.
C allows a big program to be divided into segments known as functions.
Need for functions
1. Code reuse.
2. Dividing a program into functions allows each function to be tested separately.
3. A large program may not fit in main memory.
Using Functions
While using functions we use the following terminology
1. If a function f() uses another function g().
f() is called calling function and g() is called called function
2. Function call
When a function is called, the compiler jumps to the called function to execute the statements of called function.
When the called function is executed, the program control passes back to the calling function
main() int f1(int z) Here main() is calling function and f1() is called function
{ {
3. int x, y; …… Inputs given to function are called parameters / arguments.
y= f1(x); return z; Arguments are 2 types
……. } i) Actual arguments: arguments given in function call.
} Here x is actual argument
ii) Formal arguments : arguments given in function
definition. Here z is called formal argument.
4. Return statement:
return statement terminates the execution of a function and returns the control to the calling function.
5. Function declaration/ Function prototype
Before using function, the compiler must know about its return type and number and type of arguments the
function takes
Syntax: return_type function_name (datatype variable1…..);
6. Function definition
When a function is defined space is allocated for that function in memory f1()
A function definition consists of {
i) Function header : …..
Syntax: return_type function_name (datatype variable1…..) …..
ii) Function body : }
contains code to perform specific task
Passing arguments to functions
Arguments can be passed by calling function in 2 ways
1. Call by value: In this method, the called function creates new variables and
copies the values of arguments passed to it.
If the values of arguments are modified, the modified values can be sent to caller using return statement.
Advantages: variables, literals (Ex: 6), expressions (x+1) can be passed using call by value
Disadvantage: copying arguments requires more memory and takes lot of time.
2. Call by reference : In this method, the function receives address of the
arguments. Changes made to arguments in called function will also change the values in calling function
Advantages: A function can return only one value. To return multiple values, call by reference is used
/* swapping using call by value */ /* swapping using call by reference */
void swap(int , int); void swap(int *, int *);
void main() void main()
{ {
int a ,b; int a ,b;
clrscr(); clrscr();
printf(“enter two numbers”); printf(“enter two numbers”);
scanf(“%d%d”, &a,&b); scanf(“%d%d”, &a,&b);
printf(“values before swapping = %d \t%d”, a, b); printf(“values before swapping = %d \t %d”, a, b);
swap(a,b); swap(&a,&b);
getch(); getch();
} }
void swap ( int x, int y) void swap ( int *x, int *y)
{ {
int temp; int temp;
temp =x; temp =*x;
x=y; *x=*y;
y=temp; *y=temp;
printf(“values after swapping = %d\t %d”, x, y); printf(“values after swapping = %d \t %d”, *x, *y);
} }
Types of functions:
There are 2 types of functions
1. Built in / pre-defined functions: these are stored as library files. Ex: printf, scanf, abs(), strlen()
2. User defined functions: these functions are defined by the user with his own logic. Ex: main(), factorial()
Categories of functions
1. Functions with arguments and with return type
2. Functions with arguments and without return type
3. Functions without arguments and without return type
4. Functions without arguments and with return type
Recursion
Recursive function is a function that calls itself.
Every recursive function must have an exit condition/ terminating condition / stop condition. If not,
recursive function will call itself indefinitely.
When the problem can be defined in recursive manner, then recursion can be used.
Advantages:
1. Recursive solutions are shorter and simpler than non- recursive solutions.
2. Code is clearer and easier to use.
3. Follows divide and conquer to solve problems
Disadvantages:
1. Recursion is difficult concept to some programmers
2. Recursion uses system stack. If the system stack is limited, it is difficult to implement recursion
3. uses more memory and time to execute
4. it is difficult to find errors.
Example: 1 if a=1
factorial(a) =
a*factorial(a-1) if a > 1
Types of Recursion
1. Direct recursion: a function is said to be directly recursive if it is explicitly calls itself.
2. Indirect Recursion: a function is said to be indirectly recursive if it calls another function which
ultimately calls it.
3. Tail Recursion: if no operations are pending to be performed when the recursive function returns to its
caller.
4. Linear Recursion: when the pending operation (if any) does not make another recursive call to the
function
5. Non linear / Tree recursion: when the pending operation makes another recursive call to the function
Scope of a variable
Scope is accessibility and visibility of the variables.
Variables in C has 4 types of scope
1. block scope:
a statement block is a group of statements enclosing within { and }. If a variable is declared
within a statement block , as soon as control exits the block, the variable will be removed from
memory. Such a variable is said to have block scope.
2. function scope: variable is accessible and visible from the beginning to end of a function
3. program scope: variable is accessible and visible from the beginning to end of a program
4. file scope: variable is accessible and visible from the beginning to end of a file
Storage Classes
The storage class defines scope (visibility) and lifetime of variable and functions declared within a C program.
The storage class will determine
1. where the variable will be allocated memory ( in register or main memory etc...)
2. how long the variable stays in memory (life time )
3. scope of the variable i.e, the part of C program in which the variable is accessible or visible.
4. whether the variable will be automatically initialized or not.
C supports 4 storage classes.
1. automatic
2. register
3. external
4. static
Array: It is collection of similar data type elements. All Elements of array are stored in contiguous memory
locations.
Declaration of Arrays:
An array can be declared by specifying 3 things
1. Data type: what kind of values it can store Ex: int , char , float etc..
2. Name: to identify the array
3. Size: the maximum number of values the array can hold
Syntax:
type name[size]
We can change the marks of individual elements using the above method. In marks[2] data element, 2 is the
index or subscript. It is the (index+1) i.e, 5th element in the array marks as index starts with zero in arrays.
Types of arrays:
1. One dimensional arrays (1D)
2. Two dimensional arrays (2D)
3. Multi dimensional arrays (3D)
1. 1D array is represented using one index ‘[ ]’ .It is mostly used for searching and sorting
2. 2D array is represented using two indexes ‘[][]’. One subscript denotes rows and other denotes columns.
It is mostly used for matrix representation. Example: int marks[3][3]; (3 rows and 3 columns)
3. Multi dimensional arrays have more than 2 indices. Example: int m[3][2][2]
m is an array of three 2D arrays.
Program to read and print the values of 1D Find the sum of the elements of an array
array void main()
void main() {
{ int marks[5], i, sum;
int marks[5], i; clrscr();
clrscr(); sum=0;
printf(“Enter marks of 5 students”); printf(“Enter marks of 5 students”);
for (i=0;i<5;i++) for (i=0;i<5;i++)
{ {
scanf(“%d”,&marks[i]); scanf(“%d”,&marks[i]);
printf(“\n marks = %d”, marks[i]); sum = sum+ marks[i];
} }
getch(); printf(“sum = %d”, sum);
} getch();
}
Search an element in an array using linear search Search an element in an array using binary search
void main() void main()
{ {
int a [10], i, n, s, flag = 0; int a [10], i, n, s, left, right, mid, flag=0;
printf(“Enter the number of elements”); printf(“Enter the number of elements”);
scanf(“%d”, &n); scanf(“%d”, &n);
printf (“enter %d elements”,n); printf (“enter %d elements”,n);
for (i=0;i<n;i++) for (i=0;i<n;i++)
{ {
scanf(“%d”,&a[i]); scanf(“%d”,&a[i]);
} }
printf(“enter the search element”); printf(“enter the search element”);
scanf(“%d”, &s); scanf(“%d”, &s);
for (i=0;i<n;i++) left=0;
{ right=n-1;
if ( s == a[i]) mid = (left+right)/2;
{ while (left < = right)
flag = 1; {
break; if ( s = = a[mid])
} flag =1;
} else if ( s< a[mid])
if( flag = = 1) right = mid-1;
printf(“Element found”); else
else left = mid+1;
printf(“Element not found”); mid = (left+right)/2;
getch(); }
} if( flag = = 1)
printf(“Element found”);
else
printf(“Element not found”);
getch();
}
Program to sort the given elements using bubble sort. Program to read and print values of 2D array
#include <stdio.h> #include <stdio.h>
#include <conio.h> #include <conio.h>
void main() void main()
{ {
int a [10], i, n, j, t; int a[5][5],i,j,r,c;
printf(“Enter the number of elements”); clrscr();
scanf(“%d”, &n); printf(“enter the order of matrix”);
for (i=0;i<n;i++) scanf(“%d %d”, &r,&c);
scanf(“%d”,&a[i]); printf(“Enter %d elements”, r*c);
for ( i=0; i< n; i++) for(i=0; i<0r;i++)
{ for(j=0; j<c;j++)
for ( j = i+1; j < = n; j++) scanf(“%d”, &a[i][j]);
{
if( a[i] > a[j]) for(i=0; i<r;i++)
{ {
t= a[i]; for(j=0; j<c;j++)
a[i]=a[j]; printf(“%3d”, a[i][j]);
a[j]=t; printf(“\n”);
} }
} getch();
} }
printf(“\n sorted array”);
for (i =0; i< n; i++)
printf(“%5d”, a[i];
getch();
}
1. 1D arrays and passing them as arguments to functions can be as shown in the diagram below
Passing entire array to function
When entire array is passed to function, they are always passed by address. In arrays there is no call by value
and there is only call by reference.
When the address of array is passed there is no way the function will come to know about the size of the array.
so size of the array must also be passed.
Example: One dimensional
int soe(int *, int ); arrays
void main()
{
int marks[3] = {65,67,69};
int sum;
sum = soe(&marks[0], 3);
printf(“sum of elements in array =%d”,sum); One dimensional Passing entire
} arrays array
int soe(int *b, int size)
{
int i, s=0;
for ( i=0; i< size, i++)
s=s+(*(b+i));
return s; Passing data Passing
} values addresses
clrscr();
printf(“enter the order of matrix A”);
scanf(“%d%d”,&r1,&c1);
scanf(“%d”, &a[i][j]);
scanf(“%d”, &b[i][j]);
if(r1 != c2)
{
printf(“\n multiplication is not possible”);
exit(0);
}
else
{
for(i=0; i<r1; i++)
{
for (j=0; j<c2; j++)
{
c[i][j]=0;
printf(“\n”);
}
}
STRINGS
A String in C is defined to be a sequence of characters terminated by null character ‘\0’. The null character
indicates the end of a string.
Declaration of Array of char type:
Syntax: char string_name[size];
Example: char str[20];
str is string name
20 is the size of string.
Example 2: char str[10]=”COMPUTER”;
C O M P U T E R \0
getchar() Used to read a character from keyboard and waits for ENTER char s =
or TAB or ESC key to be pressed getchar();
getch() Reads a character from keyboard and returns immediately and char s =
does not wait for ENTER key to be pressed. It does not display getch();
the character entered by user
getche() Reads a character from keyboard and returns immediately and char s =
does not wait for ENTER key to be pressed. It displays the getche();
character entered by user
Write a program to read and write strings using puts() and gets()
void main()
{
char str[20];
puts("Enter a string");
gets(str);
puts(str);
}
String manipulation functions
The string library functions which are in the header file “string.h”
The most commonly performed operations are
1. Finding the length of the string – strlen()
2. Copying one string to another string – strcpy()
3. Comparing two string --- strcmp()
4. Concatenation of two strings --- strcat()
5. Reverse the given string-- strrev()
6. Convert the input string to lower case strlwr()
7. Convert the input string to upper case strupr()
1. Finding the length
strlen() is used to find the number of characters in a string excluding the null character
Usage: int length = strlen(string)
Write a program to find the length of a string
#include <string.h> Output:
void main() Enter a string
{ computers
char str[10]; You entered computers
int len; Length of the string is 9
printf(“enter a string”);
scanf(“%s”, &str);
len = strlen(str);
printf(“You entered %s”,str);
printf(“length of the string is %d”,len);
}
2. copying one string to another string
Usage: strcpy(string1, string2);
This function copies the string2 to string 1 including the null character. The contents if any in string1 will be
lost.
#include <string.h>
void main() Output:
{ Enter a string
char str1[50],str2[50]; mpcs
clrscr(); copied string in str1 is mpcs
printf("enter a string");
gets(str2);
strcpy(str1,str2);
printf(“copied string in str1 is %s”,str1);
}
3. strcmp() is used to compare two strings
Usage: int ret = strcmp( string1, string2)
This function return values as follows:
• returns < 0 if str1 is less than str2.
Output:
• returns > 0 if str2 is less than str1. Enter first string
mpcs
• returns = 0 if str1 is equal to str2. Enter second string
Write a program to compare two strings mecs
#include <string.h> the two strings are not equal
void main()
{
char str1[50],str2[50];
int ret;
clrscr();
printf("enter first string");
gets(str1);
printf("enter second string");
gets(str2);
ret = strcmp(str1,str2);
if (ret == 0)
printf(“the two strings are equal”);
else
printf(“the two strings are not equal”);
}
4. Concatenation of two strings
The strcat() function appends the string2 to the end of the string1. The null character in string1 is overwritten.
The process stops when null character of string2 is copied. String1 must be big enough to store the contents of
string1 and string2.
Usage: strcat(string1, string2)
Write a program to concatenate two strings
#include <string.h>
Output:
void main()
Enter first string
{
mpcs
char str1[50],str2[50];
Enter second string
clrscr();
First year
printf("enter first string");
String1 = mpcs First year
gets(str1);
printf("enter second string");
gets(str2);
strcat(str1,str2);
printf(“string1 =%s”,str1);
}
5. Reverse the input string
#include <string.h>
Output:
void main()
enter a string
{
mpcs
char str1[50],str2[50];
reverse = scpm
clrscr();
printf("enter a string ");
gets(str1);
printf(“reverse =%s”, strrev(str1));
}
6. Convert the input string into lower case
#include <string.h>
Output:
void main()
enter a string
{
MPCS
char str1[50],str2[50];
lowercase = mpcs
clrscr();
printf("enter a string in capital letter ");
gets(str1);
printf(“lowercase =%s”, strlwr(str1));
}
7. Convert the input string into uppercase
#include <string.h>
Output:
void main()
enter a string in lower case
{
mpcs
char str1[50],str2[50];
uppercase = MPCS
clrscr();
printf("enter a string in lower case ");
gets(str1);
printf(“upper case =%s”, strupr(str1));
}
ARRAYS OF STRINGS
An array of string is declared as char names[5][30];
First index indicates how many strings are needed and Second index indicates the length of every individual
string.
char names[3][30] = {“RAM”,”SHYAM”,”SAI”};
3 names and each name can consist of maximum of 30 characters .
Memory representation of 2D array
names[0] R A M \0
names[1] S H Y A M \0
names[2] S A I \0
UNIT – VI Pointers
Pointer Variables
When a variable is declared some amount of memory is allocated to hold the value of that variable. The size of
memory allocated depends on the datatype of the variable. Each memory location has an address.
pointer is a variable that stores the address of another variable.
Applications of pointers
1. pointers are used to pass arrays and strings as function arguments.
2. using pointers one can pass functions as arguments to another function
3. pointers are used to create complex data structures like trees, stack, queues etc..
4. pointers are used for dynamic memory allocation
Declaring and initializing Pointers
6000 100
x ptr1
Example 1:
int x = 6000;
int *ptr1;
ptr1=&x;
ptr1 will store the starting address (here 100) and will read 2 bytes as it points to a integer variable when
dereferenced using *ptr1.
Addresses 10 10 10 10 11 111
6 7 8 9 0
100000.0 106
sal ptr2
Example2:
float sal = 100000.0;
float *ptr2;
ptr2=&sal;
ptr1 and ptr2 occupy same amount of memory. Memory enough to store the address of a memory location.
The datatype of pointer indicate that they contain the address of a variable of that datatype.
Indirection operator (or) Value at Address operator (*)
When * is used as unary operator after the pointer variable other than at the declaration of pointer variable, then
* is called indirection operator.
void main()
{
int x= 6000, *ptr;
ptr = &x;
printf(“%d”, *ptr);
}
The above program will print 6000 on the screen.
* operator deferences a pointer and will display the value present at the address stored in pointer.
printf (“%d”, *(&x) ; will also prints 6000 on the screen. Hence *ptr (or) x (or) *(&x) are same.
ptr (or) &x are same.
Write a program to declare and access pointer variable
void main()
{
int x = 6000, *ptr;
ptr = &x;
printf(“ value of x = %d”,x);
printf(“ value of x = %d”,*ptr);
printf(“ value of x = %d”,*(&x));
printf (“address of x = %u”, ptr);
printf (“address of x = %u”, &x);
}
Generic pointers
It is a pointer variable that has void as its data type. Generic pointer can be used to point to variables of any data
type.
Ex: void *ptr;
Pointers and arrays
Example: int marks[10], *ptr ;
ptr = marks;
The array name marks holds the starting address of the array i.e, &marks[0]
Write a program to print the elements of array using pointers
void main()
{
int marks[3] = { 1,2, 3}, *ptr,i=0 ;
ptr=&marks[0];
printf(“elements in an array are”);
while( i<3)
{
printf(“%d\t”, *ptr);
ptr++;
}
int *p;
p= (int *) malloc(20*sizeof(int));
2. free(p); is used to deallocate the memory.
101
102
103
104
105
106
107
108
109
110
111
112
113
Example:
struct student
{
int roll_no;
char name[10];
int marks;
}s1;
Structure initializations
1) 2) 3)
struct book struct book struct book b1,b2,b3;
{ { b1.title=”ANSI C”;
Write a program to print the details of 2 students such as rollno, name, course and fees.
#include <string.h>
void main()
{
struct student
{
int roll;
char name[40], course[10];
};
struct student s1={151301, “adi”,”IMPCS”};
struct student s2;
s2.roll=151302;
strcpy(s2.name,”naik”);
strcpy(s2.course,”IMPCS”);
printf(“rollno = %d \t name=%s \t course=%s \n”, s1.roll, s1.name, s1.course );
printf(“rollno = %d \t name=%s \t course=%s \n”, s2.roll, s2.name, s2.course );
}
typedef
By using typedef keyword an alternate name is given to existing data type.
When we precede a struct name with typedef keyword then the struct becomes a new data type.
main()
{
student s1;
printf("enter name and date, month and year of birth of student\n");
scanf("%s %d %d %d", &s1.name, &s1.dob.dd, &s1.dob.mm, &s1.dob.yy);
printf("name =%s \t date of birth =%d - %d - %d", s1.name, s1.dob.dd, s1.dob.mm, s1.dob.yy);
}
Arrays of structures
Example: student st[30];
To assign values to ith student, you should write
st[i].name = “ xyz”;
st[i].dob.dd = 21;
st[i].dob.mm=12;
st[i].dob.yy=1991;
Self referential Structures contains a pointer to data that is of same type as that of the structure.
example:
struct node
{
int val;
struct node *next;
}
Here the structure node will contain 2 types of data- an integer val and next, which is pointer to a node.
Structure is declared using struct keyword Union is declared using union keyword
{ {
}object; }object;
Each member within a structure is allocated A common memory of size equal to largest
unique memory. member size is allocated. Each member
struct book within union share the common memory.
{ union book
char title[20]; {
Size of structure is >= sum of sizes of its Size of union is equal to its largest member
members size
All the members can be assigned values at a Only one member can be assigned value at a
time. time
All the members can be accessed at same Only one member can be accessed at a time
time
Values assigned to one member will not Values assigned to one member may cause
cause the change in other members. change in values of other members.
Files
File is a collection of records stored in secondary memory such as hard disk. Record is collection of fields and
each field can carry a value.
Stream is a logical interface. Stream can be attached to any device to communicate with that device. The device
can be logical file or physical keyboard.
There are 3 standard streams in C language
1. standard input (stdin)----------- stream from which the program receives data.
2. standard output (stdout) ------- stream to which the program writes the data.
3. standard error (std err) ---------- stream to which the program writes the error messages.
stdin, stdout and stderr are the logical names given to these streams.
By default Standard input is connected to keyboard. Standard output and Standard error are connected to
monitor.
Buffer: When a stream is linked to a disk file, a buffer is automatically created.
Buffer is block of memory used for temporary storage of data. Buffers are needed as the disk drives are block
oriented.
Types of Files
There are 2 types of files.
1. ASCII text files
2. Binary files.
1. ASCII text file is a stream of characters that can be sequentially processed by a computer. In a text file, each
line of data ends with a new line character (\n). Each file ends with a special character (EOF) marker
Example: Integer vaue 123 will be stored as a sequence of 3 characters. And so requires 3 bytes to store
int value will be represented as 2 bytes of memory internally, but externally the int value will be represented as
a string of characters. To convert internal representation into external, we use printf and fprintf functions.
To convert external representation to internal representation, scanf and fscanf functions are used.
2. Binary files may contains any type of data encoded in binary form. A binary file does not require any special
processing.
Binary files can be processed sequentially or randomly.
Integer vaue 123 will be stored in 2 bytes .
Using files in C
To use files in C, we must follow the below steps
1. Declare a FILE pointer variable
2. Open the file (fopen)
3. Process the file
4. Close the file.
Declaring a file pointer variable.
A file pointer variable that points to a structure FILE has to be declared as fopen functions return a FILE
pointer.
Opening a file
a file must be opened before data can be read and write. fopen() function is used to open the file.
Syntax: filepointer_variable = fopen(“filepath”,”mode”);
ex: fp = fopen(“myfile.txt”, “r”);
File modes:
mode Description
"w" Creates an empty file for writing. If a file with the same name already exists, its contents
are erased
"a" Appends data at the end of the file. The file is created if it does not exist.
"r+" Opens a file for reading and writing. The file must exist.
note: the modes that can be used with binary files are rb,wb,ab, rb+,wb+,ab+
closing a file:
The C library function fclose closes the stream. All buffers are flushed.
syntax: fclose(filepointer_variable);
Example: fclose(fp);
Write a program to read student details from a file and display the details
#include <stdlib.h>
void main()
{
FILE *fp;
char name[40];
int roll;
fp = fopen("student.txt","r");
if( fp == NULL)
{
printf("file cannot be opened");
exit(0);
}
printf("enter rollno and name");
fscanf(fp,"%d%s", &roll,&name);
printf("\n Roll no = %d \t name = %s",roll, name);
fclose(fp);
}
if( feof(fp) )
break ;
printf("%c", c);
}while(1);
fp = fopen("file.txt",
"w+");
fwrite(c, strlen(c) + 1, 1,
fp);
fread(buffer, strlen(c)+1,
1, fp);