Question_and_answers_-_Programming_in_C-1
Question_and_answers_-_Programming_in_C-1
SUBJECT: -PROGRAMMING IN C
Types of C constant:
1. Integer constants
2. Real or Floating point constants
3. Octal & Hexadecimal constants
4. Character constants
5. String constants
6. Backslash character constants
Rules for constructing C constant:
1. Integer Constants in C:
2. Real constants in C:
Backslash_character Meaning
\b Backspace
\f Form feed
\n New line
\r Carriage return
\t Horizontal tab
\” Double quote
\’ Single quote
\\ Backslash
\v Vertical tab
\a ALERT or bell
\? Question mark
\N Octal constant (N is an octal constant)
\XN Hexadecimal constant (N – hex.dcml cnst)
ANS
C variable is a named location in a memory where a program can manipulate the data. This
location is used to hold the value of the variable.
The value of the C variable may get change in the program.
C variable might be belonging to any of the data type like int, float, char etc.
ANS:
ANS:
C data types are defined as the data storage format that a variable can store a data to perform a
specific operation.
Data types are used to define a variable before to use in a program.
1. float
2. double
1. float:
2. double:
Double data type is also same as float data type which allows up-to 10 digits after decimal.
The range for double data type is from 1E–37 to 1E+37.
ANS:
Types of C operators:
1. Arithmetic operators
2. Assignment operators
3. Relational operators
4. Logical operators
5. Bit wise operators
6. Conditional operators (ternary operators)
7. Increment/decrement operators
8. Special operators
o Click on each operators name below for detail description and example programs.
1.Arithmetic Operators in C:
Assignment operators in C:
o In C programs, values for the variables are assigned using assignment operators.
o For example, if the value “10″ is to be assigned for the variable “sum”, it can be
assigned as “sum = 10;”
o Other assignment operators in C language are given below.
o In this program, values from 0 – 9 are summed up and total “45″ is displayed as
output.
o Assignment operators such as “=” and “+=” are used in this program to assign the
values and to sum up the values.
Relational operators in C:
o Relational operators are used to find the relation between two variables. i.e. to
compare the values of two variables in a C program.
S.no Operators Example Description
1 > x>y x is greater than y
2 < x<y x is less than y
3 >= x >= y x is greater than or equal to y
4 <= x <= y x is less than or equal to y
5 == x == y x is equal to y
6 != x != y x is not equal to y
Logical operators in C:
o These operators are used to perform logical operations on the given expressions.
o There are 3 logical operators in C language. They are, logical AND (&&), logical OR
(||) and logical NOT (!).
o These operators are used to perform bit operations. Decimal values are converted
into BINARY values which are the sequence of bits and bit wise operators work on
these bits.
o Bit wise operators in C language are & (bitwise AND), | (bitwise OR), ~ (bitwise OR),
^ (XOR), << (left shift) and >> (right shift).
o Conditional operators return one value if condition is true and returns another value is
condition is false.
o This operator is also called as ternary operator.
Increment Decrement
Increment operators are used to increase the value of the variable by one and decrement
operators are used to decrease the value of the variable by one in C programs.
Syntax:
Increment operator : ++var_name; (or) var_name++;
Decrement operator : – - var_name; (or) var_name – -;
…
Example:
Increment operator : ++ i ; i ++ ;
Decrement operator: – - i ; i – - ;
ANS
Features of ‘C’ language:-
C is a general purpose, structured programming language. C programming is widely used in
computer Technology.
Low Level Features:
C programming provides Low level features that are generally provided by the Lower
level languages. C is closely related to Lower level Language such as “Assembly
Language”.
It is easier to write assembly codes in C programming.
Portability:
C Programs are portable i.e. they can run on any Compiler with little or No
Modification.
Compiler and Preprocessor make it possible for C Programs to run it on Different
Platforms.
Powerful:
Provides wide verity of “Data Types”
Provides wide verity of “Functions”
Provides useful Control and Loop Control Statements
Bit Manipulation
C Programs can be manipulated using bits. We can perform different operations at bit
level.
It provides wide verity of bit manipulation Operators. We have bitwise operators to
manage Data at bit level.
High Level Features:
It is more User friendly as compare to Previous Languages. Previous languages such
as BCPL, Pascal and other programming languages never provide such great features
to manage data.
Previous languages have their Pros and Cons but C Programming collected all useful
features of previous languages thus C become more effective Language.
Modular Programming:
Modular programming is a software design technique that increases the extent to
which software is composed of separate parts, called Modules.
C Program consist of different modules that are integrated together to form complete
program.
Efficient Use of Pointers:
Pointers have direct access to memory.
C supports efficient use of pointer.
More Efficient:
C Programming language is more efficient to Other languages.
Q.8 Discuss Precedence order and associativity of operators.
If more than one operators are involved in an expression then, C language has predefined rule of
priority of operators. This rule of priority of operators is called operator precedence.
Associativity of operators
Associativity indicates in which order two operators of same precedence(priority) executes. Let us
suppose an expression:
a==
(a==b)!
Here, operators == and != have same precedence. The associativity of both == and != is left to right,
i.e, the expression in left is executed first and execution take pale towards right.
Thus, a==b!=c equivalent to :
The table below shows all the operators in C with precedence and associativity.
Note: Precedence of operators decreases from top to bottom in the given table.
1. Documentation section
2. Link Section
3. Definition Section
4. Global declaration section
5. Function prototype declaration section
6. Main function
7. User defined function definition section
oSectionsDescription
1Documentation section:
We can give comments about the program, creation or modified date, author name etc
in this section. The characters or words or anything which are given between “/*” and
“*/”, won’t be considered by C compiler for compilation process.These will be
ignored by C compiler during compilation.
Example : /* comment line1 comment line2 comment 3 */
2.Link Section
Header files that are required to execute a C program are included in this section
3.Definition Section
In this section, variables are defined and values are set to these variables.
Global variables are defined in this section. When a variable is to be used throughout
the program, can be defined in this section.
Function prototype gives many information about a function like return type,
parameter names used inside the function.
6.Main function
Every C program is started from main function and this function contains two major
sections called declaration section and executable section.
User can define their own functions in this section which perform particular task as
per the user requirement.
In addition, these data types have some modifiers preceding them. The use of these modifiers changes
the meaning of the base type.
The memory in the computer is organized in terms of units called bytes. One byte consists of 8 bits
and bit is a smallest unit of memory.
An integer data type takes 2 Bytes of Memory and we are aware that the Salary of any of the
employee can not be “Negative”. We are using “2 Bytes” to store the memory of an Employee and
we can easily save 1 Byte over there by removing the “Signed Part” in the integer. This positive value
can easily be stored in “1 Bye Int” This leads us to the user of Data Type Modifiers.
All data types are “signed” by default. Signed Data Modifier implies that the data type variable can
store positive values as well as negative values.
For example, if we need to declare a variable to store temperature, it can be negative as well as
positive.
For example, if we need to declare a variable to store the salary of an employee as explained above,
we will use “Unsigned” Data Qualifier here.
unsigned int salary;
Sometimes while coding a program, we need to increase the Storage Capacity of a variable so that it
can store values higher than its maximum limit which is there as default. In such situations or
programs, we need to make use of the “long” data type qualifier. “long” type modifier doubles the
“length” of the data type when used along with it.
For example, if we need to store the “annual turnover” of a company in a variable, we will make us
of this type qualifier.
A “short” type modifier does just the opposite of “long”. If one is not expecting to see high range
values in a program and the values are both positive & negative.
For example, if we need to store the “age” of a student in a variable, we will make use of this type
qualifier as we are aware that this value is not going to be very high.
We can apply the above mentioned modifiers to integer (int) and character (char) base types.
* We can use all the above mentioned Type Modifiers for int data type in C Language
* Short int and long int are also termed as short and long respectively.
* float
* double
* long double
Double is same as long float. Float type occupies 4 bytes of memory. Type double occupies 8 bytes.
Long double occupies 10 bytes. The exception to this is long double, which modifies the size of the
double data type to 10 bytes. Please note that in some compilers this has no effect.
Note: We may use long modifier with double data type but it cannot be used with float, i.e. long
double is allowed but long float is not allowed because long float is equal to double.
Q12explain printf() in c
printf() function:
o printf() function is used to print the “character, string, float, integer, octal and
hexadecimal values” onto the output screen.
o We use printf() function with %d format specifier to display the value of an integer
variable.
o Similarly %c is used to display character, %f for float variable, %s for string
variable, %lf for double and %x for hexadecimal variable.
o To generate a newline,we use “\n” in C printf() statement.
Scanf():
To read an int, supply scanf with a format string containing the conversion specification %d,
and include an int variable preceded by an ampersand (&) as the second parameter.
To read a double, supply scanf with a format string containing the conversion
specification %lf (that's a lower case L, not a one), and include a doublevariable preceded by
an ampersand as the second parameter.
To read more than one number, include more than one conversion specification and more than
one extra parameter.
Importance of the Ampersand symbol (&)
It is important to put the ampersand in front of the variables that appear as parameters to scanf, and it
is easy to forget to do this. Remove the ampersand and compile and run the program. The program
will crash before it runs to completion. Put the ampersand back. If you see this behavior in the future,
check your scanfstatements.
Ans:
Control statements enable us to specify the flow of program control; ie, the order in which the
instructions in a program must be executed. They make it possible to make decisions, to perform
tasks repeatedly or to jump from one section of code to another.
There are four types of control statements in C:
In decision control statements (C if else and nested if), group of statements are executed when
condition is true. If condition is false, then else part statements are executed.
There are 3 types of decision making control statements in C language. They are,
1. if statements
2. if else statements
3. nested if statements
o Syntax for each C decision control statements are given in below table with
description.
Decision
control Syntax Description
statements
if (condition) In these type of statements, if condition is true, then
if
{ Statements; } respective block of code is executed.
if (condition)
In these type of statements, group of statements are
{ Statement1; Statement2;}
if…else executed when condition is true. If condition is false,
else
then else part statements are executed.
{ Statement3; Statement4; }
if
(condition1){ Statement1; } If condition 1 is false, then condition 2 is checked and
nested if else_if (condition2) statements are executed if it is true. If condition 2 also
{ Statement2; } gets failure, then else part is executed.
else Statement 3;
Q17. Which looping statements used in c.
Ans:
There may be a situation, when you need to execute a block of code several number of times. In
general, statements are executed sequentially: The first statement in a function is executed first,
followed by the second, and so on.
Programming languages provide various control structures that allow for more complicated execution
paths.
A loop statement allows us to execute a statement or group of statements multiple times and
following is the general form of a loop statement in most of the programming languages:
1.While Loop:
A while loop statement in C programming language repeatedly executes a target statement as long as
a given condition is true.
Syntax:
The syntax of a while loop in C programming language is:
while(condition)
{
statement(s);
}
Here, statement(s) may be a single statement or a block of statements. The condition may be any
expression, and true is any nonzero value. The loop iterates while the condition is true.
When the condition becomes false, program control passes to the line immediately following the
loop.
Flow Diagram:
Here, key point of the while loop is that the loop might not ever run. When the condition is tested and
the result is false, the loop body will be skipped and the first statement after the while loop will be
executed.
Example:
#include <stdio.h>
void main ()
{
/* local variable definition */
int a = 10;
Getch();
}
2.Do…While loop
A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to execute at
least one time.
Syntax:
The syntax of a do...while loop in C programming language is:
do
{
statement(s);
}while( condition );
Notice that the conditional expression appears at the end of the loop, so the statement(s) in the loop
execute once before the condition is tested.
If the condition is true, the flow of control jumps back up to do, and the statement(s) in the loop
execute again. This process repeats until the given condition becomes false.
Flow Diagram:
Example:
#include <stdio.h>
void main ()
{
/* local variable definition */
int a = 10;
/* do loop execution */
do
{
printf("value of a: %d\n", a);
a = a + 1;
}while( a < 20 );
Getch();
}
3.For loop:
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; condition; increment )
{
statement(s);
}
1. The init step is executed first, and only once. This step allows you to declare and initialize any loop
control variables. You are not required to put a statement here, as long as a semicolon appears.
2. Next, the condition 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 flow of control jumps to the next statement just after the for loop.
3. After the body of the for loop executes, the flow of control jumps back up to the incrementstatement.
This statement allows you to update any loop control variables. This statement can be left blank, as
long as a semicolon appears after the condition.
4. The condition is now evaluated again. If it is true, the loop executes and the process repeats itself
(body of loop, then increment step, and then again condition). After the condition becomes false, the
for loop terminates.
Flow Diagram:
Example:
#include <stdio.h>
void main ()
{
/* for loop execution */
for( int a = 10; a < 20; a = a + 1 )
{
printf("value of a: %d\n", a);
}
Getch();
}
Q18.Difference between while loop and do..while loop
Ans:
Ans:
If the result of condition is TRUE ( non-zero ), expression1 is evaluated and the result of the
evaluation becomes the result of the operation. If the condition is FALSE (zero), then expression2 is
evaluated and its result becomes the result of the operation. An example will help,
s = ( x < 0 ) ? -1 : x * x;
break Statement
break;
The break statement can be used in terminating all three loops for, while and do...while
loops.
The figure below explains the working of break statement in all three type of loops.
Q21.Use of continue statement in c
Ans:
continue Statement
It is sometimes desirable to skip some statements inside the loop. In such cases, continue
statements are used.
continue;
For better understanding of how continue statements works in C programming. Analyze the
figure below which bypasses some code/s inside loops using continue statement.
Example of continue statement
Write a C program to find the product of 4 integers entered by a user. If user enters 0
skip it.
# include <stdio.h>
void main()
int i,num,product;
for(i=1,product=1;i<=4;++i){
printf("Enter num%d:",i);
scanf("%d",&num);
if(num==0)
continue; / *In this program, when num equals to zero, it skips the statement
product*=num and continue the loop. */
product*=num;
printf("product=%d",product);
getch();
Example:
#include <stdio.h>
int main ()
{
/* local variable definition */
int a = 10;
/* do loop execution */
LOOP:do
{
if( a == 15)
{
/* skip the iteration */
a = a + 1;
goto LOOP;
}
printf("value of a: %d\n", a);
a++;
}while( a < 20 );
return 0;
}
All arrays consist of contiguous memory locations. The lowest address corresponds to the first
element and the highest address to the last element.
Declaring Arrays
To declare an array in C, a programmer specifies the type of the elements and the number of elements
required by an array as follows:
You can initialize array in C either one by one or using a single statement as follows:
The number of values between braces { } can not be larger than the number of elements that we
declare for the array between square brackets [ ].
If you omit the size of the array, an array just big enough to hold the initialization is created.
Therefore, if you write:
You will create exactly the same array as you did in the previous example. Following is an example
to assign a single element of the array:
balance[4] = 50.0;
The above statement assigns element number 5th in the array with a value of 50.0. All arrays have 0
as the index of their first element which is also called base index and last index of an array will be
total size of the array minus 1. Following is the pictorial representation of the same array we
discussed above:
The above statement will take 10th element from the array and assign the value to salary variable.
Following is an example which will use all the above mentioned three concepts viz. declaration,
assignment and accessing arrays:
#include <stdio.h>
void main ()
{
int n[ 10 ]; /* n is an array of 10 integers */
int i,j;
Getch();
}
When the above code is compiled and executed, it produces the following result:
Element[0] = 100
Element[1] = 101
Element[2] = 102
Element[3] = 103
Element[4] = 104
Element[5] = 105
Element[6] = 106
Element[7] = 107
Element[8] = 108
Element[9] = 109
atan2 Computes arc tangent and determine the quadrant using sign
Example
#include<stdio.h>
main (){
printf("enter 2 numbers:
");
Output
Enter 2 numbers:
5
Sum=8
Example
#include<stdio.h>
main (){
c= sum ();
printf(“sum = %d”,c);
getch ();
}
int sum (){
int a,b,c;
printf(“enter 2 numbers”);
scanf (“%d%d”, &a, &b);
c = a+b;
return c;
Output
Example
#include<stdio.h>
main (){
void sum (int, int );
int a,b;
printf("enter 2 numbers");
scanf("%d%d", &a,&b);
sum (a,b);
getch ();
}
int c;
c= a+b;
printf (“sum=%d”, c);
Output
Enter two numbers 10 20
Sum=30
Example
#include<stdio.h>
main (){
int sum ( int,int);
int a,b,c;
printf("enter 2 numbers");
scanf("%d%d", &a,&b);
c= sum (a,b);
printf ("sum=%d", c);
getch ();
}
int c;
c= a+b;
return c;
Output
Enter two numbers 10 20
Sum=30
Q. 28.Differentiate between call by value and call by reference.
In this method, the value of each In this method, the address of actual
variable in calling function is copied variables in the calling function are copied
into corresponding dummy variables of into the dummy variables of the called
the called function. function.
With this method, the changes made to With this method, using addresses we
the dummy variables in the called would have an access to the actual
function have no effect on the values of variables and hence we would be able to
actual variables in the calling function. manipulate them.
return 0; return 0;
} }
t = x; t = *x;
x = y; *x = *y;
y = t; *y = t;
Output:
x=20 y=10
Output:
a=20 b=10
x=20 y=10
a=10 b=20
Values of variables are passed by the Pointer variables are necessary to define to
Simple technique. store the address values of variables.
Q29. Write a program to swap (interchange) two numbers using call by reference.
/*C program to swap two number using call by reference */
#include <stdio.h>
int main()
{
int num1, num2;
/* Input numbers */
printf("Enter two numbers: ");
scanf("%d%d", &num1, &num2);
return 0;
}
}
output:
Enter the range of the Fibonacci series: 10
Fibonacci Series: 0 1 1 2 3 5 8 13 21 34 55 89
Q.11.Explain the different storage classes in ‘C’.
Ans: Every variable and function in C programming has two properties: type and storage class. Type
refers to the data type of variable whether it is character or integer or floating-point value etc.
There are 4 types of storage class:
1.automatic
2.External
3.static
4.register
Automatic storage class
Variables declared inside the function body are automatic by default. These variable are also known
as local variables as they are local to the function and doesn't have meaning outside that function
Since, variable inside a function is automatic by default, keyword auto is rarely used.
eg. int n;
External storage class
External variable can be accessed by any function. They are also known as global variables.
Variables declared outside every function are external variables.
In case of large program, containing more than one file, if the global variable is declared in file 1 and
that variable is used in file 2 then, compiler will show error. To solve this problem, keyword extern is
used in file 2 to indicate that, the variable specified is global variable and declared in another file.
Example to demonstrate working of external variable
#include<stdio.h>
void Check();
int a=5; /* a is global variable because it is outside every function */
int main()
{
a+=4;/* same as a=a+4*/
Check();
return 0;
}
void Check()
{
++a; /* ----- Variable a is not declared in this function but, works in any function as they are
global variable ------- */
printf("a=%d\n",a);
}
Output
a=10
Register Storage Class
register int a;
Register variables are similar to automatic variable and exists inside that particular function only.
If the compiler encounters register variable, it tries to store variable in microprocessor's register
rather than memory. Value stored in register are much faster than that of memory.
In case of larger program, variables that are used in loops and function parameters are declared
register variables.eg. for(i=1;i<=10;i++)
Since, there are limited number of register in processor and if it couldn't store the variable in register,
it will automatically store it in memory.
Static Storage Class
The value of static variable persists until the end of the program. A variable can be declared static
using keyword: static. For example:
static int i;
Here, i is a static variable.
Example to demonstrate the static variable
#include <stdio.h>
void Check();
int main(){
Check();
Check();
Check();
}
void Check(){
static int count=0;
printf("%d\t",count);
count+=5;
}
Output
0 5 10
During first function call, it will display 0. Then, during second function call, variable c will not be
initialized to 0 again, as it is static variable. So, 5 is displayed in second function call and 10 in third
call.
If variable c had been automatic variable, the output would have been:
0 0 0
Q.32 Explain how you can define the data by using ‘typedef’ statement ?Give the suitable
example.
Ans: Typedef is used to define new data type for an existing data type. It provides an alternative
name for standard data type. It is used for self documenting the code by allowing descriptive names.
(for belter understanding) for the standard data type. The C programming language provides a
keyword called typedef, which you can use to give a type a new name.
The general format is:
typedef existing datatype new datatype;
For example:
typedef float real;
Now, in a program one can use datatype real instead of float.
Therefore, the following statement is valid:
real amount;
After this type definitions, the identifier BYTE can be used as an abbreviation for the type unsigned
char, for example:.
By convention, uppercase letters are used for these definitions to remind the user that the type name
is really a symbolic abbreviation, but you can use lowercase, as follows:
typedef unsigned char byte;
You can use typedef to give a name to user defined data type as well. For example you can use
typedef with structure to define a new data type and then use that data type to define structure
variables directly as follows:
// Structure using typedef:
#include <stdio.h>
#include <string.h>
typedef struct student
{
int id;
char name[20];
float percentage;
} status;
int main()
{
status record;
record.id=1;
strcpy(record.name, "Raju");
record.percentage = 86.5;
printf(" Id is: %d \n", record.id);
printf(" Name is: %s \n", record.name);
printf(" Percentage is: %f \n", record.percentage);
return 0;
}
Q.33 Explain in brief the use of enumerated data types with example
Ans: Enumerated Data Type
It has the following features:
It is user defined.
It works if you know in advance a finite list of values that a data type can take.
The list cannot be input by the user or output on the screen.
For example:
enum months { jan, feb, mar, apr, may};
enum days { sun, mon, tue, wed, thu };
enum toys { cycle, bicycle, scooter };
The enum specifier defines the set of all names that will be permissible values of
the type called members which are stored internally as integer constant. The first
name was given the integer value 0, the second value 1 and so on.
Program
#include< stdio.h>
void main()
{
int i;
enum month {JAN,FEB,MAR,APR,MAY,JUN,JUL,AUG,SEP,OCT,DEC};
clrscr();
for(i=JAN;i<=DEC;i++)
printf("\n%d",i);
}
Output :
01234567891011
Q34 Explain in brief arithmetic operations perform on pointers.OR pointer arithmetic.
Ans:You can perform a limited number of arithmetic operations on pointers. These operations are:
Increment and decrement
Addition and subtraction
Comparison
Assignment
The increment (++) operator increases the value of a pointer by the size of the data object the pointer
refers to. For example, if the pointer refers to the second element in an array, the ++ makes the
pointer refer to the third element in the array.
The decrement (--) operator decreases the value of a pointer by the size of the data object the pointer
refers to. For example, if the pointer refers to the second element in an array, the -- makes the pointer
refer to the first element in the array.
You can add an integer to a pointer but you cannot add a pointer to a pointer.
If the pointer p points to the first element in an array, the following expression causes the pointer to
point to the third element in the same array:
p = p + 2;
If you have two pointers that point to the same array, you can subtract one pointer from the other.
This operation yields the number of elements in the array that separate the two addresses that the
pointers refer to.
You can compare two pointers with the following operators: ==, !=, <, >, <=, and >=.
Program to illustrate the use of pointers in arithmetic operations in C Programming
main()
{
int a, b, *p1, *p2, x, y, z;
a = 12;
b = 4;
p1 = &a;
p2 = &b;
x = *p1 * *p2 - 6;
y = 4* - *p2 / *p1 + 10;
printf("Address of a = %u\n", p1);
printf("Address of b = %u\n", p2);
printf("\n");
printf("a = %d, b = %d\n", a, b);
printf("x = %d, y = %d\n", x, y);
*p2 = *p2 + 3;
*p1 = *p2 - 5;
z = *p1 * *p2 - 6;
printf("\na = %d, b = %d,", a, b);
printf(" z = %d\n", z);
}
Output :
Address of a = 4020
Address of b = 4016
a = 12, b = 4
x = 42, y = 9
a = 2, b = 7, z = 8
Q35 Write a C program to create a file called emp.rec and store information
about a person(File handling)
Ans: /*C program to create a file called emp.rec and store information
about a person, in terms of his name, age and salary.*/
#include <stdio.h>
void main()
{
FILE *fp;
char name[20];
int age;
float salary;
Arrays Structures
3. Any array behaves like a built-in 3. But in the case of structure, first we
data types. All we have to do is to have to design and declare a data
declare an array variable and use it. structure before the variable of that
type are declared and used.
struct structure_nm
{
<data-type> element 1;
<data-type> element 2;
-----------
-----------
<data-type> element n;
}inner_struct_var;
}outer_struct_var;
Example :
struct stud_Res
{
int rno;
char nm[50];
char std[10];
struct stud_subj
{
char subjnm[30];
int marks;
}subj;
}result;
In above example, the structure stud_Res consists of stud_subj which itself is a structure with two
members. Structure stud_Res is called as 'outer structure' while stud_subj is called as 'inner structure.'
The members which are inside the inner structure can be accessed as follow :
result.subj.subjnm
result.subj.marks
/* Program to demonstrate nested structures.
#include <stdio.h>
#include <conio.h>
struct stud_Result
{
int rno;
char std[10];
struct stud_Marks
{
char subj_nm[30];
int subj_mark;
}marks;
}res;
void main()
{
clrscr();
printf("\n\t Enter Roll Number : ");
scanf("%d",&res.rno);
printf("\n\t Enter Standard : ");
scanf("%s",res.std);
printf("\n\t Enter Subject Code : ");
scanf("%s",result.marks.subj_nm);
printf("\n\t Enter Marks : ");
scanf("%d",&result.marks.subj_mark);
printf("\n\n\t Roll Number : %d",res.rno);
printf("\n\n\t Standard : %s",res.std);
printf("\nSubject Code : %s",res.marks.subj_nm);
printf("\n\n\t Marks : %d",res.marks.subj_mark);
getch();
}
Output :
Enter Roll Number : 1
Enter standard : B.Sc(CS)-I
Enter subject code : CS01
Enter marks : 80
Roll Number : 1
Standard : B.Sc(CS)-I
Subject code : CS01
Q.39 What is union? Explain.
Ans. A union is a special data type available in C that enables you to store different data types in the
same memory location. You can define a union with many members, but only one member can
contain a value at any given time. Unions provide an efficient way of using the same memory
location for multi-purpose.
Defining a Union
To define a union, you must use the union statement in very similar was as you did while defining
structure. The union statement defines a new data type, with more than one member for your
program. The format of the union statement is as follows:
union <union tag>
{
member definition;
member definition;
...
member definition;
} [one or more union variables];
Ex. union Data
{
int i;
float f;
char str[20];
} data;
Now, a variable of Data type can store an integer, a floating-point number, or a string of characters.
This means that a single variable ie. same memory location can be used to store multiple types of
data.
Accessing Union Members
To access any member of a union, we use the member access operator (.). The member access
operator is coded as a period between the union variable name and the union member that we wish to
access. You would use union keyword to define variables of union type. Following is the example to
explain usage of union:
The memory occupied by a union will be large enough to hold the largest member of the union. For
example, in above example Data type will occupy 20 bytes of memory space because this is the
maximum space which can be occupied by character string. Following is the example which will
display total memory size occupied by the above union:
#include <stdio.h>
#include <string.h>
union Data
{
int i;
float f;
char str[20];
};
void main( )
{
union Data data;
data.i = 10;
data.f = 220.5;
strcpy( data.str, "C Programming");
printf( "data.i : %d\n", data.i);
printf( "data.f : %f\n", data.f);
printf( "data.str : %s\n", data.str);
getch();
}
Q.40 What is the difference Between Stucture and Union
Structure Union
i. Access Members
We can access all the members of structure at
Only one member of union can be accessed at anytime.
anytime.
ii. Memory Allocation
Allocates memory for variable which variable require
Memory is allocated for all variables.
more memory.
iii. Initialization
All members of structure can be initialized Only the first member of a union can be initialized.
iv. Keyword
'struct' keyword is used to declare structure. 'union' keyword is used to declare union.
v. Syntax
struct struct_name union union_name
{ {
structure element 1; union element 1;
structure element 2; union element 2;
---------- ----------
---------- ----------
structure element n; union element n;
}struct_var_nm; }union_var_nm;
vi. Example
struct item_mst union item_mst
{ {
int rno; int rno;
char nm[50]; char nm[50];
}it; }it;
OR
Difference Between Stucture and Union
BASIS OF
STRUCTURE UNION
COMPARISON
'structure'. location.
. .
. .
Size Size of Structure= sum of size of all the Size of Union=size of the
Store Value Stores distinct values for all the Stores same value for all the
members. members.
'structure'.
Way of Viewing Provide single way to view each Provide multiple way to to
declared.
Q.41 What are the different modes of files(File modes)?
Ans :The file modes are as follows,
Mode Description
Opens a text file for writing, if it does not exist then a new file is created.
w
Here your program will start writing content from the beginning of the file.
Opens a text file for writing in appending mode, if it does not exist then a new
a file is created. Here your program will start appending content in the existing
file content.
Opens a text file for reading and writing both. It first truncate the file to zero
w+
length if it exists otherwise create the file if it does not exist.
Opens a text file for reading and writing both. It creates the file if it does not
a+ exist. The reading will start from the beginning but writing can only be
appended.
VI)Strcmp():Comparison occurs between a first string (str1) with a second string (str2).
On comparing the two string, the values return by a function strcmp() are:
#include<stdio.h>
#include <string.h>
int main(){
char str1[20],str2[20];
printf("Enter 1st string: ");
gets(str1);//reads string from console
printf("Enter 2nd string: ");
gets(str2);
if(strcmp(str1,str2)==0)
printf("Strings are equal");
else
printf("Strings are not equal");
return 0;
}
When the above code is compiled and executed, it produces the following result −
Value of mean : 3.400000
It should be noted here that the cast operator has precedence over division, so the value of sum is first
converted to type double and finally it gets divided by count yielding a double value.
Type conversions can be implicit which is performed by the compiler automatically, or it can be
specified explicitly through the use of the cast operator. It is considered good programming practice
to use the cast operator whenever type conversions are necessary.
Q.44 Write a program to accept an integer value. Pass this value to two functions - one to
compute square value, and the other to compute cube value.
#include <stdio.h>
int square(int);
int cube(int);
int main()
{
int a;
printf("Enter a number :");
scanf("%d",&a);
int b=square(a);
printf("\nSquare= %d",b);
b=cube(a);
printf("\nCube= %d",b);
getch();
}
int square(int x)
{
return x*x;
}
int cube(int x)
{
return x*x*x;
}
Q.45 Explain ‘C’ PREPROCESSOR DIRECTIVES:
Ans: ‘C’ Preprocessor Directives
Before a C program is compiled in a compiler, source code is processed by a program called
preprocessor. This process is called preprocessing.
Commands used in preprocessor are called preprocessor directives and they begin with “#” symbol.
Below is the list of preprocessor directives that C programming language offers.
Preprocesso
r Syntax/Description
Syntax: #define
This macro defines constant value and can be any of the basic data types.
1. #include <stdio.h>
2. #define MIN(a,b) ((a)<(b)?(a):(b))
3. void main() { printf("Minimum between 10 and 20 is: %d\n", MIN(10,20));
4. }
Macro
rewind() function
The rewind() function sets the file pointer at the beginning of the stream. It is useful if you have to
use stream many times.
Syntax:
File: file.txt
File: rewind.c
fclose(fp);
#include<stdio.h>
#include<conio.h>
void main()
FILE *fp;
char c;
clrscr();
fp=fopen("file.txt","r");
while((c=fgetc(fp))!=EOF){
printf("%c",c);
while((c=fgetc(fp))!=EOF){
printf("%c",c);
getch();
Output:
As you can see, rewind() function moves the file pointer at beginning of the file that is why "this is
simple text" is printed 2 times. If you don't call rewind() function, "this is simple text" will be printed
only once.
ftell() function
The ftell() function returns the current file position of the specified stream. We can use ftell()
function to get the total size of a file after moving file pointer at the end of file. We can use
SEEK_END constant to move the file pointer at the end of file.
#include <conio.h>
FILE *fp;
int length;
clrscr();
fp = fopen("file.txt", "r");
fseek(fp, 0, SEEK_END);
length = ftell(fp);
fclose(fp);
getch();
Output:
C fseek() function
The fseek() function is used to set the file pointer to the specified offset. It is used to write data into
file at desired location.
Syntax:
There are 3 constants used in the fseek() function for whence: SEEK_SET, SEEK_CUR and
SEEK_END.
#include <stdio.h>
void main(){
FILE *fp;
fp = fopen("myfile.txt","w+");
fclose(fp);
myfile.txt