CS-100-QP2-Solved-KTU Notes PDF
CS-100-QP2-Solved-KTU Notes PDF
E
(5)
OT
TUN
pointer
c)
K
Write a C program to store and display the following details of n students using
structure. Name, Rollno,Marks
(5)
5 a) Distinguish call by value and call by reference with the help of examples (10)
b) Explain the concept of Recursive function with the help of an example C (5)
program to find Factorial of a number.
6 a) Write a C program to sort an Array using Pointer. (10)
b) Write a C program to compute basic arithmetic operations using functions. (5)
PART C
Answer Any Two questions, each carries 20 marks.
7 a) With the help of an example C program explain Selection sort (10)
b) With the help of an example C program explain Recursive Binary Search (10)
8 a) Write notes on any ten file handling functions with syntax (10)
b) Explain the concept of Command Line Argument with the help of an example. (10)
9 a) Discuss storage classes with the help of examples. (10)
b) Write a C program to read name and marks of n number of students from user (10)
and store them in a file. If the file previously exits, add the information of n
students.
****
a) Qualifiers
Qualifiers are the keywords just using to alter the meaning of basic data types to yield a new data type.
• Size qualifiers
• Sign qualifiers
• Constant qualifiers
• Volatile qualifiers
Size Qualifiers
Size qualifiers are the keywords using to alter the size of basic data types. They are long and short. For integer
data types, there are three sizes: int, and two additional sizes called long and short, which are declared as long
int and short int. The keywords long and short are called sub-type qualifiers. The long is intended to provide
a larger size of integer, and short is intended to provide a smaller size of integer. However, not all
implementations provide distinct sizes for them. The requirement is that short and int must be at least 16
bits, long must be at least 32 bits, and that short is no longer than int, which is no longer than long. Typically, short
is 16 bits, long is 32 bits, and int is either 16 or 32 bits.
S . I N
T U N OTE
K
Eg:- long int, long float, short double etc.
Sign Qualifiers
Sign qualifiers are two signed and unsigned. signed is default one, i.e., declaring int a;
Is same as
signed int a;
both can store both +ve and –ve numbers. Declaring a variable unsigned int a;
can only store +ve values
Constant Qualifier
Volatile Qualifiers
The statements that are used to control the flow of execution of statements are known as conditional control
statements.
Conditional statements are divided into three types:-
1. Conditional
2. Unconditional
3. Looping
A ‘c ’program is a set of statements which are normally executed sequentially in the order in which they appear. This
happens when no options (or) no repetitions of certain calculations are necessary .however in practice we have a
number of situations where we may have to change the order of execution of statements until certain specified
conditions are met. This involves a kind of “decision making” to see whether a particular condition has occurred (or0
not & then direct the computer to execute certain statements accordingly.
‘C’ language passes such decision making capabilities & supports the following statements known as conditional (or)
decision making statements.
1. if statements
2. switch statement
3. conditional operator statement
If statement
S . I N
N OTE
The 'if' statement is a powerful decision making statement and is used to control the flow of execution of statements.
T U
if (test expression ) K
It is basically a two way decision statement and is used in conjunction with as expression .It takes the following form:-
It allows the computer to evaluate the expression first & then depending on whether the value of the expression
(relation(or)condition) is 'true'(non-zero)or 'false'(zero),it transfer the control to a particular statement .This point of
program has two paths follow, one for true condition & the other for the false condition.
The if statement may be implemented in different forms depending on the complexity of condition to be tested
1. simple if statement
2. if …else statement
3. nested if …else statement Downloaded from Ktunotes.in
4. else if ladder
1. Simple if statement:
General form:
if (test expression)
{
Statement–block;
}
Statement –x;
The statement-block may be a single statement (or) a group of statements. if the test statement is true, the
statement-block will be executed, other wise the statement block will be stopped & the execution will be jump to the
statement –x.
Note: when the condition is true, both the statement block & the statement-x are executed in sequence.
Flowchart for simple-if:
S . I N
T U N OTE
K
main()
{
int a, b,max;
printf("Enter any 2 values");
scanf("%d%d",&a,&b);
max=a;
if(max< b)
{
max =b;
}
printf("max =%d",max);
getch();
Downloaded from Ktunotes.in
}
2)If-else statement
Syntax:
if(test expression)
{
True block statement ;
}
else
{
false block statement;
}
Statement-x;
If test expression is true, then the true block statement, immediately following the if statement are executed ;
otherwise the false block statement () are executed . In either case , either true-block(or) false block will be executed,
not both.
S . I N
T U N OTE
K
main()
{
int n:
clrscr();
printf("enter any number");
scanf("%d",&n);
if(n%2==0)
printf("even number is even");
else
When a series of decision are involved, we may to have to use more than if-----else statement in nested form as
follows:
if(test condition)
{
if(test condition)
{
Statement-1;
}
else
{
Statement-2;
}
else
{
Statement-3;
}
Statement-x;
}
S . I N
T U N OTE
If the condition 1 is false , the statement-3 will be executed otherwise it continues to perform the second test
K
. IF the condition-2 is true, the statement-1 is evaluated; otherwise statement -2 will be evaluated & then the
control is transferred to statement-x.
{
if(a>c)
max=a;
else
max=c;
}
else
if(b>c)
max=b;
else
max=c;
}
S . I N
OTE
printf ("max=%d",max);
}
K T U N
4.THE ELSE IF LADDER:
There is another way of putting 'if's together when multipath decisions are involved. A multipath decision is a chain
of 'if's' in which the stmt associated with each else is an if. It takes the following general form.
if(cond1)
Stmt-1;
else if(cond2)
Stmt-2;
else if(cond3)
Stmt-3;
else if(condn)
Stmt-n;
else
Default stmt;
Stmt-x;
S . I N
OTE
main()
{
int a,b,c,max;
clrscr(); K T U N
printf("Enter values of a ,b,c");
scanf("%d%d%d",&a,&b,&c);
if(a>b && a>c)
max=a;
else if(b>c)
max=b;
else
max=c;
printf("Maximum is %d",max);
getch();
}
Loops
The versatility of computer lies in its ability to perform as set of instructions repeatedly. This involves a repeating
some position of a program either a specified number of a time or until a particular condition is being satisfied. This
repeative operation is done through a loop control structure.
There are 3 methods by way of which Downloaded from
we can repeat a part Ktunotes.in
of a program. They are
1. Using a while statement
2. Using a do while statement
3. Using a for while statement
While loop: It is a conditional control loop statement The while is an entry controlled loop statement. In entry
controlled loop, the control conditions are tested before start of the loop execution. If the conditions are not satisfied
then the body of the loop will not be executed.
General form
While (test condition) { Body of the loop }
The condition being tested may use relational or logical operators.
Eg: program to print "n" natural numbers while using loop.
main()
int n, i=1;
clrscr ();
while (i<=n)
S . I N
OTE
i++;
getch ();
K T U N
}
void main ()
int n, i=1;
clrscr();
scanf("%d", &n);
while(i<=n)
if(i%2==0)
i++;
Downloaded from Ktunotes.in
}
i=1;
while(i<=n)
if(i%2==1)
printf("%d\t", i);
i++;
getch();
do while
On some occasions it might be necessary to execute the body of the loop before test is performed. Such situations
can be handled with the help of do while statement.
General form:
do
{
Body of the loop
} while (test condition);
S . I N
On reaching the do statement the program proceeds to evaluate the body of the loop first. At the end of loop, the
U OTE
test condition in the while statement is evaluated. If the condition is true, the program continues to evaluate the
N
body of loop once again. This program continues as long as the condition is true. When the condition becomes false,
T
K
the loop while be terminated and the control goes to the statement that appears immediately after while statement.
Since, the test condition is evaluated at the bottom of the loop,the do while construct provides an exit-controlled
loop and the form the body of the loop is always executed at least once.
Flow chart for exit control:
S . I N
OTE
void main()
int n,i=1;
K T U N
clrscr();
scanf("%d",&n);
do
printf("%d\t",i);
i++;
}while(i<=n);
getch();
FOR Loop
The for loop is another entry controlled loop that provides a more concise loop control structure.
The general form of for loop is
for(initialization; test condition; increment)
{ Downloaded from Ktunotes.in
Body of the loop
}
1.The initializing control variables using assignment statement such as i=1&count=0,we can initialize control
variables. The variables i & count are known as
LOOP CONTROL VARIABLES 2. The value of control is tested using the test condition. The test condition is a relational
expression, such as i<10 determine, when the loop will exit. If condition is true ,the body will executed otherwise the
execution continues with the statement that immediately follows the loop.
3. When the body of the loop is executed, the control is transferred back to for statement after evaluating the last
statement in the loop. Now the control variable is incremented using assignment statement such as i=i+1 and the
new value of control variable is again tested to see whether the loop condition is satisfied or not.
Ex: To print 1 to 100 digits
03void main()
04{
05 clrscr();
06 for(i=1,i<=100,i++)
07 {
08 printf("%d/t",i);
09 }
10 getch();
S . I N
OTE
11}
12
K T U N
Ex: To print multiplication table of any numbers from 1 to 20
03void main()
04{
05 int n,i;
06 clrscr();
08 scanf("%d",&n);
09 for(i=1,i<=20,i++)
10 {
12 }
13 getch();
BREAK
It is used to terminate a switch statement.
BREAK is a keyword that allows us to jump out of a loop instantly, without waiting to get back to the conditional test.
CONTINUE
The keywords continue allow us to take the control to the beginning of the loop, by passing the statements inside the
loop which have not yet been executed.
GOTO STATEMENT
‘c’ supports go to statement to branch unconditionally from one point to another in the program.
The GOTO General Form is
goto Label;
----------- Label:
---------- Statement
---------- -------------
Label: -----------
Statement; ------------
Forward jump goto Label:
Backward jump
The go to require 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 "colors". The label is placed immediately before the statement where the
. I N
control is to be transferred. The label can be any where in the program either before (or) after go to label; state.
S
OTE
Ex; program to print ‘n’ natural number
01main()
K T U N
02{
03 int n,i=1;
04 clrscr();
05 printf("enternumber");
06 scanf("%d\t",i);
08 lb: printf("%d\t",i);
09 i++;
10 if(i<=n)
11 goto lb;
12 getch();
13}
SWITCH
01switch(expression)
02 {
03 case value-1:
04 block-1;
05 break;
06 case value-2:
07 block-2;
08 break;
09 ---------------------
10 ---------------------
11 case value-n:
12 block-n;
13 break;
14 default:
15 default-block;
S . I N
OTE
16 break;
17 }
18statement-x; K T U N
In the above general form,
Expression:It is an integer expression (or) character.
Value-1,value-2….. :These are constants (or) constant expressions (evaluable to integer constant) and are known as
"case labels". Each of these values should be unique with switch statement.
block-1,block-2…:These are the statement lists and may contain zero (or) more statements.There is no need to put
braces around these blocks.
Note: "case labels" must end with a colon (:).
When the switch is executed, the value of the expression is successively compared against the values value-1, value-
2…….If a case is found whose value matches with the value of the expression then the block of statements of that
particular case will get executed.
Break:The break statement at the end of each block signal the end of a particular case and causes an exit from switch
statement, transferring the control to the statement-x, following the switch.
The default is an optional case. When present it will be executed if the value of expression does not match with any
of the case values. If not present, no action takes place if all matches fail and the control goes to the statement-x.
main( )
printf("enterany2values");
scanf("%d%d",&a,&b);
printf("1.addition\n2.subraction\n3.multiplication\4.division\n6.modular\n");
printf("\nenteryouroption");
scanf("%d",&opt);
switch(opt)
case 1:
printf("aditionof%d&%dis%d",a,b,a+b);
break;
case 2:
printf("subof%d&%dis%d",a,b,a-b");
break;
case 3:
printf("multipleof%d&%dis%d",a,b,a*b);
break;
case 4:
S . I N
printf("divof%d&%dis%d",a,b,a/b);
T U N OTE
break;
case 5:
K
printf("modularof%d&%dis%d",a,b,a/b);
break;
default:
getch();
1. strcpy(s1, s2);
• Copies string s2 into string s1.
It copies the string str2 into string str1, including the end character (terminator char ‘\0’).
Example of strcpy:
Output:
2. strcat(s1, s2);
Example of strcat:
#include <stdio.h>
#include <string.h>
int main()
{
char s1[10] = "Hello";
char s2[10] = "World";
S . I N
OTE
strcat(s1,s2);
printf("Output string after concatenation: %s", s1);
}
return 0;
K T U N
Output:
3. strlen(s1);
Syntax:
Example of strlen:
#include <stdio.h>
#include <string.h>
int main()
{
char str1[20] = "BeginnersBook";
printf("Length of string str1: %d", strlen(str1));
return 0;
}
Downloaded from Ktunotes.in
Output:
4. strcmp(s1, s2);
It compares the two strings and returns an integer value. If both the strings are same (equal) then this function would
return 0 otherwise it may return a negative or positive value based on the comparison.
If string1 < string2 OR string1 is a substring of string2 then it would result in a negative value. If string1 > string2
then it would return positive value.
If string1 == string2 then you would get 0(zero) when you use this function for compare strings.
Example of strcmp:
#include <stdio.h>
#include <string.h>
int main()
{
char s1[20] = "BeginnersBook";
N
char s2[20] = "BeginnersBook.COM";
if (strcmp(s1, s2) ==0)
S . I
OTE
{
printf("string 1 and string 2 are equal");
}else
{
K T
printf("string 1 and 2 are different");
U N
}
return 0;
}
Output:
5. strrev()
#include<stdio.h>
#include<string.h>
int main()
Structure occupies higher memory space. Union occupies lower memory space over structure.
We can access all members of structure at a time. We can access only one member of union at a time.
E S
average;
};
OT };
return 0;
K TUN
}
int main()
scanf("%d", &array[i]);}
largest = array[0];
largest = array[i];
return 0;
a) With the help of flow chart explain compiling and execution of a C program (2.5)
S . I N
T U N OTE
K
Lets look at how to save the source code in a file, and how to compile and run it. Following are the simple steps:
2. Open a text editor and add the above-mentioned code.
3. Save the file as hello.c
4. Open a command prompt and go to the directory where you saved the file.
5. Type gcc hello.c and press enter to compile your code.
6. If there are no errors in your code the command prompt will take you to the next line and would generate
a.out executable file.
#include<stdio.h>
#include<conio.h>
void main()
{
int n1,n2,big;
Downloaded from Ktunotes.in
clrscr();
printf("\n Enter TwoNumbers”);
scanf("%d%d",&n1,&n2);
big = ((n1>n2)?n1:n2);
printf("\n The Greater Number is %d",big);
getch();
Output
Enter Two numbers
5
11
The Greater Number is 11
b) Write a C program to multiply two matrices using the concept of 2D arrays. (10)
#include <stdio.h>
int main()
{
int a[10][10], b[10][10], result[10][10], r1, c1, r2, c2, i, j, k;
S . I N
OTE
scanf("%d %d",&r2, &c2);
T
printf("Error! column of first matrix not equal to row of second.\n\n");
printf("Enter rows and column for first matrix: ");
scanf("%d %d", &r1, &c1);
printf("Enter rows and column for second matrix: ");
scanf("%d %d",&r2, &c2);
}
Output
S . I N
OTE
Enter elements a11: 3
Enter elements a12: -2
Enter
Enter
Enter
Enter
elements
elements
elements
elements
a13: 5
a21: 3
a22: 0
a23: 4 K T U N
Enter elements of matrix 2:
Enter elements b11: 2
Enter elements b12: 3
Enter elements b21: -9
Enter elements b22: 0
Enter elements b31: 0
Enter elements b32: 4
Output Matrix:
24 29
6 25
PART B
4
a) Explain the concept of Pointer in C with the help of example (5)
Pointers are variables that hold address of another variable of same data type.
Pointers are one of the most distinct and exciting features of C language. It provides power and
flexibility to the language. Although pointer may appear little confusing and complicated in the
beginning, but trust me its a powerful tool and handy to use once its mastered.
S . I N
OTE
of a. printf("%u",p); //this will also print the
T U N
address of a. printf("%u",&p); //this will also
Sample Output:
c) Write a C program to store and display the following details of n students using structure.
Name, Rollno,Marks
#include <stdio.h>
struct student
{
char name[50];
int roll;
float marks;
} s[10];
int main()
{
int i;
// storing information
for(i=0; i<10; ++i)
{
s[i].roll = i+1;
Output
5 a) Distinguish call by value and call by reference with the help of examples (10)
#include
<stdio.h> int
main()
{
int i= 2;
printf ("i squared is
S . I N
OTE
%d\n",squared(i)); printf ("i is
%d\n",i);
}
return 0;
K T U N
which will print:
i squared is 4 i is 2
i squared is 4 i is 4
The reason for this is that functions only have a local copy of the values sent to them. In C this is
known as pass by value or Call by value. Variables passed by value to a function.
Using a function you can create an addition to the C language which takes a number of arguments
and may return a single value.
Call By Reference
void swap(int a, int b)
{
a = a+b;
b=a-b;
a=a-b;
}
int main()
{
int a,b; Downloaded from Ktunotes.in
a=10;
b=5;
printf(“a= %d and b= %d”, a,b);
swap(a,b);
printf(“a= %d and b= %d”, a,b);
}
the output will be : a=10 and
b=5
a=10 and b=5
S . I N
OTE
a=5 and b=10
In the second function, the numbers are swaped because the function is called by reference and the values are
T U N
exchanged. The Address of variables are passed to the function. So whatever change we do in the function is done
K
in the value inside the address. The fig.depicts the same.
Recursive functions.
Recursion is a special property of the function. When a function calls itself then it is called recursion.
In the function with name recfun the function definition contains the function call to itself.
The execution is as follows :
The recfun() is called with arguement 5. inside the function it prints 5 and the recfun with arguement 4 is called in
which 4 is printed and recfun(3) called and so on upto recfun(0). The function recfun(0) returns without calling other
. I N
function and then recfun(1) returns and so on upto recfun(5) returns to the called function main.
S
Factorial of a Number using recurssion
T U N OTE
#include <stdio.h>
long int multiplyNumbers(int n); K
int main()
{
int n;
printf("Enter a positive integer: ");
scanf("%d", &n);
printf("Factorial of %d = %ld", n, multiplyNumbers(n));
return 0;
}
long int multiplyNumbers(int n)
{
if (n >= 1)
return n*multiplyNumbers(n-1);
else
return 1;
}
Output
S . I N
OTE
}
}
output
enter 5 nos;
K T U N
2 5 6 7 11
Sorted elements are: 11 7 6 5 2
b)Write a C program to compute basic arithmetic functions using functions.
b)
#include<stdio.h>
void main()
{
int a,b,c,d,e,f;
clrscr();
printf("Enter Two Values :");
scanf("%d%d",&a,&b);
sum(a,b);
mult(a,b);
div(a,b);
getch();
}
sum(int x,int y)
{
int z;
z=x+y;
printf("Addtion : %d\n",z);
return 0;
}
mult(int x,int y)
{
Downloaded from Ktunotes.in
int z;
z=x*y;
printf("Multiply : %d\n",z);
return 0;
}
div(int x,int y)
{
int z;
z=x/y;
printf("Div : %d\n",z);
return 0;
}
PART C
7 a) With the help of an example C program explain Selection sort
Selection Sort
Consider the following depicted array as an example.
For the first position in the sorted list, the whole list is scanned sequentially. The first position where
14 is stored presently, we search the whole list and find that 10 is the lowest value.
S . I N
U N OTE
So we replace 14 with 10. After one iteration 10, which happens to be the minimum value in the list,
T
K
appears in the first position of the sorted list.
For the second position, where 33 is residing, we start scanning the rest of the list in a linear
manner.
We find that 14 is the second lowest value in the list and it should appear at the second place. We
swap these values.
After two iterations, two least values are positioned at the beginning in a sorted manner.
The same process is applied to the rest of the items in the array. Following is a pictorial depiction
2. Loop over the input until it is empty, "removing" the first remaining (leftmost)
element.
Algorithm :
/*
* C Program to Implement Selection Sort
*/
#include <stdio.h>
void selectionSort(int arr[], int size)
{
int i, j;
for (i = 0 ; i < size;i++)
{
for (j = i ; j < size; j++)
{
if (arr[i] > arr[j])
swap(&arr[i], &arr[j]);
}
}
}
//fucntion to swap to variables
void swap(int *a, int *b)
{
int temp;
temp = *a;
*a = *b;
*b = temp;
}
output
S . I N
The idea of binary search is to use the information that the array is sorted and
OTE
reduce the time complexity to O(Logn).
T U N
We basically ignore half of the elements just after one comparison.
K
1. Compare x with the middle element.
2. If x matches with middle element, we return the mid index.
3. Else If x is greater than the mid element, then x can only lie in right
half subarray after the mid element. So we recur for right half.
4. Else (x is smaller) recur for the left half.
Recursive implementation of Binary Search
#include<stdio.h>
int main(){
int a[10],i,n,m,c,l,u;
l=0,u=n-1;
return 0;
}
int mid,c=0;
if(l<=u){
mid=(l+u)/2;
if(m==a[mid]){
c=1;
}
else if(m<a[mid]){
return binary(a,n,m,l,mid-1);
}
else
return binary(a,n,m,mid+1,u);
}
else
return c;
}
Sample output:
S . I N
OTE
Enter the size of an array: 5
N
Enter the elements of the array: 8 9 10 11 12
T U
Enter the number to be search: 8
Number is found.
K
8 a) Write notes on any ten file handling functions with syntax (10)
Here filename is the name of the file to be opened and mode specifies the
purpose of opening the file. Mode can be of following types,
*fp is the FILE pointer (FILE *fp), which will hold the reference to the opened(or
created) file.
mode description
r opens a text file in reading mode
w opens or create a
text file in writing mode. a
opens a text file in
append mode
r+ opens a text file in both reading
and writing mode w+ opens a text
file in both reading and writing
Closing a File
The fclose() function is used to close an already opened file.
General Syntax :
int fclose( FILE *fp );
Here fclose() function closes the file and returns zero on success, or EOF if
there is an error in closing the file. This EOF is a constant defined in the
header file stdio.h.
S . I N
Input/Output operation on File
T U N OTE
K
In the above table we have discussed about various file I/O functions to perform
reading and writing on file. getc() and putc() are simplest functions used to
read and write individual characters to a file.
#include<stdio.h>
#
i
n
c
l
u
d
e
<
c
o
n
i
o
.
h
>
m
a
i
F
I
L
E
*
f
p
;
c
h
a
r
c
h
;
f
p
S . I N
OTE
f
o
p
e K T U N
n
(
"
o
n
e
.
t
x
t
"
,
"
w
"
)
;
p
r
i
n
t
d
a
t
a
"
)
;
p
u
t
c
(
c
h
,
f
p
S . I N
OTE
)
;
K T U N
}
fclose(fp);
fp = fopen("one.txt", "r");
w
h
il
e
(
(
c
h
g
e
t
c
(
f
p
E
O
F
)
p
r
i
n
t
f
(
"
%
c
"
,
c
h
)
;
fclose(fp);
N
}
S . I
T U N
Reading and Writing in a Binary File OTE
K
A Binary file is similar to the text file, but it contains only large numerical
data. The Opening modes are mentioned in the table for opening modes
above.
fread() and fwrite() functions are used to read and write is a binary file.
fwrite(data-element-to-be-
written,
size_of_elements
,
number_of_elem
ents, pointer-to-
file);
fread() is also used in the same way, with the same arguments like fwrite()
function. Below mentioned is a simple example of writing into a binary file
const char *mytext = "The quick brown
fox jumps over the lazy dog"; FILE *bfp=
fopen("test.txt", "wb");
if (bfp) {
fwrite(mytext,
sizeof(char),
We will be using fseek() and ftell() functions to find the size of the
file. There are others ways to find the file size, like looping on the whole
content of file and finding out the size, but using File Handling functions
makes it easier.
#include<stdio.h>
#include<conio.h>
void main()
F
I
L
E
S . I N
OTE
*
f
p
;
K T U N
c
h
a
r
c
h
;
int size = 0;
fp
=
fo
pe
n(
"
M
yF
ile
.tx
t",
"r
else
fclose(fp);
S . I N
T U N OTE
b)
K
Explain the concept of Command Line Argument with the help of an example.
Here argc counts the number of arguments on the command line and argv[ ]
is a pointer array which holds pointers of type char which points to the
arguments passed to the program.
#include <conio.h>
printf("The
arguments
supplied are:\n");
for(i=1;i< argc;i++)
printf("%s\t",argv[i]);
else
} getch();
Return (0);
I N
Remember that argv[0] holds the name of the program and argv[1] points to the
S .
OTE
first command line argument and argv[n] gives the last argument. If no argument
is supplied, argc will be one.
9 a)
K T U N
Discuss storage classes with the help of examples.
Scope rules Storage classes.
Variables and functions having external linkage are available to all files
that constitute a program. File scope variables and functions declared as
static (described shortly) have internal linkage. These are known only
within the file in which they are declared. Local variables have no linkage
and are therefore known only within their own block.
T U N
Static Storage Class OTE
4.
K
External Storage Class
Now, let us discuss these storage classes one by one.
In above example program you see three definitions for variable i. Here, you
may be thinking if there could be more than one variable with the same name.
Yes, there could be if these variables are defined in different blocks. So, there
will be no error here and the program will compile and execute successfully.
The printf in the inner most block will print 3 and the variable i defined
in the inner most block gets destroyed as soon as control exits from the block.
Now control comes to the second outer block and prints 2 then comes to the
outer block and prints 1. Here, note that automatic variables must always be
initialized properly, otherwise you are likely to get unexpected results
because automatic variables are not given any initial value by the compiler.
. I N
implicitly. Register variables are also given no initial value by the compiler.
S
OTE
The following piece of code is trying to get the address of variable i into
K T U N
pointer variable p but it won't succeed because i is declared register;
therefore following piece of code won't compile and exit with error "error:
address of register variable requested".
#include <stdio.h>
int main()
printf("Val
ue of i:
%d", *p);
printf("Add
ress of
i: %u",
p);
staticdemo.c..
S . N
they cannot be used outside the file (translation unit)
I
/* staticdemo.c */
T U N OTE
K
#include <stdio.h>
Static in i;
i++;
printf("%d\n", gInt);
gInt++;
int main()
Static Demo();
Static Demo();
Output
Static variables have default initial value zero and initialized only once in their
lifetime.
I N
later than it has been used in printf. In this example, the extern
S .
OTE
specifier tells the compiler that variable x has already been defined and it is
declared here for compiler's information.
int main()
K T U N
#include <stdio.h> extern int x;
{
printf("x: %d\n ", x);
}
int x = 10;
b) Write a C program to read name and marks of n number of students from user and store them
in a file. If the file previously exits, add the information of n students.
#include <stdio.h>
int main() {
char name[50];
scanf("%d",&n);
FILE *fptr;
fptr=(fopen("C:\\student.txt","a"));
if(fptr==NULL) {
printf("Error!");
exit(1);
for (i=0;i<n;++i) {
scanf("%s",name);
scanf("%d",&marks);
S . I N
OTE
fclose(fptr);
}
return 0;
K T U N