Upload
others
View
3
Download
0
Embed Size (px)
Citation preview
MCA Semester – I 610001 - Fundamentals of Programming (FOP)
Department of MCA, B. H. Gardi College of Engineering & Technology, Rajkot Page 1
Q-1 what is function? Explain its components and function types in c?
Explain formal parameter and actual parameters?
A function is basically a self – contained block of program statements that
performs a particular task in program.
It is basically a group of statements used to perform a specific task.
Actually the concept of function is basically the concept called sub-program.
Why they are require?
In a program there are some situation where it is required to execute a
series of program statements, repeatedly, n times.
So at that time without writing the same code at as many places in same
program we can write it as a block of program and can execute it whenever it
required in the program.
The above situation can be expressed as follows:
Here figure (I) shows a program not using a function (II) shows program
using one function call many times.
If a program doesn’t uses a function than a program length would be larger
which is difficult for reading and locating an errors.
MCA Semester – I 610001 - Fundamentals of Programming (FOP)
Department of MCA, B. H. Gardi College of Engineering & Technology, Rajkot Page 2
C divides the entire concept of programming to a combination of functions.
C has no procedures, only functions.
A function can be declared in C program using following construct :
Return_type function_name (datatype var1, datatype var2, … , datatype
varN);
{
Executable statement 1 ;
Executable statement 2 ;
Return expr;
}
The above declaration indicates that
1. Function_name : - It is the name of function.
2. Return_type : It is the data type which type value the function can return.
3. Return: It returns the value to the calling function which is of type
Return_type.
Any no. of variables can be passed as its argument when the function is
being called. Also any no. of statements can resides between two
parentheses {}.
� Components of a function :
Components Purpose
Function prototype Declaration Specifies function name, arg. Type and
return value data type.
Function Call Causes the function to execute.
Function Definition The function itself contains the lines of
code that is to be executed.
� Function prototype declaration :
Before a function is used, C must know the parameter types the
function expects to receive and the data type to returns. Therefore a user
defined function should be normally declared before it use to allow the
compiler to perform type checking of its arguments used in function call.
MCA Semester – I 610001 - Fundamentals of Programming (FOP)
Department of MCA, B. H. Gardi College of Engineering & Technology, Rajkot Page 3
• The general form of function prototype declaration :
Return_type function_name (datatype var1, datatype var2, … , datatype
varN);
The above declaration indicates that
1. Function_name : - It is the name of function.
2. Return_type : It is the data type which type value the function can return.
� Function Call :
All functions , within the standard library or user-written, are called from
within the main() function.
The function call statement invokes the function , which means the
program control passes to that of the function. Once the function completes its
task, the program control is passed back to the calling function.
The general form for function call statement :
Function_name(variable1 , variable2, …., variableN);
The above declaration indicates that
1. Variable : It indicates the arguments to be passes to the function.
� Function Definition :
The function definition section defines the collection of statements to be
executed whenever the function is to be called.
It consist of the function header and a function body, which is a block of
code enclosed in parentheses
• The general form of function definition :
return_type function_name (datatype var1 , datatype varN)
{
local variable declaration ;
statements ;
return expr;
}
MCA Semester – I 610001 - Fundamentals of Programming (FOP)
Department of MCA, B. H. Gardi College of Engineering & Technology, Rajkot Page 4
� Formal parameter & Actual Parameter :
A function will carry out its task whenever it accessed from some portion of a
program. Generally a function will process information passed to it from the
calling statement of a program and return a single value.
Information will passes to the function via special identifiers or variables
called arguments or actual arguments and returned with return statement.
A parameter or variable defined in function definition or function
prototype is called a formal parameter.
For example.
MCA Semester – I 610001 - Fundamentals of Programming (FOP)
Department of MCA, B. H. Gardi College of Engineering & Technology, Rajkot Page 5
Question: Explain following Function with Syntax and Example.
(1) strcat ( )
Syntax:
char *strcat(char *dest, const char *src);
The strcat( ) function concatenates a copy of str2 to str1 and terminates
str1 with a null. The null terminator originally ending str1 is overwritten
by the first character of str2.
The strcat( ) function returns str1.
Example:
char *s1=”Good ”,*s2=”Morning”;
strcat(s1,s2);
printf(“%s”,s1);
Output:
Good Morning
(2) strcpy( )
Syntax:
char *strcpy(char *str1, const char *str2);
The strcpy( ) function copies the contents of str2 into str1. str2 must be a
pointer to a null terminated string.
The strcpy( ) function returns a pointer to str1.
Example:
Char *s1=”Good ”,*s2=”Morning”;
strcpy(s1,s2);
printf(“%s”,s1);
Output:
Morning
(3) strcmp( )
Syntax:
int strcmp(const char *str1, const char *str2);
The strcmp( ) function compares two strings and returns an integer based
on the outcome as shown here:
MCA Semester – I 610001 - Fundamentals of Programming (FOP)
Department of MCA, B. H. Gardi College of Engineering & Technology, Rajkot Page 6
Value Meaning
Less than zero str1 is less than str2
Zero str1 is equal to str2
Greater than zero str1 is greater than str2
Example:
char *s1=”Good”,*s2=”Goood”;
If(strcmp(s1,s2) == 0)
{
printf(“String is Equal”);
}
else
{
printf(“String is not Equal”);
}
Output:
String is Equal
(4) strlen( )
Syntax:
size_t strlen(const char *str);
The strlen( ) function returns the length of the null-terminated string
pointed to by str. The null terminator is not counted.
Example
The following code fragment prints 5 on the screen:
printf("%d", strlen("hello"));
(5) getch( )
Syntax:
int getch(void);
getch reads a single character directly from the keyboard, without echoing
to the screen.
getch() return the character read from the keyboard.
Example
MCA Semester – I 610001 - Fundamentals of Programming (FOP)
Department of MCA, B. H. Gardi College of Engineering & Technology, Rajkot Page 7
char ch;
ch=getch();
(6) getche( )
Syntax:
int getche(void);
getche reads a single character from the keyboard and echoes it to the
current text window, using direct video or BIOS.
getche() return the character read from the keyboard.
Example
char ch;
ch=getche();
(7) getchar( )
Syntax:
int getchar(void);
getchar() is implemented in such a way that it buffers input an integer is
passed. So, this is called line buffered input until you have press ENTER.
Return Value:
On success,getchar returns the character read, after converting it to an int
without sign extension.
On error return EOF.
Example
char ch;
ch=getchar();
(8) fseek( )
fseek() Repositions the file pointer of a stream
You can perform random read and write operations using the C I/O system
with the help of fseek( ),which sets the file position indicator.
MCA Semester – I 610001 - Fundamentals of Programming (FOP)
Department of MCA, B. H. Gardi College of Engineering & Technology, Rajkot Page 8
Syntax:
int fseek(FILE *fp, long int numbytes, int origin);
Argument What It Is/Does
*fp File pointer
num_bytes Number of bytes from origin
Origin Origin Meaning Value
SEEK_SET Beginning of file 0
SEEK_CUR Current position 1
SEEK_END End of file 2
fseek( ) function returns zero when successful and a nonzero value if an
error occurs.
Example
FILE *fp;
fp=fopen(“D:/student.txt”);
fseek(*fp,0L,SEEK_SET);
(9) ftell( )
Returns the current file pointer
You can determine the current location of a file using ftell( ).
Syntax:
long int ftell(FILE *fp);
It returns the location of the current position of the file associated with fp.
If a failure occurs, it returns –1.
Example:
FILE *fp;
Fp=fopen(“D:/student.txt”);
int i;
i=ftell(fp);
MCA Semester – I 610001 - Fundamentals of Programming (FOP)
Department of MCA, B. H. Gardi College of Engineering & Technology, Rajkot Page 9
(10) feof( )
Syntax:
int feof(FILE *stream);
The feof( ) function determines whether the end of the file associated with
stream has been reached.
A nonzero value is returned if the file position indicator is at the end of the
file; zero is returned otherwise.
Example
This code fragment shows one way to read to the end of a file:
Assume that fp has been opened for read operations.
while(!feof(fp))
{
getc(fp);
}
(11) fread( )
fread( ) functions allow the reading of blocks of any type of data.
Syntax:
size_t fread(void *buffer, size_t num_bytes, size_t count, FILE *fp);
Argument What It Is/Does
*buffer Points to a block into which data is read
num_bytes Length of each item read, in bytes
Count Number of items read
*fp Specifies file pointer
The fread( ) function returns the number of items read.
(12) fwrite( )
fwrite( ) functions allow the writing of blocks of any type of data.
Syntax:
size_t fwrite(const void *buffer, size_t num_bytes, size_t count, FILE *fp);
Argument What It Is/Does
*buffer Pointer to any object; the data written begins at ptr
MCA Semester – I 610001 - Fundamentals of Programming (FOP)
Department of MCA, B. H. Gardi College of Engineering & Technology, Rajkot Page 10
num_bytes Length of each item of data
count Number of data items to be appended
*fp Specifies file pointer
The fwrite( ) function returns the number of items written.
(13) sizeof( )
Syntax:
sizeof <expression>
sizeof ( <type> )
sizeof is a unary compile-time operator that returns the length, in bytes, of
the variable or parenthesized type specifier that it precedes.
Example:
double f;
printf("%d ", sizeof(f));
printf(''%d", sizeof(int));
MCA Semester – I 610001 - Fundamentals of Programming (FOP)
Department of MCA, B. H. Gardi College of Engineering & Technology, Rajkot Page 11
Question: Explain storage class in c.
Answer:
• In c, the variables are declared by the type of data they can hold.
• The name of variable is associated with a memory location within the
computer where the value assigned to the variable is stored in the form of
bits.
• During the execution of program these variable may be stored in register of
CPU or the primary memory of the computer.
• To indicate where the variable would be stored, how long they would exist,
what would be their region of existence and what its default value, all things
depends on storage class.
• The prototype of storage class specifier is:
<storage_class_specifier> <data_type> <variable_name>;
• C provides four types of storage class.
1. Automatic
2. External
3. Register
4. Static
1. Automatic storage class specifier:
• By, default all variable declared within the body of any function are of any
function are automatic.
• The keyword auto is used in the declaration of a variable to explicitly specify
its storage class.
• Their region of use in limited within the function body and when the
function completes its specific task and
• These variables stored in primary memory of the computer and behave as
local variable of the function.
• The default value held within these variables is garbage.
• Syntax:
auto <data_type> <variable_name>;
• Example:
auto char any_alpha;
auto int any_number;
auto float any_decimal;
MCA Semester – I 610001 - Fundamentals of Programming (FOP)
Department of MCA, B. H. Gardi College of Engineering & Technology, Rajkot Page 12
2. External storage class specifier:
• A program in c, particularly when it is large can be broken up in to
smaller program.
• After compiling these, each program file can be joined together to from
the large program.
• These small programs module that combine together may need some
variables that are used by all of them.
• In c such a provision can be made by specifying these variables
accessible to all the small program modules as an external storage class
variable.
• These variables are global to all small programs that are formed as
separate file.
• The key word declaring such global variable is extern.
• These variables remain as long as the program is in execution.
• These variable stored in primary memory of computer.
• Their default value is Zero.
• Syntax:
extern <data_type> <variable_name>;
• Example:
extern int i ;
3. Register storage class specifier:
• Variable stored in register of CPU are accessed in much lesser time then
those stored in the primary memory.
• To allow the fastest access time for variables the register storage class
specifier is used.
• The keyword for this storage class is register.
• These variables are stored in some register of CPU.
• The default value of this variable is garbage.
• The existence of the register specified variable are restricted within the
region of function or a block where it has been declared and exist as long
as the function or block remains active.
• Syntax:
register <data_type> <variable_name>;
• Example:
register int i;
MCA Semester – I 610001 - Fundamentals of Programming (FOP)
Department of MCA, B. H. Gardi College of Engineering & Technology, Rajkot Page 13
4. Static storage class specifier:
• The use of static storage class specifier makes a variable a permanent
variable within a specified region.
• Two kinds of variable are allowed to be specified as static variable:
1. Local variable.
2. Global variable.
• The default value of static variable is Zero.
• The keyword for this storage class is static.
• The variable is usable with in function or block where it is declared and
preserves its previous value held by it between function calls or between
block re-entries.
• Syntax:
static <data_type> <variable_name>;
• Example:
static int i ;
MCA Semester – I 610001 - Fundamentals of Programming (FOP)
Department of MCA, B. H. Gardi College of Engineering & Technology, Rajkot Page 14
Question: Explain dynamic memory allocation functions.
Answer:
• A dynamic memory allocation uses function to get memory dynamically.
• If functions are used to get memory dynamically and the values returned by
these function are assigned to pointer variables such assignments are known
as dynamically memory allocation.
• Memory assigned during runtime.
• C provide four types of dynamic memory allocation function:
1. malloc()
2. calloc()
3. realloc()
4. free()
1. malloc ():
• malloc function useful to allocate memory dynamically.
• This function requests a contiguous block of memory of the given size in heap.
• malloc() return a pointer to the heap block or NULL if request is not satisfied.
• Syntax:
void * malloc( size_t size);
• The type size_t is essentially an unsigned long that indicates how large a block
the caller would like measured in bytes.
• Because of block pointer returned by malloc () is a void *, a type cast will be
required when storing the void pointer in to regular typed pointer.
• Example:
Int *ip;
Ip=(int *) malloc (sizeof(int));
2. calloc ():
• Calloc () works like malloc () functions.
• But initialize the memory to zero if possible.
• Syntax: void * calloc(size_t count,size_t eltsize);
• This function allocates a block enough to contain an array of count elements.
• Each of element size is eltsize.
• Its content is cleared to zero before calloc returns.
• Example:
int *ip,count;
ip= (int *) calloc (count, sizeof (int));
MCA Semester – I 610001 - Fundamentals of Programming (FOP)
Department of MCA, B. H. Gardi College of Engineering & Technology, Rajkot Page 15
3. realloc():
• realloc() function take an existing heap block and try to reallocate it to a heap
block of given size which may be larger or smaller than the original size of
block.
• This function returns a pointer to the new block or NULL if the reallocation was
unsuccessful.
• realloc() takes care of moving the bytes from the old block to new block.
• Syntax: void * realloc(void *block,size_t size);
• Example:
int *ip;
ip=(int *) realloc (np,200*sizeof(int));
• Memory reallocation has succeeded and np might be set to what is returned.
4. free():
• Free() function takes a pointer to a heap block earlier allocated by malloc ()
and returns that block to the heap block to the heap for reuse.
• After the free() the user should not access any part of the block or assume that
the block is valid memory.
• A block should not feed a second time.
• Syntax:
void free(void * block);
• Example:
int * ip;
ip= (int *) malloc (sizeof(int));
free (ip);
MCA Semester – I 610001 - Fundamentals of Programming (FOP)
Department of MCA, B. H. Gardi College of Engineering & Technology, Rajkot Page 16
Question: What is an array? How it differ from an ordinary variable?
Explain the procedure to initialize one-dimensional and two Dimensional
arrays.
Answer :
An Array is the collection of an element that can share same name
OR
An Array is a derived data type variable that holds multiple elements which has
the same data type.
Difference between Array and ordinary variable :
• A variable is a reference to a single object (often a number, character, or
string of characters). An array is a reference to a contiguous block of
memory in which zero or more individual objects.
• Array is the set of a multiple values where as variable can store single
value at a time.
• The difference between the definition of array and ordinary variable is the,
array is always declared, initialized, and accessed using subscript whereas
ordinary variable do not have any subscript.
• The syntax for ordinary variable definition is data_type v1, v2, ….; And the
syntax for array variable is data_type v1[N1],v2[N2],…; where v1,v2 are
name of variable and N1, N2 are the integer constants indicating the
maximum size of array.
Procedure to initialize one-dimensional:
• We can initialization the element of array in the same way as the ordinary
variable When declaring a regular array of local scope (within a function,
for example), if we do not specify otherwise, its elements will not be
initialized to any value by default, so their content will be undetermined
until we store some value in them. Array are automatically initialized with
their default values, which for all fundamental types this means they are
filled with zeros.
• Declare an array, we have the possibility to assign initial values to each
one of its elements by enclosing the values in braces { }.
For example:
int billy[5] = { 16, 2, 77, 40, 12071 };
• An array index will always start with zero (0) ,in memory it initialize with
the continues memory location as given below.
MCA Semester – I
Department of MCA, B. H. Gardi College of Engineering & Technology, Rajkot
This declaration would have created an array like this:
• The amount of values between
number of elements that we declare for the array between square brackets
[ ]. For example, in the example of array
elements and in the list of initial values within braces
5 values, one for each element.
• After this declaration, array
initialization values.
Procedure to initialize 2
• Like the one-dimensional array two
by following their declaration with a list of initial enclosed in branch.
int table[2][3]={0,0,0,1,1,1};
• Two dimensional array can we initializing with the row and column in
first dimension total no of row and second dimensio
column
• Initializes the element of the first row to zero and the second row to 1
then initialization is done row by row. an above statement can be
equivalently written as
int table [2][3]={
OR
int table [2][3]={{0,0,0} {1,1,1}};
Initialization in the memory of two
610001 - Fundamentals of Programming (FOP)
Department of MCA, B. H. Gardi College of Engineering & Technology, Rajkot
This declaration would have created an array like this:
The amount of values between braces { } must not be larger than the
number of elements that we declare for the array between square brackets
. For example, in the example of array arr we have declared that it has 5
elements and in the list of initial values within braces { } we hav
values, one for each element.
After this declaration, array arr would be 5 ints l, since we have provided 5
initialization values.
Procedure to initialize 2-dimensional:
dimensional array two- dimensional array may be initialize
by following their declaration with a list of initial enclosed in branch.
nt table[2][3]={0,0,0,1,1,1};
Two dimensional array can we initializing with the row and column in
first dimension total no of row and second dimension total number of
Initializes the element of the first row to zero and the second row to 1
then initialization is done row by row. an above statement can be
lently written as
nt table [2][3]={
{0,0,0}
{1,1,1}
};
OR
nt table [2][3]={{0,0,0} {1,1,1}};
Initialization in the memory of two-dimension array:
Fundamentals of Programming (FOP)
Department of MCA, B. H. Gardi College of Engineering & Technology, Rajkot Page 17
must not be larger than the
number of elements that we declare for the array between square brackets
we have declared that it has 5
we have specified
would be 5 ints l, since we have provided 5
dimensional array may be initialized
by following their declaration with a list of initial enclosed in branch.
Two dimensional array can we initializing with the row and column in
n total number of
Initializes the element of the first row to zero and the second row to 1
then initialization is done row by row. an above statement can be
MCA Semester – I 610001 - Fundamentals of Programming (FOP)
Department of MCA, B. H. Gardi College of Engineering & Technology, Rajkot Page 18
• Initialization in the memory of two-dimension array in the continues
memory allocation as under
MCA Semester – I 610001 - Fundamentals of Programming (FOP)
Department of MCA, B. H. Gardi College of Engineering & Technology, Rajkot Page 19
Question: Explain Bit-Field in Brief.
• There are mainly two ways of manipulating the bits in C.
1. Bit wise operators
2. Bit Fields
• One of the ways consist of using bitwise operators. The other way consist
of using bitfield in which the definition and the access method are based
on structure.
The general format for declaring bit-fields using a structure is as
follows:
Struct bitfield_name
{
Unsigned int member1 : bit_width1 ;
Unsigned int member2 : bit_width2;
…..
Unsigned int memberN : bit_widthN;
}variable1,variable2,…,variable;
In above construct, the declaration of variable is optional. We can
individually create the variables for the structure by:
struct bitfield_name Variable1, Variable 2, …. , VariableN;
In above structure of bit field each bitfield , for example , ‘unsigned int
member 1 : bit_width1’, is an integer that has a specified bit width.
By this technique the exaxt number of bits required can be specified. So a
whole world is not required to hold a field.
MCA Semester – I 610001 - Fundamentals of Programming (FOP)
Department of MCA, B. H. Gardi College of Engineering & Technology, Rajkot Page 20
These will result in saving bits within a word rather than the whole words
to be considered. The use of bitfields may save some memory against the
variables which can have either 1 or 0 characters.
This idea directly motivates the consept of packed fields and operation on
individual bits.
For Ex., consider the following bit field structure :
Struct test
{
Unsigned tx : 2 ;
Unsigned rx : 2 ;
Unsigned chk_sum : 3 ;
Unsigned p : 1 ;
}status_byte;
These construct declares a structure that has
1. A variable name , status_byte , containing four unsigned bitfields.
2. The number following the colon is the field width. Field variables may be
assigned values. The value assigned to a field must not be greater than its
maximum storable value.
3. Individual fields are referenced as though they are structure members.
Like ,
chk_sum = 6 ;
i.e. the above statement will sets the bits in the chk_sum as 110.
However, some extra instructions will be required to perform all
necessary packing and unpacking of bits. So bit-fields are very rarely used
in practice.
MCA Semester – I 610001 - Fundamentals of Programming (FOP)
Department of MCA, B. H. Gardi College of Engineering & Technology, Rajkot Page 21
Question: Explain Bitwise Operator in Brief.
• In C there are two ways of manipulating the data bits
1. By Bitwise Operator
2. Bit - Field
• C has a distinction of supporting some special operators known as Bitwise
Operators for manipulating the data at bit-lewel.
• Bitwise operators except their operands to be an integer values and
treated them as a bit sequence.
• These variables are basically used for reseting the bits or shifting them
right or shifting them left.
• Bit wise operators may not be applied to float or doubles.
The following table shows the commonly available bit wise operators :
Operator Description
& Bitwise AND
| Bitwise OR
^ Bitwise XOR
<< Bitwise Shift Left
>> Bitwise Shift Right
~ Bitwise Negation
1. & - Bitwise AND :-
The bitwise AND compares the corresponding bits of its operands
and produces a 1 when both bits are 1 otherwise produces 0.
Variable Decimal
Equivalent B3 B2 B1 B0
X 12 1 1 0 0
Y 10 1 0 1 0
Z = x & y 8 1 0 0 0
2. | - Bitwise OR :-
The bitwise OR compares the corresponding bits of its operands and
produces a 0 when both bits are 0, and 1 otherwise.
MCA Semester – I 610001 - Fundamentals of Programming (FOP)
Department of MCA, B. H. Gardi College of Engineering & Technology, Rajkot Page 22
Variable Decimal
Equivalent B3 B2 B1 B0
X 12 1 1 0 0
Y 10 1 0 1 0
Z=x|y 14 1 1 1 0
3. ^ - Bitwise XOR :-
The bitwise XOR compares the corresponding bits of its operand
and produces a 0 when both bits are 1 or both bits are 0.
Variable Decimal
Equivalent B3 B2 B1 B0
X 12 1 1 0 0
Y 10 1 0 1 0
Z=x^y 6 0 1 1 0
4. << - Bitwise Shift Left :-
• The bitwise left shift operator takes a bit sequence as their
left operand and a positive integer n as their right operand.
• The output produces a left bit sequence but with shifted to
left side for n bit positions.
It can be initialized like :-
vaiable_name << Number of bit position
To perform (01 1010 0111 << 2 )
Variable Bit’s To Be Shifted Answer
00 1010 0111 2 1010 0111 00
5. >> - Bitwise Shift Right :-
• The bitwise right shift operator takes a bit sequence as their
left operand and a positive integer n as their right operand.
• The output produces a left bit sequence but with shifted to
right side for n bit positions.
It can be initialized like:-
vaiable_name >> Number of bit position
MCA Semester – I 610001 - Fundamentals of Programming (FOP)
Department of MCA, B. H. Gardi College of Engineering & Technology, Rajkot Page 23
To perform (01 1010 0111 >> 2 )
Variable Bit’s To Be Shifted Answer
00 1010 0111 2 00 0010 1001
6. ~ - Bitwise Negation :-
• The bitwise negation operator is a unary operator that
complements the bits in its operand. Like 1 to 0 or 0 to 1.
xi ~xi
0 1
1 0
MCA Semester – I 610001 - Fundamentals of Programming (FOP)
Department of MCA, B. H. Gardi College of Engineering & Technology, Rajkot Page 24
Question: Explain Enumerated Data Type in brief.
• An enumeration data type are data types whose variable can represent any
value that is from its already declared set of values.
• i.e. these are the data types whose value may be any member of
symbolically declared set of values.
• The enumeration data type are created to fix number of values that the
variable can have.
• For ex. We can declare a variable named days that can access only values
between (Sunday,Monday,Tuesday,….,Saturday);
• These symbolically declared members are basically an integer constants.
like 0,1,2,3,..
These symbolic integers are basically used to access any member values.+
THE GENERAL CONSTRUCT TO DECLARE A VARIABLE OF ENUMERATION
TYPE :
enum tag_name { member1, member2, … ,memberN } variable1,
variable2…..variablex;
Here In Above Declaration
1. tag_name : It is the name of variable used to access its members.
2. member1, member2…,memberN : These are the members or elements
for enumeration data type variable.
3. variable1, variable2,… , variablex : These are the variables of
enumeration data type.
• The enum tag_name defines the user-defined data type.
• All the members of enum variable can be accessed with integer constants.
By default , the first member , that is, member1 is given the value
0,member2 to value 1
• Members within the braces {} may be initialized, in which case, the next
member is given a value one more that the preceding member. So, each
member is given the value of the previous member plus 1.
The general form of declaring a variable of enum type is:
enum tag_name Variable1, Variable2,….., VariableN;
The variables can take the values which are its members like,
Variable1 = member1;
MCA Semester – I 610001 - Fundamentals of Programming (FOP)
Department of MCA, B. H. Gardi College of Engineering & Technology, Rajkot Page 25
i.e. here the value represented by member1 is assigned to Variable1.
A typical declaration would be,
enum days { Mon , Tue, Wed, Thu, Fri, Sat, Sun };
void main()
{
enum days start, end;
start=Tue; //Means value of start=1;
end=Sat; //Means value of end=5
}
� Here the above declaration means that the values ‘Mon..Sat’ may be
assigned to a variable of type enum days.
� The above values are 0...6, in this example and these are values must be
associated with any input or output operations.
MCA Semester – I 610001 - Fundamentals of Programming (FOP)
Department of MCA, B. H. Gardi College of Engineering & Technology, Rajkot Page 26
Question: What is Link List? Differentiate Array Vs. Link List. Explain
operations on Singly Linked List.
Definition: - A linked list is an ordered collection of elements, where each
element has at least one pointer for printing to the next element of the list
and at least one value.
Such an element is known as the node of a linked list.
Linked List Array
Memory Allocation :-
No overflow is possible.
� All memory offered for an
application available.
(I.e. at run-time, when new
storage is required.)
� The links need additional
space.
� (No any sequence is
maintained.)
Memory Allocation :-
� All memory must be allocation
before use. So, the memory
space allocated can be
exhausted or left unused.
� (Sequential memory
allocation.)
Accessing items :-
� Only sequential search is
possible.
Accessing items :-
� Random access is possible,
when the order (array index)
number is known.
Expressing order of items :-
� No order is maintain since
nodes may not be stored at
continuous memory
locations.
Expressing order of items :-
� The location in memory
indicates the order number of
item.
Efficiency of operation :-
� Insertion and deletion are
effective regardless (in any
case) of the position they are
inserted in.
Efficiency of operation :-
� Many data movements are
needed in insertions and in
deletion of items.(because of
sequential memory
allocation)
Programming :-
� Needs a bit of expertise.
Programming :-
� Very easy.
� What is meant for singly linked list?
Definition:- A singly linked list is simply a sequence of dynamically allocated
objects, each of which refers to its successor in the list.
� All the operations on Singly Linked List.
� Insert a node :-
Insertion is further classified into three different parts.
MCA Semester – I 610001 - Fundamentals of Programming (FOP)
Department of MCA, B. H. Gardi College of Engineering & Technology, Rajkot Page 27
• After a particular node
(Insert after particular (given/specified) node.)
• After nth node
(Insert at the last position in the list.)
• Before a particular node
(Insert before particular node.)
� Search a particular node
� Remove a particular node
� Sort the nodes
� Destroy (delete all nodes)
MCA Semester – I 610001 - Fundamentals of Programming (FOP)
Department of MCA, B. H. Gardi College of Engineering & Technology, Rajkot Page 28
Question: Define Structure. What are the difference between Structure
and Union? Explain the concept of Nested Structure with example.
� Structure is a user-defined data type may also be called a derived
data type.
� It can be work with collection of data as separate variables.
� Nesting structure is also possible.
Structure Union
� Every member has its
own memory.
� The keyword used is
struct.
� All members occupy
separate memory
locations; hence different
interpretations of the
same memory location
are not possible.
� Consume (use) more
space compared to union.
� All the members can be
initialized.
� Use sizeof keyword in
structure it returns size
of all the members.
� All members use the same
memory.
� The keyword used is union.
� Different interpretations for the
same memory location are
possible. (memory is shared by
all the members)
� Conservation (saving) of
memory is possible.
� Only first member can be
initialized.
� Use sizeof keyword in union it
returns size of biggest member
in the union.
� Nested structure :-
Definition:- A structure can be placed within another structure. In other
words, structures can contain other structures as member.
� A structure within a structure means nesting of structures.
� In such a case, the dot operators in conjunction with the structure
variables are used to access the members of the innermost as well
as outermost structures.
MCA Semester – I 610001 - Fundamentals of Programming (FOP)
Department of MCA, B. H. Gardi College of Engineering & Technology, Rajkot Page 29
� An example of nesting of structure:-
struct Date
{
int dd, mm, yy;
};
struct Student
{
int rno;
char name[15];
struct Date b_date; //Declaration of structure within structure (Nested)
};
void main()
{
struct Student s1;
// Initialize members of structure
s1.rno = 1;
strcpy(s1.name, "Haresh");
/* Initialize member of nested structure Date */
s1.b_date.dd = 12;
s1.b_date.mm = 4;
s1.b_date.yy = 1989;
// Print members of structure
printf("\nRoll No.: %d", s1.rno);
printf("\nName : %s", s1.name);
/* To print members of nested structure Date */
printf("\nB_Date : %d-%d-%d", s1.b_date.dd, s1.b_date.mm,
s1.b_date.yy);
getch();
}
MCA Semester – I 610001 - Fundamentals of Programming (FOP)
Department of MCA, B. H. Gardi College of Engineering & Technology, Rajkot Page 30
Question: Explain following concept with example
(1) RECURSIVE FUNCTION AND ITS APPLICATION
(2) COMMAND LINE ARGUMENTS
(1) RECURSIVE FUNCTION AND ITS APPLICATION:
Basic Concept of recursion or comparison with looping (JUST FOR
UNDERSTANDING):
1) As we all know that loop (for, while, do..while) is used to execute the code
again and again.
2) We require a condition that stop the execution of loop and execute the next
instruction.
3) For example,
We are going to add first 5 natural no. using for loop basic syntax
would be something like ….
For (i=1;i<=5;i++)
{
Total = Total + i;
}
Let us assume that initially Variable Total is assigned the value 0 first instruction
will add the value 1 to variable total now the value of variable total is 1 .
Next instruction will add value of variable i to total. Now, the value of total is 3
and so on the value of variable i will be added to total until the condition is
satisfy.
Same way as the looping work the recursive function works.
As we require a termination condition in for loop same way we required a
termination condition for the recursive function also.
Let us see an example,
int addno(int n) {
if(n<5)
{
return ( n + addno(n+1));
MCA Semester – I 610001 - Fundamentals of Programming (FOP)
Department of MCA, B. H. Gardi College of Engineering & Technology, Rajkot Page 31
}
}
In the above example will add the first 5 value n. The value of n will be increment
by one (1) every time function calls and terminate the recursive call when the
value of n is greater than 5.
Definition:
A recursive function is one that calls itself directly or indirectly to solve a
smaller version of its task until a final call which does not require a self-
call. OR
A function that calls itself is called the recursive function.
Characteristics of recursion
1) Recursion function requires stopping at any certain condition.
Otherwise, the recursion process will be infinite.
2) Recursion function prepares the stack every time function calls.
Stack would be something like:
Example
Let us see an example of factorial no using recursion …
#include<stdio.h>
long int factorial(int number) /* function prototype */
void main()
{
int i;
printf(“\n Enter the number:”);
scanf(“%d”,&i);
printf(“\n Factorial no:%d”,factorial(i));
MCA Semester – I 610001 - Fundamentals of Programming (FOP)
Department of MCA, B. H. Gardi College of Engineering & Technology, Rajkot Page 32
getch();
}
long int factorial(int number)
{
If(number<0)
{
printf(“\nError- negative argument to factorial”);
exit(1);
}
else if(number==0)
{
return 1;
}
else
{
return (number * factorial(number-1));
}
}
Application of recursion function
1) Recursion function used in constructing graph
2) Recursion function used for the tree like structure also.
For e.g. In our day to day like life we are see many type of MLM Company
Means first you become member and make sub-member under yourself
that type of problem to convert into (technical) we must have to use the
recursion process. Basically this is a tree like structure.
M1
M2 M3 M4
M5 M6 M7
MCA Semester – I 610001 - Fundamentals of Programming (FOP)
Department of MCA, B. H. Gardi College of Engineering & Technology, Rajkot Page 33
(2) COMMAND LINE ARGUMENT:
Why use command line argument?
We are using array in c programming language such like int arr[10]
And allocating value of to array of 10 in an array. The main drawback of the
using array is
1) if we use five array index or assign five value to the given array then the
rest of five element will be unused.
2) We can’t assign more than 10 values to an array of such type.
The command line argument overcome such kind of disadvantages
Basic syntax:
int main(int argc, char *argv[])
The declaration states that :
1) main returns an integer value (used to determine if the program
terminates successfully).
2) argc stands for argument counter and it counts the number of
argument passed by the user argc must be at least 1.
3) argv stands for Argument vector is an array of character type which
hold the argument passed by the user.
Let us see an example of finding max value using command line argument:
#include<stdio.h>
void main(int argc, char *argv[])
{
int I=1,max;
max=atoi(argv[1]);
for(i=1;i<argc;i++)
{
MCA Semester – I 610001 - Fundamentals of Programming (FOP)
Department of MCA, B. H. Gardi College of Engineering & Technology, Rajkot Page 34
If(max<atoi(argv[i]))
{
max = atoi(argv[i]);
}
}
printf(“Max value is:%d”,max);
getch();
}
The above program must be execute using DOS prompt
First argument must be name of the file and rest of the argument will be
NUMBER because we are finding maximum value from an argument.
The atoi function will convert character type to int type. We need to use
this function to convert character argument into int type.
MCA Semester – I 610001 - Fundamentals of Programming (FOP)
Department of MCA, B. H. Gardi College of Engineering & Technology, Rajkot Page 35
Question: What is Preprocessor? Explain it in brief.
� The C preprocessor is used to modify the program according to the
preprocessor directives in the source code.
� A preprocessor directive is statement that gives the preprocessor specific
instructions on how to modify the source code.
� The preprocessor is invoked as the first step of the compilation process.
� It is usually hidden from the programmer because the compiler runs it
automatically.
� It is advantageous to use the preprocessor because it Makes:-
1. Program development easier.
2. Programs easier to read.
3. Modification of programs easier.
4. C code more transportable between different machine architectures.
The Bellow display the preprocessor Directives:-
MCA Semester – I 610001 - Fundamentals of Programming (FOP)
Department of MCA, B. H. Gardi College of Engineering & Technology, Rajkot Page 36
UNCONDITIONAL:-
(1) #define:-
� The #define causes the compiler to go through the program,replacing
every occurrence of macro_name with replacement_string.
� The replacement string stops at the end of the line. No semicolon is used at
the end of the directive.
� The general form for the define directive is
#define marco_name replacement_string
For Example:
#define print printf
void main()
{
print(“Welcom to C world”);
}
(2) #undef:-
� This directive undefines a macro.
� A macro must be undefined before being redefined to a dirrerent value.
� The use of #undef on an undefined identifier is harmless and has no effect.
� #undef takes a single argument, the name of the macro to be undefined.
� The general form of #undef directive is
#undef marcor_name
For example:
#undef print
(3) #include:-
� The first form is used for referring to the standard system header files.
� It searches for a file named file_name in a standard header file library and
insert it at the current location.
� They must be included before the program can make use of the library
function.
MCA Semester – I 610001 - Fundamentals of Programming (FOP)
Department of MCA, B. H. Gardi College of Engineering & Technology, Rajkot Page 37
� The angle brackets,< > indicates the preprocessor to search for the header
file in the standard location for library definitions.
� The second from searches for a file in the current directory.
� This is used where multi file programs are being written ,Certain
information is required at the beginning of each program file.
� it is conventional to gives header files a name that ends in ‘.h’ to
distinguish them from other types of files.
� The general directgive has two general froms
#include <file name>
and
#include “file name”
For example:-
#include<stdio.h>
void main()
{
printf(“Welcome again the c World”);
}
� The C have by default it can provided the stdio.h header file.
(4) #Line:-
� The #line directive is used to change the value of __LINE__ and __FILE__
variable.
� The file name is optional.
� The __FILE__ and the __LINE__ variable represent the current file and line
that is being read.
The general form of the directive:-
#line line_number <file name>
For example:-
#line 20 “program1.c”
� The above example to change the current line number to 20,and current
file to “program1.c”.\
MCA Semester – I 610001 - Fundamentals of Programming (FOP)
Department of MCA, B. H. Gardi College of Engineering & Technology, Rajkot Page 38
(5) #error:-
� The preprocessor #error is used for reporting errors by the preprocessor.
� The general from is
#error error_message
� When the preprocessor encounters this, it output the error_message and
causes the compilation to be aborted.
� Therefore it should be only used for reporting errors that make further
compilation pointless or impossible.
For Example:-
#ifdef LINUX
#error This software requires the LINUX OS.
#endif
(6) #pragma:-
� The #pragma directive allows the programmer the ability to convey to the
compiler to do certain tasks.
� Since the #pragma directive is implementation-specific, uses vary from
compiler to compiler.
CONDITIONAL:-
(1) #if (2) #elfi (3) #else (4) #endif :
� Here #if is a conditional directive of the preprocessor, it has expression
that evaluates to an integer.
� #elif is same as the else_if ladder of c,and else is also used with #if or #elif
directive is required. And #endif is used to delimit the end of statement or
condition.
� Above all the conditional preprocessor is also same as work of the if,else_if
and the endif of constructed of C.
� The general format of this condtional preprocessor is:-
#if <constant_expressions1>
<statement_sequencel1>
#elif <constant_expression2>
<statement_sequences2>
MCA Semester – I 610001 - Fundamentals of Programming (FOP)
Department of MCA, B. H. Gardi College of Engineering & Technology, Rajkot Page 39
#elif<constant_ expression3>
<statement_sequences3>
#else
<statement_sequences>
#endif
For Example:-
#If SYSTEM1.H
#include “system_1.h”
#elif SYSTEM2.H
#include “system_2.h”
#else
#include “system_3.h”
#endif
(5) #ifdef (6) #ifndef:-
� The #ifdef directive executes a statement sequences if the macro_name is
defined.
� if the macro_name is not defined, the #ifndef directive executes a
statement sequences, for both the directives, the end of statement is
delimited by #endif.
� The general form of
#ifdef :- #ifdef macro_name
<statement_sequences>
#endif
#ifndef :- #ifndef macro_name
<statement_exrpression>
#endif
MCA Semester – I 610001 - Fundamentals of Programming (FOP)
Department of MCA, B. H. Gardi College of Engineering & Technology, Rajkot Page 40
Question: Scope and Life time of Variable in C ?
� The period of time during which memory is associated with the identifier
is extent, of the variable, the region of the program over which the
declaration of an identifier is visible is called the scope and identifier.
� The scope relates to the accessibility the period of existence and the
boundary of usage of variables declared in a statement block or a function.
� These features in turn define whether a variable is local or global in
nature.
� The variables declared in a block are accessible and usable within that
block ({}).it means this type of variable is life is only between { }.
� We can define the global variable that mean define the variable global
declaration or above the main () is called global variable In this type of
variable life is whole program.
� The bellow display the scope and life time of variable
void main()
{
int x=3;
printf(“The Outer block:=%d”,x);
{
int x=45;
printf(“The inner block=>%d”,x);
}
printf(“Outer block:=%d”,x);
}
Output:-
The Outer Block=3
The Inner Block=45
The Outer Block=3
Start Outer Block
End of Outer Block
Start Inner Block
End of Inner Block
MCA Semester – I 610001 - Fundamentals of Programming (FOP)
Department of MCA, B. H. Gardi College of Engineering & Technology, Rajkot Page 41
� The above program show that because the variable x has been redeclared
as 45 in the inner block,a local variable gets created in the inner block,this
variable is only accessible and known as the inner block.
MCA Semester – I 610001 - Fundamentals of Programming (FOP)
Department of MCA, B. H. Gardi College of Engineering & Technology, Rajkot Page 42
Question: Explain if and nested if. What is different between nested if and
ternary operator?
o IF
• If statement is known as one way decision handler.
• One way decisions are handled with if statement that either do
something or do nothing at all.
• That decision is depend on “test Expression”.
• That general form is following.
if (test expression)
{
Statement-1;
……….
Statement-n;
}
Figure illustration:
true false
• In the above, figure Test Express is logical condition either it is true or
false
Test Expres
Statement_n
STOP
MCA Semester – I 610001 - Fundamentals of Programming (FOP)
Department of MCA, B. H. Gardi College of Engineering & Technology, Rajkot Page 43
• If the condition is true then the statement available in the if block are
executed.
• Otherwise next operation is executed or program is terminated.
int a=10, b=20;
if (a<b)
{
printf (“A is MINIMUM”);
}
• In the above example, if A is smaller than the B then the “A is
MINIMUM” print on the screen.
• Otherwise program stop that execution.
o Nested if:
• A nested if is an if that is the target of another if or else
• In a nested if, an else statement always refers to the nearest if
statement that is within the same block as the else and that is not
already associated with an else
• The general form of nested…if is following:
if (logical condition)
{
if (logical condition)
{
Outer condition
Inner condition
MCA Semester – I 610001 - Fundamentals of Programming (FOP)
Department of MCA, B. H. Gardi College of Engineering & Technology, Rajkot Page 44
Statements;
}
else
{
Statements;
}
Statements;
}
• If the outer condition is true then after the inner condition execute.
int a=30,b=20,c=40;
if (a>b)
{
if (a>c)
{
printf("A is MAX");
}
else
{
printf("C is MAX");
}
}
else
{
Inner else
MCA Semester – I 610001 - Fundamentals of Programming (FOP)
Department of MCA, B. H. Gardi College of Engineering & Technology, Rajkot Page 45
if(b>c)
{
printf("B is MAX");
}
else
{
printf("C is MAX");
}
}
Different between nested…if and ternary operator
• Nested…if: it one type of technique to selecting true or false execution.
• In that, there is outer block or inner block.
• Ternary Operator: Three operand are used in operation that is
known as ternary operator.
• The main difference between the Nested…if and Ternary Operator
is FLEXIBILITY
� In the Nested if, we must write block wise so that code may
be long.
� Long cannot provides the flexibility because of debugging
or error correction are difficult.
� EX. Show the example of 2.0
� In the other hand, there are only required one statement
to produces the code of example 2.0
� Shown below:
MCA Semester – I 610001 - Fundamentals of Programming (FOP)
Department of MCA, B. H. Gardi College of Engineering & Technology, Rajkot Page 46
int a=60,b=50,c=40;
a>b ?
( a>c ? printf("A is MAX"):printf("C is MAX") ) :
(b>c ? printf ("B is MAX"):printf("C is MAX") );
• In the nested if, there are use two keyword IF and ELSE.
• Other hand in the ternary operator, there are used two operator? and :
• The main advantage of the nested if is two return type can be
different in the if or else part.
• While in the ternary operator return type are same.
MCA Semester – I 610001 - Fundamentals of Programming (FOP)
Department of MCA, B. H. Gardi College of Engineering & Technology, Rajkot Page 47
Question: Explain the Process of Completion. Differentiate Compiler Vs.
Interpreter
Answer: Compiling process consists of two steps:
1) The analysis of the source program.
2) The synthesis of the program in the machine language .
� The analysis phase uses the precise description of the source
programming language.
� A source language is described using lexical rules, syntax rules and
semantic rules.
Fig-(The process compiler)
� Lexical rules specify the valid syntactic element of language.
� Syntax rules specify the way in which syntactic elements are
combination to form the statements of the language.
� Lexical analyzer:- It take successive line of a program and breaks
them into individual lexical item namely, identifier, Operator
delimiter,etc.
MCA Semester – I 610001 - Fundamentals of Programming (FOP)
Department of MCA, B. H. Gardi College of Engineering & Technology, Rajkot Page 48
� And attaches with a symbol table for each identifier and find internal
repetition of each constant.
� The symbol table is used later to allocate memory to each variable.
� Syntax analysis:- It is use expression, declaration, and other
statement are identified by using the result of lexical analysis.
� Semantic analysis:- In this, the syntactic units recognized by the
syntax analyzer are processed.
� An intermediate representation of the final machine language code is
produced.
� The last, code translation is code generation, when optimization to
reduce the length of machine language program is carried out.
� The out of the code generator is a machine level language program for
the specific computer.
� The execution of a program written in high-level language involves the
following steps:
1. Translation
2. Linking
3. Relocation
4. loading
Linker:-
� Linker resolves symbolic references between object program.
� Features of programming language influence the linking requirement of
a program.
� Linking is used in many languages like FORTRAN/COBOL, for give the
reference of variable.
� In c files are transfer separately, so function calls with the reference to
global data require linking.
Relocation:-
� Relocation means abjection of all address dependant locations, such as
address constant, to correspond to the allocation space.
� Relocation is used moving program to one area to another area.
Loader:-
� Loading means physically placing the instructions and data into main
memory.
MCA Semester – I 610001 - Fundamentals of Programming (FOP)
Department of MCA, B. H. Gardi College of Engineering & Technology, Rajkot Page 49
� A loader is a system program that accept object program and prepares
them for execution and initiates.
Function of loader:-
� Assignment of load-time storage area to the program.
� Loading of program into assigned area.
� Relocation of program to execute properly from its load
time storage area.
� Linking of programs with one another.
Difference between a compiler and an Interpreter
COMPILER INTERPRETER
Scans the entire program before
translating it into machine code.
Translates and executes the program
line by line.
Converts the entire program to
machine code and only when all the
syntax errors Removed do execution
take place.
Each time the program is executed;
every line is checked for syntax error
and then converted into the equivalent
machine code.
Slow in debugging. Good for fast debugging.
Execution time is less. Execution time is more.
MCA Semester – I 610001 - Fundamentals of Programming (FOP)
Department of MCA, B. H. Gardi College of Engineering & Technology, Rajkot Page 50
Question: Explain Ternary (Conditional) Operator in Brief.
• The conditional operator ternary operator has three expressions. It has the
general form
expression1 ? expression2 : expression3
• First, expression1 is evaluated; it is treated as a logical condition. If the
result is non-zero, then expression2 is evaluated and its value is the final
results. Otherwise, expression3 is evaluated and its value is the final result.
For example:
int M=1,N=2,Min;
Min = ( M<N ? M : N ); //Min is assigned a value 1
• In the above example,because M is less than N,M<N expression evaluates
to true,therefore,Min is assigned the value M,i.e.,1.
• The same code can also be written using the if-else construct
int M=1,N=2,Min;
if(M<N)
{
Min=M;
}
else
{
Min=N;
}
• Note that out of the second and the third expressions of the conditional
operator, only one is evaluated. This may be significant when one or both
contain side effects, that is, their evaluation causes a change to the value of
a variable.
For example, in
Min= (M<N ? M++ : N++ );
MCA Semester – I 610001 - Fundamentals of Programming (FOP)
Department of MCA, B. H. Gardi College of Engineering & Technology, Rajkot Page 51
• M is incremented because M is less than N and N is not incremented and
not changed.
• Because a conditional operation is itself an expression,it may be used as an
operand of another conditional operation,that is,expression may be
nested.
int M=1,N=2,P=3,Min;
Min=(M<N?(M<P?M:P):(N<P?N:P));
• First of all M<N condition is checked if it is evaluated to true then M<P
condition is checked if it is evaluated true then M is printed otherwise N is
printed.
• If M<N condition is evaluated to false then N<P condition is checked if it is
evaluated to true the N is printed otherwise P is printed.
• The conditional expression is not only a shorthand; It may also result in
less object code than would be generated by other alternative means, e.g.,
by use of one or more if statements.
MCA Semester – I 610001 - Fundamentals of Programming (FOP)
Department of MCA, B. H. Gardi College of Engineering & Technology, Rajkot Page 52
Question: Explain different File Opening Modes used with fopen ().
What is fopen () :-
• fopen() is used for opening a file.
• The fopen ( ) function opens a stream for use and links a file with that stream.
• Then it returns the file pointer associated with that file.
• Syntes :-
• FILE *fopen(const char *filename, const char *mode);
• Example:-
FILE *fp;
fp = fopen("test", "w");
The modes used with fopen() :-
Modes Meaning
R Open a text file for reading
W Create a text file for writing
A Append to a text file
Rb Open a binary file for reading
wb Create a binary file for writing
ab Append to a binary file
r+ Open a text file for read/write
w+ Create a text file for read/write
a+ Append or create a text file for read/write
r+b Open a binary file for read/write
w+b Create a binary file for read/write
a+b Append or create a binary file for read/write
MCA Semester – I 610001 - Fundamentals of Programming (FOP)
Department of MCA, B. H. Gardi College of Engineering & Technology, Rajkot Page 53
Question: Write a short note on Type of Stream in C.
What is Stream:-
“The Stream is a common, logical interface to the various devices that
comprise the computer.”
Stream:-
• A very important concept in C is the stream.
• In its most common form, a stream is a logical interface to a file.
• As defined by C, the term ‘file’ can refer to a disk file, the screen, the
keyboard, a port, a file on tape, and so on.
• Although files differ in form and capabilities, all streams are the same.
• The Stream provides a consistent interface to the programmer.
• Stream I/O uses some temporary storage area, called buffer, for reading
from or writing data to a file.
• This is illustrated in following figure.
• The C file system is designed to work with a wide variety of devices,
including terminals, disk drives, and tape drives.
• Even though each device is very different, the buffered file system
transforms each into a logical device called a stream. All streams behave
similarly.
MCA Semester – I 610001 - Fundamentals of Programming (FOP)
Department of MCA, B. H. Gardi College of Engineering & Technology, Rajkot Page 54
• Because streams are largely device independent, the same function that
can write to a disk file can also write to another type of device, such as the
console.
• There are two types of streams: text and binary.
Text Streams:-
• A Text stream is a sequence of characters.
• Standard C states that a text stream is organized into lines terminated by a
newline character.
• However, the newline character is optional on the last line.
• In a text stream, certain character translations may occur as required by
the host environment.
• For example, a newline may be converted to a carriage return/linefeed
pair.
• Therefore, there may not be a one-to-one relationship between the
characters that are written (or read) and those stored on the external
device.
• Also, because of possible translations, the number of characters written
(or read) may not be the same as the number that is stored on the external
device.
Binary Streams:-
• A Binary stream is a sequence of bytes that has a one-to-one
correspondence to the bytes in the external device— that is, no character
translations occur.
• Also, the number of bytes written (or read) is the same as the number on
the external device.
• However, an implementation— defined number of null bytes may be
appended to a binary stream.
• These null bytes might be used to pad the information so that it fills a
sector on a disk.
MCA Semester – I 610001 - Fundamentals of Programming (FOP)
Department of MCA, B. H. Gardi College of Engineering & Technology, Rajkot Page 55
Question: Explain concept of (1) Array of Pointer (2) Pointer to Array
(1) Array of Pointer:
• Pointers and Arrays are logically related, but they are not same.
• Array of pointer is a collection of Pointers.
• In general, an array of pointers can be used to point to an array of data
items, with each element of pointer array pointing to an element of the
data array.
• The advantage of an array of pointers is that the pointers can be reordered
in any manner without moving the data items. Because reordering
pointers is relatively fast compared to recording large data items such as
data records or strings.
Declaration Syntax of Array of Pointer:
data_type array_name[SIZE];
Note: - SIZE represents the number of rows.
• An array of pointers can be declared very easily. Like as,
int *p[10];
• This declares an array of 10 pointers, each of which points to an integer.
• The first pointer is called p[0], the second is p[1], and so on up to p[9].
• We could make point to integer variable in memory.
For Example:
int *p[10]; int a=10,b=20,c=30;
p[0] = &a; p[1] = &b; p[2] = &c;
• • •
10 20 30
MCA Semester – I 610001 - Fundamentals of Programming (FOP)
Department of MCA, B. H. Gardi College of Engineering & Technology, Rajkot Page 56
• It can be seen from the diagram that the first pointer p[0] is points to a, the
second pointer is point to b, and so on up to p[9].
• Access value of pointer of array in 1-Dimension array.
printf(“%d”,*p[2]); //get value 30
• But in 2 dimension array assignment of pointer and accessing pointer
value is different.
Assignment pointer in 2-Dimension:
int a[3][3]={{1,2,3},{4,5,6},{7,8,9}}
int *p[3],i,j;
for(i=0;i<3;i++)
{
p[i]=&a[i][0];
}
Accessing value of pointer in 2-Dimension:
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf(“%3d”,*(*(p+i)+j));
}
}
1 2 3
4 5 6
7 8 9
Output
1 2 3
4 5 6
7 8 9
p[0]
p[1]
p[2]
MCA Semester – I 610001 - Fundamentals of Programming (FOP)
Department of MCA, B. H. Gardi College of Engineering & Technology, Rajkot Page 57
(2) Pointers to an Array :
• Suppose we have an array of integer data type, which name is v. We can
declare integer value and make it point to the array as is done normally.
int v[5] = {10,11,12,13};
int *p ; p=&v;
printf(“%d \n”,*p);
V[0]
V[1]
V[2]
V[3]
V[4]
• Using p++, increases the pointer so that it points to the next element of
the array. Now p is point to the v[1].
• Similarly, we can use instructions such as += and -= to refer to different
elements in the array.
V[0]
V[1]
V[2]
V[3]
V[4]
10
11
12
13
14
10
11
12
13
14
p
p
p+=2;
MCA Semester – I 610001 - Fundamentals of Programming (FOP)
Department of MCA, B. H. Gardi College of Engineering & Technology, Rajkot Page 58
V[0]
V[1]
V[2]
V[3]
V[4]
• Reference can be made to the different array element without having to
after the value of p.
V[0]
V[1]
V[2]
V[3]
V[4]
• We have already used *p to refer to the first element of the array, but
*(p+1) refer to the next element after *p, *(p+2) to refer to the one after
that, etc.
• Now it is time to the problem of the two-dimension array. The first
element of a 2-D array of integers is a one-dimensional array of integer.
And a pointer to a 2-D array of integers must be a pointer to that data
type.
• One way of declaring a pointer in 2-D without typedef keyword, it is
pointer to array.
Declaration Syntax of Pointer to an Array:
data_type (*array_name)[SIZE];
SIZE represents the number of columns.
10
11
12
13
14
10
11
12
13
14
p
p--;
*p
*(p-1)
*(p+1)
*(p+2)
*(p+3)
MCA Semester – I 610001 - Fundamentals of Programming (FOP)
Department of MCA, B. H. Gardi College of Engineering & Technology, Rajkot Page 59
Assign value in Pointer in 2-D:
int a[2][3]={{3,4,5},{6,7,8}};
int (*pa)[3];
pa =&a[0];
Accessing value From 2-D using Pointer to Array:
for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
{
printf("%d\t",(*(pa+i))[j]);
}
printf("\n");
}
Output :
3 4 5
6 7 8
MCA Semester – I 610001 - Fundamentals of Programming (FOP)
Department of MCA, B. H. Gardi College of Engineering & Technology, Rajkot Page 60
Question: Explain Escape Sequence:
• Character combinations consisting of a backslash (\) followed by a letter
or by a combination of digits is called "escape sequences”.
• C language supports some special character constants that are used in
output functions.
Example:
The symbol ‘\n’ stands for newline characters.
Backslash Character Constants:
Constant Meaning
‘\n’ New line
‘\t’ Horizontal tab
‘\v’ Vertical tab
‘\?’ Question mark
‘\\’ Backslash
‘\0’ Null
‘\a’ Audible alert
‘\b’ Back space
‘\f’ Form feed
‘\’’ Single quote
‘\’’’ Double quote
‘\r’ Carriage return
• List of above backslash character constants table that each one of them
represents one character, all though they consist of two characters. These
characters combination are known as “escape sequences”.
• Give one example for each.
MCA Semester – I 610001 - Fundamentals of Programming (FOP)
Department of MCA, B. H. Gardi College of Engineering & Technology, Rajkot Page 61
Question: Explain Formatted I/O Statements in C.
• In C language formatted I/O statements is required in a specified format
the two standard library function that are the under
1. printf()
2. Scanf()
(1) Input function printf():
• The printf() function useful for printing captions and numerical results. It
is highly desirable that the outputs are produced in such a way that are
understandable and are in an easy-to-use form
• The general form of printf statements is under :
Syntax:
printf(“control string “,arg1,arg2,…..,argn);
(a) Control String:
• Control string consists of three types of items
1. Character that will be printed on the screen as they appear.
2. Format specifications that define the output format for display of each
item, The output format specifier are preceded by a % sign and tell
printf( ) what type of data is to be print, Format specifiers for printf()
are under.
Conv.
code
variable type Display
%c char Single character
%d(%i) int Singed integer
%E(%e) float or double Exponential format
%f float or double Signed decimal
%g(%G) float or double Use %f or %e, whichever is sorter
%o int Unsigned octal value
%p pointer Address stored in pointer
%s Array of char Sequence of characters
%u int Unsigned decimal integer
%x(%X) int Unsigned hex value
%% None No corresponding argument is converted,
prints only a %
%n Pointer to int The corresponding arguments is a pointer to
an integer into which the number of character
displayed is placed
MCA Semester – I 610001 - Fundamentals of Programming (FOP)
Department of MCA, B. H. Gardi College of Engineering & Technology, Rajkot Page 62
3. Escape sequence character
Such as: \n,\t,\b…etc
(b) Arguments:
• The arguments arg1,arg2,arg3…argn are the variables whose values are
formatted and printed according to the specification of the control string.
(2) Input function scanf():
• scanf( ) is the general -purpose console input routine. It can read all the
built-in data types and automatically convert numbers into the proper
internal format. It is much like the reverse of printf( ).
• The general form of scanf() statements is under :
Syntax:
scanf(“control string“,variable1_address, ,…..,variableN_address);
• The scanf( ) function returns the number of data items successfully
assigned a value. If an erroroccurs, scanf( ) returns EOF. The
control_string determines how values are read into the variables pointed
to in the argument list.
• The control string consists of three classifications of characters:
(1) Format specifier:
• Format specifications that define the get format for display of
each item for printf(), The input format specifier are preceded by
a % sign and tell scanf( ) The format specifier are matched, in
order from left to right.
Conversion
code
Meaning
%c Read Single character
%d(%i) Read s Singed integer
%E(%e) Read floating point number
%f Read a floating point number
%g(%G) Read a floating point number
%o Read octal number
%p Read a pointer
%s Read a string
%u Read an Unsigned decimal integer
MCA Semester – I 610001 - Fundamentals of Programming (FOP)
Department of MCA, B. H. Gardi College of Engineering & Technology, Rajkot Page 63
%x(%X) Read a Unsigned hex value
%% Read a percent sign
%[] Scans for a set of characters.
%n Receives an integer value equal to
the number of characters read.
• White-space characters
• Non-white-space characters
(2)Variable address
• The variable_address1, variable_address2,…, variable_addressN
that pass the address of the variable using the ‘&’ operator.
Example:
#include <stdio.h>
void main()
{
int i, j;
printf(“enter value of I and J “);
scanf("%o%x", &i, &j);
printf(''%o %x", i, j);
getch();
}
MCA Semester – I 610001 - Fundamentals of Programming (FOP)
Department of MCA, B. H. Gardi College of Engineering & Technology, Rajkot Page 64
Differences
Break Continue
It helps to make an earlier exit from the
Block where it appears.
It can be used in all control statements
Including switch construct.
Control passes to the next statement.
It breaks the loop.
It helps in avoiding the remaining
statements in a current iteration
It can be used only in loop constructs.
Control passes at the beginning of the loop
It does not break the loop.
Call/ Pass by Value Call / Pass by Reference
• Pass by value return the value to
the main function
• Pass by reference return the address
to the main function.
• Change in the subfunction does
not reflect to the main function
• Change in the subfunction reflects to
the main function.
• It can return only one value of
variable.
• It can return more than one value of
variables because it return reference
• In Function call value is passed. • In Function call address is passed.
• C and Java restrict themselves to
Call by Value.
• C++ and Pascal let you declare that a
parameter is a reference.
• Value of actual parameter is used
to initialize the formal
parameter.
• Formal parameter refers to the same
memory cell for the actual
parameter.
do…while while
while is entry control loop
First it executes body of the loop then
it will check the condition.
If condition is false although body loop
will execute one time.
It will execute one more time then while
loop.
Do while is exit control loop
First it checks the condition then execute
body of the loop
If condition will be false then it will came
out of the loop.
It will execute one time less the do while
loop.
MCA Semester – I 610001 - Fundamentals of Programming (FOP)
Department of MCA, B. H. Gardi College of Engineering & Technology, Rajkot Page 65
Explain Operator precedence and operator Associativity in brief.
Operator precedence:
� When more than one operator are present in an expression, operator
precedence decides which operator is evaluate first.
� Operator precedence is known as operator priority
Operator Associativity:
� When more than one operator with same precedence are present
,operator associativity operator is evaluated left to right or visa versa
Table Operator precedence And operator Associativity
operator Associativity precedence
( ) [] -> . ++(postfix) --(postfix) L to R 1
++(prefix) --(prefix) ! ~ (1’s compli.) sizeof(type)
+(unary)
-(unary) &(address) * (pointer reference)
R to L
2
* / % L to R 3
+ - L to R 4
<< >> L to R 5
< <= > >= L to R 6
== != L to R 7
& L to R 8
^ L to R 9
| L to R 10
&& L to R 11
MCA Semester – I 610001 - Fundamentals of Programming (FOP)
Department of MCA, B. H. Gardi College of Engineering & Technology, Rajkot Page 66
Example of precedence of operator
void main()
{
int a;
int b=4;
int c=8;
int d=2;
int e=4;
int f=2;
a=b + c / d + e * f; /* =4+8/2+4*2 =4+4+4*2 =4+4+8 =16 */
printf(“\n a=%d”,a);
a=( b +c ) / d + e * f ; /*=(4+8)/2+4*2 =12/2+4*2 = 6+8 =14 */
printf(“\na=%d”,a);
}
Output
a=16
a=14
|| L to R 12
? : R to L 13
= += -= *= /= %= >>= <<= &= ^= |= R to L 14
,(comma operator) L to R 15
MCA Semester – I 610001 - Fundamentals of Programming (FOP)
Department of MCA, B. H. Gardi College of Engineering & Technology, Rajkot Page 67
Question: What is ALGORITHM? Explain feature of it. List different way of
stating algorithm.
• An algorithm is an “effective” procedure for solving a problem in a finite
number of steps.
THE KEY FEATURES OF ALGORITHM:-
There are three key features of an algorithm.
(1) Sequence (also known as process)
(2) Decision. (also known as selection)
(3) Repetition (also known as iteration or looping)
(1) Sequence:-
• Sequence means that each steps or process in the algorithm is expressed in
the specified order, otherwise, it will fail.
(2) Decision:-
• In algorithm the outcomes of a decision is either true or false; there is no
state in between.
• The decision can also be stated as:
If proposition
Then proceses1
else
Process2
(3) Repetition:-
• Repetition can be implemented using construct like the repeat loop,
while loop, and if..then…goto..loop.
• The repeat loop is used to iterate or repeat a process or sequence of
processes until some condition becomes true.
• It has general form
MCA Semester – I 610001 - Fundamentals of Programming (FOP)
Department of MCA, B. H. Gardi College of Engineering & Technology, Rajkot Page 68
REPEATE
PROCESS1
PROCESS2
…
…
PROCESSN
until proposition.
• The repeated loop does some processing before testing the state of the
proposition.
DIFFERENT TYPES OF STATING ALGORITHM:-
(1) Step –form
(2) Pseudo-code
(3) Flowchart
(4) Nassi-Schneiderman
MCA Semester – I 610001 - Fundamentals of Programming (FOP)
Department of MCA, B. H. Gardi College of Engineering & Technology, Rajkot Page 69
Question: What is Flowchart? Explain in brief.
Flowchart:-
• It is a program designed tool which is used before writing the actual
program.
• Flowcharts are generally developed in the early stages of formulating
computer solution.
Symbols Used in Flowchart:-
MCA Semester – I 610001 - Fundamentals of Programming (FOP)
Department of MCA, B. H. Gardi College of Engineering & Technology, Rajkot Page 70
Advantage of Using Flowchart:-
• Communication:-
Flow charts are a better ways of communicating the logic of a
system to all concerned.
• Effective Analysis:-
With the help of flow charts, problems can be analyzed more
effectively.
• Proper Documentation:-
Program flowcharts harts serve as a good program documentation
needed for various purposes.
• Effective Coding:-
Flowcharts acts as a guide or blueprint during the systems analysis
and program development phase.
• Proper debugging:-
Flowcharts help in the debugging process.
• Effective program maintenance:-
The maintenance of an operating program becomes easy with the
help of a flowchart.
Limitations of using flowchart:-
• Complex logic sometimes, the program logic is quit complicated. In
such a case, a flowchart becomes complex and clumsy.
• Alternation and modifications if alteration are required, the flowchart
may need to be redrawn completely.
• Reproduction Since the flowchart symbols cannot be typed in, the
reproduction of a flowchart becomes a problem.
• The essentials of what has to be done can easily be lost into the
technical details of how it is to be done.