C Study Material
C Study Material
Unit 1
MCQ QUESTIONS:
1. Select the correct answer for the question.
1) Who invented C Language.?
A) Charles Babbage
B) Grahambel
C) Dennis Ritchie
D) Steve Jobs
8. The Sequence of the Instruction written to perform specific task is called the__________.
A. Statement
B. Program
C. Algorithm
D. None of the above
17. A Variable of a particular type can hold only a constant of the same type. Choose right
answer.
A) TRUE
B) FALSE
C) It depends on the place the variable is declared.
D) None of the above.
22. A ___________ is a data name that may be used to store a data value
A. Keyword
B. Constant
C. Variable
D. Data type
24. A single character can be defined as a character data type using the keyword ________
A. String
B. char
C. character
D. int
25. Data types are derived from the fundamental data types are called as ___________
A. Derived data types
B. Detailed data types.
C. Defined data types
D. None of the above
Descriptive Questions:
1) Explain any two phases of Program Development Cycle with diagram
1. Decimal Integer
2. Octal Integer
3. Hexadecimal Integer
Example:
Decimal Constants : 15, -265, 0, 99818, +25,
Octal Constants : 045 , 077
HexaDecimal Constants : 0X6 , 0X88
Real constant
The numbers containing fractional parts like 99.25 are called real or floating points constant.
The Real or Floating-point constants can be written in two forms:
1. Fractional or Normal form
2. Exponential or Scientific form
Express a Real constant in fractional form
A real constant consistsyy for a series of digits representing the whole part of the number,
followed by a decimal pointy, followed by a series of representing the fractional part.
Valid Real constants (yyFractional): 0.0 -0.1 +123.456 .2 2.
Invalid Real constant: - 1 - a decimal point is missing
1, 2.3 - Illegal character (.)
Single Character Constantsy
It simply contains a single character enclosed within ' and ' (a pair of single quote). It is to be
noted that the character '8' is not the same as 8. Character constants have a specific set of integer
values known as ASCII values (American Standard Code for Information Interchange).
Example:
'X', '5', ';'
String Constants
These are a sequence of characters enclosed in double quotes, and they may include letters,
digits, special characters, and blank spaces. It is again to be noted that "G" and 'G' are different
- because "G" represents a string as it is enclosed within a pair of double quotes whereas 'G'
represents a single character.
Example:
"Hello!", "2015", "2+1"
Backslash character constant
• There are some characters which have special meaning in C language.
• They should be preceded by backslash symbol to make use of special function of them.
Given below is the list of special characters and their purpose
Ex:
Backslash_character Meaning
\b Backspace
\f Form feed
10) Explain in brief classification of a) integer types and b) floating point types
Integer Data Type:
• Integers are whole numbers with a range of values. Integers occupy one word of
storage.
• In a 16-bit machine, the range of integers is -32768 to+32767
• In order to provide some control over a range of numbers and storage space, C
has 3 classes of storage for integers namely, short int, int and long int in both
signed and unsigned format
• Short int is used for small range of values and requires half the amount of
storage as a regular int number uses.
• Long int requires double the storage as an int value.
• In unsigned integers, all the bits in the storage are used to store the magnitude
and are always positive.
12) Explain with examples declaring, initializing and assigning value to variable
Variables are identifiers whose value can change during execution of the Program. Variables
used to store values. A data type is associated with each variable & it decides what values the
variable can take. Rules for declaring variable are same as that of identifier.
In C, a variable must be declared before it can be used. Variables are declared in the
declaration section of function.
Declaration of Variable
data_typevariable_name;
or
data_type variable1, variable2,…,variablen;
where data_type is any valid c data type and variable_name is any valid identifier.
For example,yyy
int a;
float variable;
float a, b;
Initialization of Variable
Assigning initial value to the variable is called variable initialization. C variables declared
can be initialized with the help of assignment operator ‘=’.
Syntax
data_typevariable_name=constant/literal/expression;
or
variable_name=constant/literal/expression;
Example
1 int a=10;
2 int a=b+c;
3 a=10;
4 a=b+c;
Multiple variables can be initialized in a single statement by single value, for example,
a=b=c=d=e=10;
13) Explain with example #define statement in ‘C. List rules apply to it.
The preprocessor #define is another more flexible (see Preprocessor Chapters) method to
define constants in a program.
#define TRUE 1
#define FALSE 0
#define NAME_SIZE 20
The const keyword is to declare a constant, as shown below:
int const a = 1;
const int a =2;
Symbolic Constant in C Language :
A symbolic constant is a name that substitutes for a sequence of characters. The characters
may represent numeric constant, a character constant or a string constant. Thus, a symbolic
constant allows a name to appear in place of a numeric constant, a character constant or a
string.
Constants defined using #define pre-processor directive is called symbolic constant.
Syntax: #define symbolic name value
For example
#define PI 3.141593
#define TRUE 1
#define FALSE 0
#define PI 3.141593 defines a symbolic constant PI whose value is 3.141593. When the
program is preprocessed, all occurrences of the symbolic constant PI are replaced with the
replacement text 3.141593.
Note that the pre-processor statements begin with a #symbol, and are not end with a semicolon.
By convention, preprocessor constants are written in UPPERCASE.
• Makes Logic Clear: The main advantage of using a flowchart to plan a task is that
it provides a pictorial representation of the task, which makes the logic easier to
follow. The symbols are connected in such a way that they show the movement
(flow) of information through the system visibly. The steps and how each step is
connected to the next can be clearly seen. Even less experienced personnel can
trace the actions represented by a flowchart, that is, flowcharts are ideal for
visualizing fundamental control structures employed in computer programming.
• Communication: Being a graphical representation of a problem-solving logic,
flowcharts are a better way of communicating the logic of a system to all
concerned. The diagrammatical representation of logic is easier to communicate to
all the interested parties as compared to actual program code as the users may not
be aware of all the programming techniques and jargons.
• Effective Analysis: With the help of a flowchart, the problem can be analysed in
an effective way. This is because the analysing duties of the programmers can be
delegated to other persons, who may or may not know the programming
techniques, as they have a broad idea about the logic. Being outsiders, they often
tend to test and analyse the logic in an unbiased manner.
• Useful in Coding: The flowcharts act as a guide or blueprint during the analysis
and program development phase. Once the flowcharts are ready, the programmers
can plan the coding process effectively as they know where to begin and where to
end, making sure that no steps are omitted. As a result, error-free programs are
developed in HLL and that too at a faster rate.
• Proper Testing and Debugging: By nature, a flowchart helps in detecting the
errors in a program, as the developers know exactly what the logic should do.
Developers can test various data for a process so that the program can handle every
contingency.
• Appropriate Documentation: Flowcharts serve as a good program documentation
tool. Since normally programs are developed for novice users, they can take the
help of the program documentation to know what the program actually does and
how to use the program.
2.When one of the operands is real and the other is an integer, the expression is called
__________ arithmetic expression.
A) mixed mode
B) yreal mode
C) integer mode
D) expression mode
13. What is the other name for C Language ?: Question Mark Colon Operator.?
A) Comparison Operator
B) If-Else Operator
C) Binary Operator
D) Ternary Operator
14. Choose a syntax for C Ternary Operator from the list.
A) condition ? expression1 : expression2
B) condition : expression1 ? expression2
C) condition ? expression1 < expression2
D) condition < expression1 ? expression2
17. If you have to make decision based on multiple choices, which of the following is best
suited?
a) if
b) if-else
c) if-else-if
d) All of the above
20. If the Boolean expression of if statement evaluates to ________, then the block of code
inside the if statement will be executed.
A. True
B. False
C. True and False
D. None of these
switch(a)
{
case 2: printf("ZERO "); break;
case default: printf("RABBIT ");
}
}
A) RABBIT
B) ZERO RABBIT
C) No output
D) Compiler error
24. The ___________statement skips some statements inside the loop and goes back to
beginning of loop for executing next iteration.
A. if
B. continue
C. goto
D. break
Descriptive questions
1. List and explain arithmetic, logical and relational operators available in C
ArithmeticOperators:
All the basic arithmetic operators are supported by C. These operators can
manipulate with any built in data types supported by C. The various operators are
tabulated as follows:
Operator Meaning
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulo Division
Comparisons can be done using relational operators. A relational expression contains
a combination of arithmetic expressions, variables or constants along with relational
operators. A relational expression can contain only two values i.e. true or false. When
the expression is evaluated as true then the compiler assigns a non zero(1) value and 0
otherwise. These expressions are used in decision statements to decide the course of
action of a running program.
Syntax: ae1 relational operator ae2
where ae1 and ae2 are arithmetic expressions
Operators Meaning
< Less than
<= Less than or equal to
> Greater than
y>= Greater than or equal to
== Equal to
!= Not equal to
Logical Operators:
An expression that combines two or more relational expressions is called a
logical expression and the operators used to combine them are called logical
operators.
Syntax: R1 operator R2
where R1 and R2 are relational expressions
Operator Meaning
&& Logical And
|| Logical Or
! Logical Not
Example :
if(agey > 55 && salary < 1000)
if(number < 0 || number > 100)
Increment/Decrement Operators:
C has 2 very powerful operators that are not found in any other language. They
are increment/decrement operators i.e. ++ and --. The ++ operator is used to increment
value of a variable by 1. The -- operator is used to decrement value of a variable by 1.
Both are unary operators and can be written as follows: ++m, m++ , m—and –
m. Both m++ and ++m mean the same thing when they form statements independently.
But, they behave differently when used in expression on the right hand side of
assignment operator.
E.g. Let a=5; x=a++; Here, this statement can be broken into 3 statements
as follows a=5; x=a; a=a+1;
In the above example, the value of a is assigned to x and then its value is incremented
by 1. A prefix operator first adds 1 to the operand and then the result is assigned
to the variable on the left. A postfix operator first assigns its value to the variable
and then increments its value by 1.
E.g. m=10;y
y=--m
Here the value of m is decremented by 1 and then assigned to y. Hence the value of y is
9.
3) Write a note on bitwise operators available in C
These operators are used to manipulate data at bit level. These operators are
used for testing the bits or shifting the bits either to the left or right.
Operator Meaning
& Bitwise And
| Bitwise Or
^ Bitwise exclusive Or
<< Shift left
>> Shift Right
~ One’s complement
Example 2:9-12/(3+3)*(2-1)
Whenever parentheses are used, the expressions within parentheses assume
highest priority. If two or more sets of parentheses appear one after another as shown
above, the expression contained in the left-most set is evaluated first and the right-most
in the last. Given below are the new steps.
First pass
Step 1: 9-12/6 * (2-1)
Step 2 : 9-12/6 * 1
Second pass
Step 3 : 9-2* 1
Step 4 : 9-2
Third pass
Step 5 :7
• The format string must be a text enclosed in double quotes. It contains type of data to
input. Example: integer (%d) , float (%f) , character (%c) or string (%s).
• The arg1,arg2..argn contains a list of variables each preceded by & ( to get address of
variable) and separated by comma.
Examples :-
int i, d ;
char c ;
float f ;
scanf( "%d", &i ) ; /* input integer data*/
scanf( "%d %c %f", &d, &c, &f ) ; /* input int , char and float */
The & character is the address of operandin C, it returns the address in memory of the
variable it acts on.
Syntax :
printf(“format string”, v1,v2…vn);
The printf() function is used for formatted output and uses a format string which is made up
of a series of format specifiers to govern how it prints out the values of the variables or
constants required. The more common format specifiers are given below
%c character %f floating point
%d integer %lf double floating point
%i integer %e exponential notation
%u unsigned integer %s string
%ld signed long %x hexadecimal
%lu unsigned long %o octal
#include<stdio.h>
void main()
{
int i;
printf("Please enter a value...");
scanf("%d", &i);
printf( "\nYou entered: %d", i);
}
When you will compile the above code, it will ask you to enter a value. When you will enter
the value, it will display the value you have entered on screen.
11) Explain simple if statement and else..if with syntax and example.
Simple if Statement
The basic format of if statement is:
if(test_expression)
{
statement 1;
statement 2;
...
}
Here if the test expression is evaluated to true, the statement block will get executed, or it will
get skipped.
Example :
#include<stdio.h>
main()
{
int a = 15, b = 20;
if (b > a) {
printf("b is greater");
}
}
If ..else Statement
If the test expression evaluates to true, then the if block will be executed, otherwise, the else
block will be executed.
Example:
#include<stdio.h>
main( )
{
int a;
printf("n Enter a number:");
scanf("%d", &a);
if(a>0)
printf( "n The number %d is positive.",a);
else
printf("n The number %d is negative.",a);
}
Syntax:
if (condition1)
{
/* Executes when condition1 is true*/
if (condition2)
{
/* Executes when condition2 is true*/
}
}
Example
#include <stdio.h>
int main()
{
int var1, var2;
printf("Input the value of var1:");
scanf("%d", &var1);
printf("Input the value of var2:");
scanf("%d",&var2);
if (var1 != var2)
{
printf("var1 is not equal to var2\n");
/*Nested if else*/
if (var1 > var2)
{
printf("var1 is greater than var2\n");
}
else
{
printf("var2 is greater than var1\n");
}
}
else
{
printf("var1 is equal to var2\n");
}
return 0;
}
while(i<10)
{
printf("%d\n",i);
i++;
}
}
16) Explain do..while statement with syntax and example
do...while loop in C programming checks its condition at the bottom of the loop.
A do...while loop is similar to a while loop, except the fact that it is guaranteed to execute at
least one time.
Syntax :
do {
statement(s);
} while(condition );
if the condition is true, the flow of control jumps back up to do, and the statement(s) in the
example
main ()
{
int a = 10;
/* do loop execution */
do {
printf(" %d\n", a);
a = a + 1;
}while( a < 20 );
}
When the above code is compiled and executed, it prints values from 10 to 19
#include <stdio.h>
main ()
{
int i;
/* for loop execution */
for( i = 1;i < 10;i++ ){
printf("%d\n",,i);
}
}
When the above code is compiled and executed, it prints values from 1 to 9
i) Nesting of Loops
C programming allows to use one loop inside another loop. The following section shows a few
examples to illustrate the concept.
The syntax for a nested for loop statement in C is as follows −
for ( init_exp; test_exp; update_exp )
{
for(init_exp; test_exp; update_exp)
{
statement(s);
}
statement(s);
}
while(condition) {
statement(s);
}
statement(s);
}
Here we are not updating the value of i. So after each iteration value of i remains same. As a
result, the condition (i<10) will always be true. For the loop to work correctly add i++;
UNIT-3
Multiple Choice Questions:
2.
int main() {
int i = 1 ;
while( i<=2)
printf("%d",i);
return 0;
}
What is output of above code
A.12
B.i
C.Compilation error
D.indefinite loop
3. When _________ is encountered inside any loop, Control automatically passes to the first
statement after loop.
A.Continue
B.break
C.goto
D.return
4. This Loop tests the condition after having executed the Statements within the Loop.
A.while
B.do-while
C.for Loop
D.if-else-if
return 0;
}
A) RABBIT
B) RABBIT is printed unlimited number of times.
C) No output
D) Compiler error.
6. What is the way to suddenly come out of or Quit any Loop in C Language.?
A) continue; statement
B) break; statement
C) leave; statement
D) quit; statement
15. What is the minimum and maximum Indexes of this below array.?
int main()
{
int ary[9];
return 0;
}
A) -1, 8
B) 0, 8
C) 1,9
D) None of the above
Descriptive Questions:
1. Explain while statement with syntax and example
The syntax of a while loop is:
while (testExpression)
{
Statement block
}
where, test Expression checks the condition is true or false before each loop.
The while loop evaluates the test expression.If the test expression is true (nonzero),
codes inside the body of while loop are executed. The test expression is evaluated again.
The process goes on until the test expression is false. When the test expression is false,
the while loop is terminated. While loop is entry controlled loop.
Example
/* Programm to print numbers from 1 to 9*/:
#include <stdio.h>
main()
{
int i=1;
while(i<10)
{
printf("%d\n",i);
i++;
}
}
2. Explain do..while statement with syntax and example
do...while loop in C programming checks its condition at the bottom of the loop.
A do...while loop is similar to a while loop, except the fact that it is guaranteed to
execute at least one time.
Syntax :
do {
statement(s);
} while (condition );
if the condition is true, the flow of control jumps back up to do, and the statement(s) in
the loop executes again. This process repeats until the given condition becomes false.
Example
main ()
{
int a = 10;
/* do loop execution */
do {
printf(" %d\n", a);
a = a + 1;
}while( a < 20 );
}
When the above code is compiled and executed, it prints values from 10 to 19
3. Explain for statement with syntax and example
A for loop is a repetition control structure that allows you to efficiently write a loop that
needs to execute a specific number of times.
Syntax
The syntax of a for loop in C programming language is −
for ( init_exp; test_exp; update_exp )
{
statement(s);
}
• The init_exp step is executed first, and only once. This step allows you to
initialize loop control variables.
• Next, the test_exp is evaluated. If it is true, the body of the loop is executed. If
it is false, the body of the loop does not execute and the flow of control jumps to the
next statement just after the 'for' loop.
• After the body of the 'for' loop executes, the flow of control jumps back up to
the update_exp This statement allows you to update any loop control variable
• The condition is now evaluated again. If it is true, the loop executes and the
process repeats itself. After the condition becomes false, the 'for' loop terminates.
Example
#include <stdio.h>
main ()
{
int i;
/* for loop execution */
for( i = 1;i < 10;i++ ){
printf("%d\n",,i);
}
}
When the above code is compiled and executed, it prints values from 1 to 9
4. Explain the following:
i. Nested loops
C programming allows to use one loop inside another loop. The following
section shows a few examples to illustrate the concept.
The syntax for a nested for loop statement in C is as follows −
while(condition) {
while(condition) {
statement(s);
}
statement(s);
}
do {
statement(s);
do {
statement(s);
}while( condition );
}while( condition );
Example
#include <stdio.h>
main()
{
int i=1,j;
while (i <= 5)
{
j=1;
while (j <= i )
{
printf("%d ",j);
j++;
}
printf("\n");
i++;
}
}
ii. Infinite loops
A loop becomes an infinite loop if a condition never becomes false. Loop will
not terminate
Example
int i = 1
while(i<10)
{
printf("%d\n", i);
}
Here we are not updating the value of i. So after each iteration value of i remains same.
As a result, the condition (i<10) will always be true. For the loop to work correctly add
i++;
int a = 1 ;
/* while loop execution */
while( a < 10 )
{
printf("value of a: %d\n", a);
a++;
if( a > 5)
{
The continue statement skips some statements inside the loop and goes back to
beginning of loop for executing next iteration.. The continue statement is used with
decision making statement such as if...else.
continue;
#include <stdio.h>
main ()
{
int a = 1 ;
/* do loop execution */
do {
if( a == 5)
{
a ++;
continue;
}
printf("value of a: %d\n", a);
a++;
} while( a < 10 );
}
The body of the loop may or The body of the loop will be executed at least once
may not be executed at all. condition is checked at last
for, while are an example of an Do…while is an example of an exit control loop.
entry control loop
int arr[10];
• Here int is the data type, arr is the name of the array and 10 is the size of array.
It means array arr can only contain 10 elements of int type.
• Index of an array starts from 0 to size-1 i.e first element of arr array will be
stored at arr[0]address and the last element will occupy arr[9].
Initialization of an Array
If we omit the size of the array, an array size is equal to number elements assigned.
int balance[] = {1000 , 200, 300, 700, 500};
in the above example size of array is 5.
Example:
/* Program to initialize array at run time.*/
#include<stdio.h>
main()
{
int a[4];
int i, j;
printf("Enter array element:");
for(i=0; i<4; i++)
{
scanf("%d",&a[i]); //Run time array initialization
}
printf("Value in Array:");
for(j=0; j<4; j++)
{
printf("%d \n",a[j]);
}
getch();
}
0 1 2 3 n-1
1
2
3
4
m-1
9. Explain the different ways available for the initialization of string variable .
Character arrays can be initialized in two ways. That is, characterr
arrays may be initialized when they are declared.
char subject[9] = {'c',' o' ,'m' ,'p','u' ,'t',' e' ,'r' ,'\0' }
Even though there are eight characters in the word "computer", the character array
"subject" is initialized to 9. This is because to store the null ('\0') character at the end
of the string. When character array is initialized by listing its elements, null character
must be supplied explicitly as shown in the above example.
Consider another example
char subject[9]={ "computer"};
Here each character of the string "computer" is stored in individual elements of
a character array subject, but it automatically adds null character at the end of the string.
It is also possible to initialise a character array without specifying the number of
elements. In such cases, the size of the array will be determined automatically, based
on the number of elements in the given string. .
For example
The input function scanf ( ) with %s format specification can be used to read an array
of characters.
Example
char Subject[10];
scanf("%s" ,Subject);
If we enter subject name as "Computer Science" then only the first word "Computer"
will be assigned to the variable Subject This is because, the scanf( ) function terminates
its input on the first occurrence of the white space.
In such cases, when line of text has to be read from the terminal one can make use of
gets() function or one can make use of getchar() function repeatedly to read successive
single characters from the keyboard and place them into a character array.
¬¬
Example Program 1
# include <stdio.h>
# include <string.h>
main()
{
char text[50], ch;
int i=0;
printf("Enter line of text and press enter key at the end\n");
while((ch=getchar())!=’\n’)
(
text[i]=ch;
i++;
}
text[i]='\0' /*put null at the end*/
printf("Entered line of the text:\n%s" ,text);
}
10. Write a program to sort elements of an integer array.
Program to input n numbers and sort it in ascending order using bubble sort.
#include<stdio.h>
main()
{
int a[10],n,i,j,temp;
clrscr();
printf("Enter number of elements:");
scanf("%d",&n);
printf("Enter array elements:");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
for(i=0;i<n;i++)
for(j=0;j<n-i-1;j++)
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
printf("Sorted array is\n");
for(i=0;i<n;i++)
printf("%d\t",a[i]);
getch();
}
11. Write a program to search for an element in an integer array.
Program to search a number in a list, using linear search technique. If present print its
position(s).
#include<stdio.h>
main()
{
int a[10],n,x,i,flag=0;
clrscr();
printf("Enter number of elements:");
scanf("%d",&n);
printf("Enter array elements:");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("Enter search element:");
scanf("%d",&x);
for(i=0;i<n;i++)
{
if(a[i]==x)
{
printf("%d is found at the location %d\n",x,i);
flag=1;
}
}
if(flag==0)
printf("Given element not found");
getch();
}
12. Explain with example how to declare, initialize and use strings in C.
Declaring String Variables
Where string_name is a valid variable name and the size determines' the number of
characters in the string_name.
For example
char name [20] ;
When the compiler assigns a string data to character array, it automatically supplies a
null character ('\0') at the end of the string. Therefore the array size should be one more
than maximum number of characters in the string.
Initializing Strings
Even though there are eight characters in the word "computer", the character array
"subject" is initialized to 9. This is because to store the null ('\0') character at the end
of the string. When character array is initialized by listing its elements, null character
must be supplied explicitly as shown in the above example.
Consider another example
char subject[9]={ "computer"};
Here each character of the string "computer" is stored in individual elements of
a character array subject, but it automatically adds null character at the end of the string.
It is also possible to initialise a character array without specifying the number of
elements. In such cases, the size of the array will be determined automatically, based
on the number of elements in the given string. .
For example
The input function scanf ( ) with %s format specification can be used to read an array
of characters.
Example
char Subject[10];
scanf("%s" ,Subject);
If we enter subject name as "Computer Science" then only the first word "Computer"
will be assigned to the variable Subject This is because, the scanf( ) function terminates
its input on the first occurrence of the white space.
In such cases, when line of text has to be read from the terminal one can make use of
gets() function or one can make use of getchar() function repeatedly to read successive
single characters from the keyboard and place them into a character array.
¬¬
Example Program 1
# include <stdio.h>
# include <string.h>
main()
{
char text[50], ch;
int i=0;
printf("Enter line of text and press enter key at the end\n");
while((ch=getchar())!=’\n’)
(
text[i]=ch;
i++;
}
text[i]='\0' /*put null at the end*/
printf("Entered line of the text:\n%s" ,text);
}
The printf function with %s format specifier can be used to display the strings on the
screen. For example the following statement
Example Program 2
#include <stdio.h>
main()
{
clrscr();
printf ("%20s", "Left justified printing.\n");
printf ("%-40.24s", "Left justified printing.\n");
printf ("%-40.16s", "Left justified printing.\n");
printf ("%-40.12s", "Left justified printing.\n");
printf ("%-40.8s", " Left justified printing.\n");
printf ("%-40s", "Left justified printing.\n");
printf ("%-40.0s", " Left justified printing.\n");
printf ("%40.25s", "Right justified printing.\n");
printf ("%40.20s", "Right justified printing.\n");
printf ("%40.5s", "Right justified printing.\n");
printf ("%40.0s", "Right jusdfied printing.\n”);
}
The output of the program illustrates the following features of the %s specifications.
1. When the field width is less than the length of the string, the
entire string is printed.
2. The integer value on the right side of the decimal point specifies the number
of characters to be printed.
3. When the number of characters to be printed is specified as zero, nothing is
printed.
4. The minus (-) sign in the specification causes the string to be printed left
justified.
1. strcat( ) function
This function is used to concatenate two strings, i.e., it appends one string at the end of
another string. This function accepts two strings as parameters and adds the contents of
the second string at the end of the first string. Its syntax is follows
strcat (string!, string2);
here, the string string2 is appended to the end of string1.
Example Program 3
2. strlen() function
strlen() function returns the number of characters in the given string. Here, the length
does not include the terminating character '\0' (NULL). Its syntax is as follows.
Len = strlen( string);
Where Len is an integer type variable and string is an one dimensional array of
characters.
Example Program 4
3. strcmp () function
This function is used to compare two strings. The function accepts two strings as
parameters and returns an integer, whose value is:
Less than 0, if the first string is less than the second string Equal to 0, if both are
identical
Greater than 0, if the first string is greater than the. second string. The general form of
strcmp() function is as follows
strcmp (stringl, string2);
The strcmp() function compares two strings, character by character, (ASCII
comparision) to decide the greatest one. Whenever two characters in the string differ,
there is no need to compare the other characters of the strings.
Example Program 5
#include <string.h>
#include <stdio.h>
main()
{
char Strl [] = "aaa", Str2[] = "bbb", Str3[] = "ccc";
int ptr;
clrscr();
ptr = strcmp(Str2, Str]);
if (ptr > 0)
printf("String 2 is greater than String 1 \n");
else
printf("String 2 is less than String 1 \n");
ptr = strcmp(Str2, Str3);
if (ptr > 0)
printf("String 2 is greater than String 3\n");
else
printf("String 2 is less than String 3\n");
getch();
}
4. strcpy() function
This function copies one string to another. The strcpy() function accepts two strings as
parameters and copies the second string, character by character into the first string, upto
and including null character of the second string. Its syntax is as follows
strcpy (string 1, string2);
Example Program 6
#include <stdio.h>
#include <string.h>
main()
{
char string[25];
char strl [ ] = "Computer Science";
clrscr( );
strcpy(string, strl);
printf("Copied string: %s\n", string);
getch();
}
14. Mention suitable string functions to do the following:
a. To find length of the string
strlen() function returns the number of characters in the given string. Here, the
length does not include the terminating character '\0' (NULL). Its syntax is as
follows.
Len = strlen( string);
Where Len is an integer type variable and string is an one dimensional array of
characters.
Example Program 4
Example Program 6
#include <stdio.h>
#include <string.h>
main()
{
char string[25];
char strl [ ] = "Computer Science";
clrscr( );
strcpy(string, strl);
printf("Copied string: %s\n", string);
getch();
}
c. To add two strings
This function is used to concatenate two strings, i.e., it appends one string at the end
of another string. This function accepts two strings as parameters and adds the
contents of the second string at the end of the first string. Its syntax is follows
strcat (string!, string2);
here, the string string2 is appended to the end of string1.
Example Program 3
int main() {
char str[20] = "coffee";
strrev(str);
return 0;
}
15. What are the possible values that the function strcmp( ) can return? What do they
mean?
This function is used to compare two strings. The function accepts two strings as
parameters and returns an integer
Return Value from strcmp()
Return
Remarks
Value
Example:
include <stdio.h>
#include <string.h>
int main () {
char str1[15];
char str2[15];
int ret;
strcpy(str1, "abcdef");
strcpy(str2, "ABCDEF");
if(ret < 0) {
printf("str1 is less than str2");
} else if(ret > 0) {
printf("str2 is less than str1");
} else {
printf("str1 is equal to str2");
}
return(0);
}
UNIT-4
Multiple Choice Questions:
void show()
{
printf("CURRENCY ");
}
A) CURRENCY BANK
B) BANK CURRENCY
C) BANK
D) Compiler error
int show()
{
return 10;
}
A) PISTA COUNT=
B) PISTA COUNT=0
C) PISTA COUNT=10
D) Compiler error
17. What is the default return value of a C function if not specified explicitly.?
A) -1
B) 0
C) 1
D) None of the above
19. A recursive function without If and Else conditions will always lead to.?
A) Finite loop
B) Infinite loop
C) Incorrect result
D) Correct result
20. What is the C keyword that must be used to achieve expected result using Recursion.?
A) printf
B) scanf
C) void
D) return
27. Variables of type auto, static and extern are all stored in .?
A) ROM
B) RAM
C) CPU
D) Compiler
28. Which among the following is a Local Variable.?
A) register
B) auto
C) static
D) extern
Descriptive Questions:
1) Explain with example how to declare, define and call a function in C
Function prototype (Declaration)
A function prototype is simply the declaration of a function that specifies function's
name, parameters and return type. It doesn't contain function body.
A function prototype gives information to the compiler that the function may later be
used in the program.
The function prototype is not needed if the user-defined function is defined before the
main() function.________________________________________
Syntax of function prototype
returnType functionName(type1 argument1, type2 argument2,...);
Function definition
Function definition contains the block of code to perform a specific task.
Syntax of function definition
return type functionName(data-type argument1, data-type argument2, ...)
{ Local Variable Declarations
Execution statement(s)
[return value/expression]
}
Where .
Return data type- type of the return value by the functions.
If nothing is returned to the calling function, then data type is void. Function_name - It
is the user defined function name.
Argument(s) - The argument list contains valid variable name separated by commas. .
return statement- It is used to return value to the calling function. A function can have
multiple return statements . But only one return statement is executed (A function can
return only single value). Execution of return statement causes execution to be
transferred back to calling function.
When a function is called, the control of the program is transferred to the function
definition. And, the compiler starts executing the codes inside the body of a function.
Calling a Function:
A function can be accessed or called by specifying its name, followed by a list of
arguments enclosed in parentheses and separated by commas. If the function call does
not require any arguments, an empty pair of parentheses must follow the function name.
2) Explain with the help of a code example declaring, defining and calling a function in
C
Function prototype (Declaration)
A function prototype is simply the declaration of a function that specifies function's name,
parameters and return type. It doesn't contain function body.
A function prototype gives information to the compiler that the function may later be used
in the program.
The function prototype is not needed if the user-defined function is defined before the
main() function.________________________________________
Syntax of function prototype
returnType functionName(type1 argument1, type2 argument2,...);
Function definition
Function definition contains the block of code to perform a specific task.
Syntax of function definition
return type functionName(data-type argument1, data-type argument2, ...)
{ Local Variable Declarations
Execution statement(s)
[return value/expression]
}
Where .
Return data type- type of the return value by the functions.
If nothing is returned to the calling function, then data type is void. Function_name - It is
the user defined function name.
Argument(s) - The argument list contains valid variable name separated by commas. .
return statement- It is used to return value to the calling function. A function can have
multiple return statements . But only one return statement is executed (A function can
return only single value). Execution of return statement causes execution to be transferred
back to calling function.
When a function is called, the control of the program is transferred to the function
definition. And, the compiler starts executing the codes inside the body of a function.
Calling a Function:
A function can be accessed or called by specifying its name, followed by a list of
arguments enclosed in parentheses and separated by commas. If the function call does not
require any arguments, an empty pair of parentheses must follow the function name.
Example Program 1
# include <stdio.h>
int Add(int x, int y); /*function prototype or function declaration*/
main()
{
int a, b, sum;
printf("enter two number");
scanf("%d %d", &a, &b);
sum=Add(a,b );
printf("sum of %d and %d is %d", a, b, sum);
}/*End of the main*/
int main()
{
int result;
result = greatNum(); // function call
printf("The greater number is: %d", result);
return 0;
}
Example program 7
/*Recursive function program to find the factorial of a number*/
#include<stdio.h>
int fact(int n);
main( )
(
int num;
clrscr( );
printf("\nEnter a number :");
scanf("%d" ,&num);
Suppose the definition fact is called with the value 2, then the value of num in the
function fact is 2, and the condition in the if statement is false, and the function gets
called again with the value num - 1, which is 1. In the second invocation of fact, the
value of num is 1. The condition in the if statement is again false, and a third invocation
of fact results, passing 0 to it. In the third invocation, the value of num 0, and the
condition of fact returns 1 to the second invocation.
Hence, the statement
return (num * fact (num-1);
Multiplies 1 by 1 and causes the number 1 to be returned to the first invocation; where
the value of num was 2. This brings back to the statement
return (num * fact(num-l));
Which is now executing in the first invocation. The return value of the second
invocation, 1 is multiplied by 2 and the value 2 is returned. Two important conditions
must be satisfied by any recursive function:
i) Each time when a function calls itself, it must be closer, in some sense to a
solution.
ii) There must be a decision criterion for stopping the process or computation.
For the function factorial, each time when the function calls itself, its argument is
decremented by one. The stopping criterion is the if statement that checks for the zero
argument.
main ( )
{
---------
---------
actual parameters
function1(a1, a2, a3 am); /* function call*/
¬ ---------
---------
}
Arguments matching between the function call and the called function.
The actual and formal arguments should match in number, type and order. The values
of actual arguments are assigned to the formal arguments on a one to one basis starting
with the first argument as shown in figure. In case, the actual arguments are more than
the formal parameters (m > n), the extra actual arguments are discarded. But if the actual
arguments are less than the fomal arguments, the unmatched formal arguments are
initialized to some garbage values. Any mismatch in data type may also result in passing
of garbage values.
The formal parameters must be valid variable names, but the actual arguments may be
variable names, expressions or constants. The variables used in actual arguments must
be assigned values before the function call is made.
Example
# include <stdio.h>
int Add(int x, int y); /*function prototype or function declaration*/
main()
{
int a, b, sum;
printf("enter two number");
scanf("%d %d", &a, &b);
sum=Add(a,b );
printf("sum of %d and %d is %d", a, b, sum);
}/*End of the main*/
Example program 7
/*Recursive function program to find the factorial of a number*/
#include<stdio.h>
int fact(int n);
main( )
(
int num;
clrscr( );
printf("\nEnter a number :");
scanf("%d" ,&num);
Suppose the definition fact is called with the value 2, then the value of num in the
function fact is 2, and the condition in the if statement is false, and the function gets
called again with the value num - 1, which is 1. In the second invocation of fact, the
value of num is 1. The condition in the if statement is again false, and a third invocation
of fact results, passing 0 to it. In the third invocation, the value of num 0, and the
condition of fact returns 1 to the second invocation.
Hence, the statement
return (num * fact (num-1);
Multiplies 1 by 1 and causes the number 1 to be returned to the first invocation; where
the value of num was 2. This brings back to the statement
return (num * fact(num-l));
Which is now executing in the first invocation. The return value of the second
invocation, 1 is multiplied by 2 and the value 2 is returned. Two important conditions
must be satisfied by any recursive function:
i) Each time when a function calls itself, it must be closer, in some sense to a
solution.
ii) There must be a decision criterion for stopping the process or computation.
For the function factorial, each time when the function calls itself, its argument is
decremented by one. The stopping criterion is the if statement that checks for the zero
argument.
#include<stdio.h>
int fact(int n);
main( )
(
int num;
clrscr( );
printf("\nEnter a number :");
scanf("%d" ,&num);
Auto int x;
auto has been the default class for all the variables we have used so for. The value of the
automatic variables cannot be changed in some other function in the program. So, we can
declare and use the same variable name in different functions in the same program.
Example:
#include<stdio.h>
int Add (int a,int b);
main( )
{
auto int a=10,b=15,c;
clrscr( );
c= a+b;
printf("c= %d", c);
c= Add(a,b);
printf("\nc= %d", c);
}
int Add( int a, int b)
{
int c;
c= a+b;
return c;
}
Example:
# inc1ude<stdio.h>
main( )
{
Because external variables are globally accessible, they provide an attention to function
arguments and return values for communicating data between functions. Any function
may access an external variable by referring to it by name. If a number of variables must
be shared among functions, external variables are more convenient and efficient than
long argument lists. External variables are also useful because of their greater scope and
lifetime. Automatic(local) variables are internal to a function; they come into existence
when the function is entered, and disappeared (destroyed) when it is left. External
variable on the other hand, are permanent, so they retain values from one function
invocation to the next. Thus if functions must share some data, yet neither calls the other,
it is often most convenient if the shared data is kept in external variables rather than
passed in and out via arguments.
One important feature of global variable is that if a function has a local variable, of the
same name as a global variable, the local variable has precedence over the global
variable. Analogously, a variable declared within a block has precedence over an
external variable of the same name.
In order to be able to use an externally declared variable inside' a function, such a
variable may explicitly redeclared inside the function with the extern qualifier, for
example:
extern int X;
Example:
#include <stdio.h>
int Sum;
void Inc( );
main( )
{
int a,b;
clrscr( );
priiltf("Enter two numbers");
scanf("%d %d", &a,&b);
Sum = a+b;
printf("Sum of %d and %d is %d", a,b,Sum);
Inc( );
printf("\nAfter incrementing the value of Sum is %d",Sum);
getch( );
}
void Inc( )
{
Sum ++;
}
14) Write a note on static variable.
Another C storage declaration is static. The keyword static is used to declare variables
which must not lose their storage locations or their values when control leaves the
functions or blocks where in they are defined. In C, static variables retain their values
between function calls. The initial value assigned to a static variable must be a constant,
or an expression involving constants. But static variables are by default initialized to 0,
in contrast to autos.
For example
Static int i;
Initalises variable i to 0
¬Example Program 13
#include<stdio.h>
void Display(void);
main( )
{
int i;
clrscr( );
for ( i=1; i<=4; i++)
Display( );
}
void Display(void)
{
static int x= 0;
x++;
printf("\nx=%d" ,x);
}
output:
x=1
x=2
x=3
x=4
A static variable is initialized only once, when the program is compiled. It is never
initialized again. During the first call to Display( ), x is incremented to I. Because x is
static, this value retains and therefore, the next call adds another I to x giving its value
equal to 2. The value of x becomes 3 when third call is made and 4 when fourth call is
made.
UNIT – 5
Multiple Choice Questions:
A. String
B. Structures
C. Char
D. None of the above
A. -
B. ->
C. .
D. both . and ->
A. Yes
B. No
C. May Be
D. Can't Say
a. string
b. structures
c. char
d. all of the mentioned
B. The compiler will keep track of what type of information is currently stored
C. Only one of the members of union can be assigned a value at particular time
D. Size allocated for Union is the size of its member needing the maximum storage
21. If there is any error while opening a file, fopen will return?
a. Nothing
b. EOF
c. NULL
d. Depends on compiler
22. It is not possible to combine two or more file opening mode in open () method.
a. True
b. False
c. May be True or False
d. Can't Say
23. Which files will get closed through the fclose() in the following program?
void main()
{
FILE *fp, *ft;
fp = fopen("a.txt", "r");
ft = fopen("b.txt", "r");
fclose(fp,ft);
}
a. a, b
b. a
c. b
d. Error in fclose
A. A character string containing the name of the file & the second argument is the mode
B. A character string containing the name of the user & the second argument is the mode
C. A character string containing file pointer & the second argument is the mode
D. None of the mentioned
25. When a C program is started, O.S environment is responsible for opening file and
providing pointer for that file?
A. Standard input
B. Standard output
C. Standard error
D. All of the above
26. A mode which is used to open an existing file for both reading and writing ______
a) ”W”
b) ”W+”
c) ”R+”
d) ”A+”
28. Select a function which is used to read a single character from a file at a time?
a) fscanf()
b) getch()
c) fgetc()
d) fgets()
Descriptive Questions:
1. What is structure? Why it is required?
Arrays provide a means to homogenous data items into a single named unit. But most
of the applications require the grouping together of heterogeneous data items. Such an entity is
called structure and the related data items use in it are referred to as members. Thus a single
structure might contain integer elements, floating point elements and character elements.
Pointers, arrays and other structures can also be included as elements with in a structure.
Give the general format used for defining a structure
DEFINING A STRUCTURE
Every structure must be defined and declared before it appears in a C program .The
general form of structure definition and declaration is as follows,
struct tagname
{
data-type member_1 ;
data-type member_2;
-----------
-----------
data-type member_n;
};
In this declaration struct is a required keyword ,tagname is a name of the structure and
member_1 ,member_2, ..........................................member_n are individual member
declarations. The individual members can be ordinary variables, pointers, arrays or other
structures. The member names with in a particular structure must be distinct from one another
though a member name can be same as the name of a variable defined outside of the structure.
Example
struct Student
{
int Regno;
char Name[20);
int m1,m2,m3,Total_marks;
float Avg;
};
This structure named Student (i.e, the tag is student) contains seven members, an integer
variable Regno ,a 20-element character array (Name [20]). integer variables
m1,m2,m3,Total_marks and a floating type variable Avg.
The general form of declaring structure variable is
struct structure-type variable- list;
The following declaration declares student to be of type Std.
struct Student Std;
union tagnmae
{
Data-type member__1;
Data-type member_2;
-----------¬
Data- type member n;
};
Where union is a required keyword and the tag is optional.
A union may be initialized by value of the type of its first member. If a union has been assigned
a value of certain type then it is not correct to attempt to retrieve from it a value of a different
type.
Example:
union Item
{ int x;
float y;
char z;
} Alpha;
This declares a variable Alpha of type union Item. The union contains three members each with
a different data type. But it is possible to use only one of them at a time. This is due to the fact
that only one location is allocated for a union variable irrespective of size.
In order to gain access to a member of a structure, the dot operator "." is used. That is a structure
member can be accessed by writing.
structure_name. member_name
Where structure_name refers to the name of a structure type variable and member _name refers
to the name of member with in the structure. The period (.) is an operator and it is a member
of the highest precedence group and it groups from left to right.
Example
Example:
#include<stdio.h>
#include<conio.h>
void main( )
{
struct employee {
long int code;
char name[20];
float salary;
};
struct employee emp;
clrscr( );
printf(" Enter employee code:");
scanf("%d" ,&emp.code);
fflush(stdin);
printf("Enter employee name:");
gets(emp.name);
fflush(stdin);
printf("Enter salary:");
scanf("%f' ,&emp.salary);
printf("EMPLOYEE INFORMATION SYSTEM\n\n\n");
printf("CODE NAME SALARY\n");
printf("%d\t %s\t %f\n",emp.code, emp.name, emp.salary);
getch( );
}
union tagnmae
{
Data-type member__1;
Data-type member_2;
-----------
Data- type member n;
};
Where union is a required keyword and the tag is optional.
A union may be initialized by value of the type of its first member. If a union has been
assigned a value of certain type then it is not correct to attempt to retrieve from it a value of a
different type.
Example:
union Item
{ int x;
float y;
char z;
} Alpha;
This declares a variable Alpha of type union Item. The union contains three members each with
a different data type. But it is possible to use only one of them at a time. This is due to the fact
that only one location is allocated for a union variable irrespective of size.
struct Stud
{
int Regno;
char Name[20];
int mark 1, mark2, mark3, Total;
float Avg;
};
struct Stud Student[10];
Here Student is an array of 10 elements of type Stud. Thus Student [0] will contain the first set
of values, Student[1] will contain the second set of values and so on.
Example:
#include<stdio.h>
#include<string.h>
struct student
{
int regno;
char name[15], grade[15];
int m1, m2, m3, total;
float avg;
};
main()
{
struct student s[5];
int i, n;
clrscr();
printf("Enter number of students: ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter information about student %d\n",i+1);
printf("Enter regno\n");
scanf("%d",&s[i].regno);
fflush(stdin);
printf("Enter the name ");
gets(s[i].name);
printf("Enter the marks in 3 subjects ");
scanf("%d%d%d",&s[i].m1, &s[i].m2, &s[i].m3);
s[i].total=s[i].m1+s[i].m2+s[i].m3;
s[i].avg=s[i].total/(3.0);
if(s[i].m1>=35&&s[i].m2>=35&&s[i].m3>=35)
{
if(s[i].avg>=70)
strcpy(s[i].grade,"Distinction");
else
if(s[i].avg>=60)
strcpy(s[i].grade,"First class");
else
if(s[i].avg>=50)
strcpy(s[i].grade,"Second class");
else
strcpy(s[i].grade,"Pass class");
}
else
strcpy(s[i].grade,"Fail");
}
printf("-----------------------------------------------------------\n");
printf("regno\tname\tm1\tm2\tm3\ttotal\tavg\tgrade\n");
printf("-----------------------------------------------------------\n");
for(i=0;i<n;i++)
{
printf("%d\t%s\t",s[i].regno, s[i].name);
printf("%d\t%d\t%d\t",s[i].m1, s[i].m2, s[i].m3);
printf("%d\t%0.2f\t%s\n",s[i].total, s[i].avg, s[i].grade);
}
getch();
}
Example
struct date
{int day;
int month;
int year;
};
struct student
{
int Regno;
char Name[20];
struct date DOB
} std;
or
it can also be written as
struct Student
{
int Regno;
char Name[20];
struct date
struct date
{int day;
int month;
int year;
}DOB ;
} ;
If a structure member is itself a structure then a member of the embedded structure can be
accessed by writing
variable. member.submember
Where member refers to the name of the member within the outer structure, and submember
refers to the name of the member within the embedded structure.
In the above example the last member of std is std.DOB which is itself a structure of type
date. To access the year of date of birth, we have to write as
std.DOB.year;
8. Explain with example defining a union, declaring union variable and accessing union
members
The general form of union is
union tagnmae
{
Data-type member__1;
Data-type member_2;
-----------
Data- type member n;
};
Where union is a required keyword and the tag is optional.
A union may be initialized by value of the type of its first member. If a union has been
assigned a value of certain type then it is not correct to attempt to retrieve from it a value of a
different type.
Example:
union Item
{ int x;
float y;
char z;
} Alpha;
This declares a variable Alpha of type union Item. The union contains three members each with
a different data type. But it is possible to use only one of them at a time. This is due to the fact
that only one location is allocated for a union variable irrespective of size.
----z--------
--------------x-----------
----------------------------y----------------------
The compiler allocates a piece of storage that is large enough to hold the largest variable type
in the union. In the declaration above the member (float type) requires 4 bytes which is the
largest among the members. Figures shows how all the three variables share the same address.
To access union members we have to use dot operator .
Example :-
Alpha.x
Alpha.y
Alpha.z
Declaration:
int fprintf(FILE *fp, const char *format, …);fprintf()
function writes string into a file pointed by fp. In a C
program, we write string into a file as below.
fprintf() – To fprintf (fp, “some data”); or
write into a file fprintf (fp, “text %d”, variable_name);
int main( )
{
FILE *fp ;
char data[50];
// opening an existing file
printf( "Opening the file test.c in write mode" ) ;
fp = fopen("test.c", "w") ;
if ( fp == NULL )
{
printf( "Could not open file test.c" ) ;
return 1;
}
printf( "\n Enter some text from keyboard” \
“ to write in the file test.c" ) ;
// getting input from user
while ( strlen ( gets( data ) ) > 0 )
{
// writing in the file
fputs(data, fp) ;
fputs("\n", fp) ;
}
// closing the file
printf("Closing the file test.c") ;
fclose(fp) ;
return 0;
}
# include <stdio.h>
int main( )
{
FILE *fp ;
char data[50] ;
printf( "Opening the file test.c in read mode" ) ;
fp = fopen( "test.c", "r" ) ;
if ( fp == NULL )
{
printf( "Could not open file test.c" ) ;
return 1;
}
printf( "Reading the file test.c" ) ;
while( fgets ( data, 50, fp ) != NULL )
printf( "%s" , data ) ;
printf("Closing the file test.c") ;
fclose(fp) ;
return 0;
}
14. Write a C program for using getc and putc functions wrt files?
#include <stdio.h>
main( )
{
FILE *f1;
char c;
printf("Data Input\ n\ n");
f1 = fopen("INPUT", “w"); /* Open the file INPUT */
while((c=getchar()) != EOF) /* Get a character from keyboard*/
putc(c,f1); /* Write a character to INPUT file */
fclose(f1);
printf("\nData Output\n\n");
f1 = fopen("'NPUT","r"); /*.Reopen the file INPUT */
while((c=getc(f1) != EOF) /* Read a character from INPUT*/
printf("%c",c);
fclose(f1); /* Close the file INPUT
putw(integer_variable ,fp);
integer_variable =getw(fp);
Example:
#include <stdio.h>
main( )
{
FILE *f1, *f2, *f3;
int number, i;
printf(“Contents of DATA file(Input -1 to terminate)\n\n”);
f1 =fopen(“DATA”, “w”);
while(1)
{
scanf(U%d", &number);
if(number = = -1)
break;
putw(number,f1 );
}
fclose(f1 );
f1 = fopen(“DATA”, “r");
f2 = fopen(“ODD", “w");
f3 = fopen(“EVEN", “w");
while((number = getw(f1)).! = EOF)
{
if(number %2 == 0)
putw(number, f3);
else
putw(number, f2);
fclose(f1 );
fclose(f2);
fclose(f3);
f2 = fopen(“ODD",”r");
f3 = fopen(“EVEN", “r");
printf(“\n\nContents of ODD file\n\n");
while((number = getw(f2)) ! = EOF)
printf("%4d", number);
printf("\n\nContents of EVEN file\n\n");
while((number = getw(f3)) ! = EOF)
printfr%4d" number);
fclose(f2);
fClose(f3);
}
This statement would cause the reading of the items in the list from the file specified by fp,
according to the specifications contained in the control string. Example:
fscanf(f2, "%s %d", Item, &quantlty);
Like scanf, fscanf also returns the number of items that are successfully read. When the end of
file is reached, it returns the value EOF.