Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
UNIT I - INTRODUCTION
PART A (2 MARKS)
1. Define computers?
A computer is a programmable machine or device that performs pre-defined or programmed
computations or controls operations that are expressible in numerical or logical terms at high speed and with
great accuracy.
(Or)
Computer is a fast operating electronic device, which automatically accepts and store input data,
processes them and produces results under the direction of step by step program.
It stores data.
Micro computer
Mini Computer
Mainframe computer
Super Computer
ABC
EDVAC
EDSAC
UNIVAC
Basic components of the computer system are Input Unit, Central Processing Unit, Secondary Storage Unit
and Output Unit.
7. What is an ALU?
Arithmetic logic unit, the part of a computer that performs all arithmetic computations, such as addition and
multiplication, and all logical operations such as comparison operations. The ALU is one component of the
CPU (central processing unit).
8. What are the functions in the input unit?
An input device is a device that is used to input data or information into a computer. Some examples of input
devices include:
Keyboards.
Computer mice
Light Pen.
Digitizer.
Touchpad.
Speakers.
Printer.
Headphone
Volatile memory: also known as volatile storage is computer memory that requires power to maintain the
stored information, unlike non-volatile memory which does not require a maintained power supply. It has
been less popularly known as temporary memory.
Non-volatile memory: nonvolatile memory, NVM or non-volatile storage, is computer memory that can
retain the stored information even when not powered.
13. Write the binary and octal equivalent of hexadecimal number 7BD? (APR2009)
Binary Equivalent of 7BD = (0111 1011 1101)2
Octal Equivalent of 7BD = (011 110 111 101) = (3675)8
14. Convert binary number 100110 into its octal equivalent? (JAN2009)
Octal equivalent of 100110 = (100 110) = (46)8
15. What are registers? (JAN2009)
A special, high-speed storage area within the CPU. All data must be represented in a register before it can be
processed.
For example, if two numbers are to be multiplied, both numbers must be in registers, and the result is also
placed in a register.
16. Differentiate analog and digital computers? (JAN2010) Analog Computer Digital Computer
Sl.No
Analog Computer
Digital Computer
Less accuracy
More accuracy.
25. Draw the flowchart to find the maximum among three numbers (JAN2009)
UNIT-II
1. Define Compilation process.
Compilation refers to the processing of source code files (.c, .cc, or .cpp) and the creation of an 'object'
file. This step doesn't create anything the user can actually run. Instead, the compiler merely produces the
machine language instructions that correspond to the source code file that was compiled.
2. What do you meant by linking?
Linking refers to the creation of a single executable file from multiple object files. In this step, it is
common that the linker will complain about undefined functions (commonly, main itself). During
compilation, if the compiler could not find the definition for a particular function, it would just assume
that the function was defined in another file. If this isn't the case, there's no way the compiler would know it
doesn't look at the contents of more than one file at a time. The linker, on the other hand, may look at
multiple files and try to find references for the functions that weren't mentioned.
3. Define Constants in C. Mention the types.
The constants refer to fixed values that the program may not alter during its execution. These fixed values
are also called literals.
Constants can be of any of the basic data types like an integer constant, a floating constant, a character
constant, or a string literal. There are also enumeration constants as well.
The constants are treated just like regular variables except that their values cannot be modified after their
definition.
4. What are the different data types available in C?
There are four basic data types available in C.
1. int
2. float
3. char
4. double
5. What is meant by Enumerated data type.
Enumerated data is a user defined data type in C language.
Enumerated data type variables can only assume values which have been previously declared.
Example :
enum month { jan = 1, feb, mar, apr, may, jun, jul, aug, sep, oct, nov, dec };
6. What are Keywords?
Keywords are certain reserved words that have standard and pre-defined meaning in C. These keywords can
be used only for their intended purpose.
Example: Sum
8. Difference between Local and Global variable in C.
Local
These variables only exist inside the specific function that creates them. They are unknown to other
functions and to the main program. As such, they are normally implemented using a stack. Local
variables cease to exist once the function that created them is completed. They are recreated each time a
function is executed or called.
Global
These variables can be accessed (ie known) by any function comprising the program. They are
implemented by associating memory locations with variable names. They do not get recreated if the
function is recalled.
9. What are Operators? Mention their types in C.
An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations. C
language is rich in built-in operators and provides following type of operators:
Arithmetic Operators
Relational Operators
Logical Operators
Bitwise Operators
Assignment Operators
Special Operators
++a
means
do
the
increment
before
the
operation
(pre
increment)
Example:
a=5;
x=a++;
y=a;
x=++a;
3. Distinguish between while..do and do..while statement in C. (JAN 2009)
While
Executes the statements within the while block if only the
condition is true.
DO..while
Controlled Statement)
nested if statements
Description
You can use one if or else if statement inside another if or else if statemen
switch statement
can
use
one
or
more
loop
inside
any
are
two
types
of
I/O
statements
available
in
C.
Statements
20. Write short notes about main ( ) function in C program. (MAY 2009)
m execution starts from the opening brace { and ends with closing brace }, within
which executable part of the program exists.
21. Define delimiters in C.
Delimiters Use
: Colon
; Semicolon
( ) Parenthesis
[
Square
}
Curly
Bracket
Brace
# Hash
, Comma
22. Why header files are included in C programming?
This section is used to include the function definitions used in the program. Each header file has h
extension and include using # include directive at the beginning of a program.
23.What is the output of the programs given below?
main()
main()
float a;
float a;
a=x\y;
a=(float) x\y;
printf(Value of a=%f,a);
Output:
Output:
1.
1.500000
While
some statements.
(iii) If the condition is false the control is
(iii) If the condition is false then it
stops
the execution the statements.
27.Differentiate between formatted and unformatted you input and output functions? Formatted I/P functions:
These functions allow us to supply the input in a fixed format and let us obtain the output in the specified
form. Formatted output converts the internal binary representation of the data to ASCII characters which are
written to the output file.
Unformatted I/O functions:
There are several standard library functions available under this category-those that can deal with a string of
characters. Unformatted Input/Output is the most basic form of input/output. Unformatted input/output
transfers the internal binary representation of the data directly between memory and the file.
UNIT II
(16 Marks)
1. Define C language. Mention the basic structure of C programs with explanation. (16)
C programs are essentially constructed in the following manner, as a number of well defined sections.
/* HEADER SECTION
*/
/* Contains name, author, revision number*/
/* INCLUDE SECTION
/* contains #include statements
*/
*/
*/
*/
/* FUNCTIONS SECTION
/* user defined functions
*/
*/
/* main() SECTION
*/
int
{
----}
main()
A Simple Program
The following program is written in the C programming language.
#include <stdio.h>
Void main()
{
printf(Programming
}
in
is
easy.\n);
or
character
array
HEADER FILES
Header files contain definitions of functions and variables which can be incorporated into any C
program by using the pre-processor #include statement. Standard header files are provided with each
compiler, and cover a range of areas, string handling, mathematical, data conversion, printing and reading
of variables. To use any of the standard functions, the appropriate header file should be included. This is
done at the beginning of the C source file. For example, to use the function printf() in a program, the line
#include <stdio.h> should be at the beginning of the source file, because the definition for printf() is
found in the file stdio.h All header files have the extension .h and generally reside in the /include
subdirectory.
#include <stdio.h>
#include mydecls.h
The use of angle brackets <> informs the compiler to search the compilers include directory for the
specified file. The use of the double quotes around the filename inform the compiler to search in the
current directory for the specified file.
2. Discuss about the various data types in C. (MAY 2009)
The four basic data types are
a. INTEGER
These are whole numbers, both positive and negative. Unsigned integers (positive values only) are
supported. In addition, there are short and long integers.
The keyword used to define integers is,
int
An example of an integer value is 32. An example of declaring an integer
int sum;
sum = 20;
b. FLOATING POINT
These are numbers which contain fractional parts, both positive and negative. The keyword used to define
float variables is, float An example of a float value is 34.12. An example of declaring a float variable
called money is,
float
money;
money = 0.12;
c. DOUBLE
These are exponentional numbers, both positive and negative. The keyword used to define double
variables is, double
An example of a double value is 3.0E2. An example of declaring a double
double big;
big = 312E+7;
d. CHARACTER
These are single characters. The keyword used to define character variables is,char An example of a
character value is the letter A. An example of declaring a character variable called letter is, char letter;
letter = A;
Note the assignment of the character A to the variable letter is done by enclosing the value in single
quotes.
Example:
#include
<
stdio.h
>
main()
{
int sum;
float
money;
char
letter;
double pi;
sum = 10;
pi = 2.01E6;
of
money
%f\n,
money
);
printf(value
of
letter
%c\n,
letter
);
pi
pi
);
printf(value
of
%e\n,
}
Sample program output
value of sum = 10
value of money = 2.210000 value of letter = A
value of pi = 2.010000e+06
3. What are Operators? Explain the various operators available in C. (16)
An ex pr e ss io n is a sequence of operators and operands that specifies computation of a value, or that
designates an object or a function, or that generates side effects, or that performs a combination thereof.
ARITHMETIC OPERATORS:
The symbols of the arithmetic operators are:Operation Operator Comment
Multiply
Divide
sum = sum * 2;
sum = sum / 2;
4
4
8
2
Addition
sum = sum + 2;
Subtraction
Increment
++
++sum;
Decrement
--
--sum;
Modulus
Example:
sum = sum % 3;
#include
main()
{
int sum 50;
float modulus;
modulus = sum % 10;
printf("The
%%
}
<stdio.h>
of
%d
by
10
is
%f\n",
sum,
modulus);
equal
Example:
#include <stdio.h>
main()
/*
Program
introduces
the
for
statement,
counts
{
int count;
for( count = 1; count <= 10; count = count + 1 ) printf("%d ", ount ); printf("\n");
}
LOGICAL (AND, NOT, OR, EOR)
to
ten
*/
LOGICAL OR ||
Logical or will be executed if any ONE of the conditions is TRUE (non-zero).
LOGICAL NOT !
logical not negates (changes from TRUE to FALSE, vsvs) a condition.
LOGICAL EOR ^
Logical error will be executed if either condition is TRUE, but NOT if they are all true.
BIT OPERATIONS
C has the advantage of direct bit manipulation and the operations available are,
Operation
Operator Comment
AND
&
OR
sum = sum | 2;
Exclusive OR
sum = sum ^ 2;
1's Complement
sum = ~sum;
Left Shift
<<
-5
4
Right Shift
>>
16
Example:
/*
Example
program
#include <stdio.h>
illustrating
<<
and
>>
*/
main()
{
int n1 = 10, n2 = 20, i = 0;
i
=
n2
<<
four
times
i = n1 >> 5; /* n1 shifted right
five
times
}
4.
Explain
in
detail
about
4;
*/
/*
n2
shifted
printf("%d\n",
*/
managing
printf("%d\n",
the
Input
Output
left
i);
i);
Operations.
(16)
Printf ():
printf() is actually a function (procedure) in C that is used for printing variables and text. Where text
appears in double quotes "", it is printed without modification. There are some exceptions however. This has
to do with the \ and % characters. These characters are modifier's, and for the present the \ followed by the n
character represents a newline character.
Example:
#include <stdio.h>
main()
{
printf("Programming
in
printf("And
so
}
O/P:
Programming in C is easy. And so is Pascal.
is
easy.\n");
Pascal.\n");
is
Scanf ():
Scanf () is a function in C which allows the programmer to accept input from a keyboard.
Example:
#include <stdio.h>
main()
{
int number;
/*
printf("Type
printf("The
}
in
number
program
which
number
you
introduces
\n");
typed
was
keyboard
input
scanf("%d",
%d\n",
*/
&number);
number);
1;
i<=
=
5;
++i
)
getchar();
The program reads five characters (one for each iteration of the for loop) from the keyboard. Note that
getchar() gets a single character from the keyboard, and putchar() writes a single character (in this case, ch)
to the console screen
if( expression )
program statement;
Example:
if(
++student_count;
students
<
65
IF ELSE
The general format for these is,
if( condition 1 ) statement1;
else if( condition
2 ) statement2;
else if( condition
3 ) statement3;
else statement4;
The else clause allows action to be taken where the condition evaluates as false (zero).
The following program uses an if else statement to validate the users input to be in the range 1-10.
Example:
#include <stdio.h>
main()
{
int number; int valid = 0;
while( valid == 0 ) {
printf("Enter a number between 1 and 10 -->"); scanf("%d",&number); if( number < 1 )
{
printf("Number
is
below
1.
Please
re-enter\n");
valid
}
else
if(
number
>
10
{
printf("Number
is
above
10.
Please
re-enter\n");
valid
}
else
valid
=
}
0;
)
0;
1;
an
number1
operator
in
operator
'/')
number2;
else
result = number1
if(operator
==
'+')
'-')
=
%f
number1
is
%f\n",
number1,
operator,
number2;
number2,
result
);
6. With example explain the Branching and Looping mechanism in C (16) ITERATION, FOR LOOPS
The basic format of the for statement is,
for(
start
condition;
continue
program statement;
condition;
re-evaulation
Example:
/* sample program using a for statement
*/ #include <stdio.h>
main()
/*
{
int count;
Program
introduces
the
for
statement,
counts
to
ten
*/
for( count = 1; count <= 10; count = count + 1 ) printf("%d ", count );
printf("\n");
}
The program declares an integer variable count. The first part of the for statement
for( count = 1;
initialises the value of count to 1. The for loop continues whilst the condition
count <= 10;
evaluates as TRUE. As the variable count has just been initialised to 1, this condition is TRUE and so the
program statement printf("%d ", count ); is executed, which prints the value of count to the screen,
followed by a space character.
Next, the remaining statement of the for is executed
count = count + 1 );
which adds one to the current value of count. Control now passes back to the conditional test,
count <= 10;
which evaluates as true, so the program statement
printf("%d ", count );
is executed. Count is incremented again, the condition re-evaluated etc, until count reaches a value of
11.
When this occurs, the conditional test
count <= 10;
evaluates as FALSE, and the for loop terminates, and program control passes to the statement
printf("\n");
which prints a newline, and then the program terminates, as there are no more statements left to
execute.
THE WHILE STATEMENT
The while provides a mechanism for repeating C statements whilst a condition is true. Its format is,
while( condition )
program statement;
Somewhere within the body of the while loop a statement must alter the value of the condition to allow the
loop to finish.
Example:
/* Sample program
including
#include <stdio.h>
while
*/
main()
{
int loop = 0;
while(
{
printf("%d\n",
loop
<=
10
)
loop);
++loop;
}
}
The above program uses a while loop to repeat the statements
printf("%d\n", loop);
++loop;
while the value of the variable loop is less than or equal to 10.
Note how the variable upon which the while is dependant is initialised prior to the while statement (in this case
the previous line), and also that the value of the variable is altered within the loop, so that eventually the
conditional test will succeed and the while loop will terminate.
This program is functionally equivalent to the earlier for program which counted to ten. THE DO WHILE
STATEMENT
The do { } while statement allows a loop to continue whilst a condition evaluates as TRUE (non-zero). The
loop is executed as least once.
Example:
/* Demonstration of
DO...WHILE */
#include <stdio.h>
main()
{
int value, r_digit;
printf("Enter the number to be
reversed.\n"); scanf("%d", &value);
do {
r_digit
10;
r_digit); value
value / 10;
} while( value !=
0
}
= value %
printf("%d",
=
);
printf("\n");
The above program reverses a number that is entered by the user. It does this by using the modulus %
operator to extract the right most digits into the variable r_digit. The original number is then divided by 10,
and the operation repeated whilst the number is not equal to 0.
SWITCH CASE:
The switch case statement is a better way of writing a program when a series of if elses occurs. The general
format for this is,
switch ( expression )
{ case value1:
program
statement;
program statement;
break;
case valuen:
program statement;
break;
default:
break;
}
he keyword break must be included at the end of each case statement. The default clause is optional,
and is executed if the cases are not met. The right brace at the end signifies the end of the case
selections.
Example:
#include <stdio.h>
main()
{
int menu, numb1, numb2, total;
printf("enter
in
&numb1,
&numb2
printf("1=addition\n");
scanf("%d", &menu );
two
numbers
);
-->");
printf("enter
scanf("%d
in
%d",
choice\n");
printf("2=subtraction\n");
switch( menu )
{
case
1:
total
numb2;
break;
numb1
numb2;
default:
break;
case
printf("Invalid
2:
total
option
numb1
selected\n");
if( menu == 1 )
printf("%d plus %d is %d\n", numb1, numb2, total ); else if( menu == 2 ) printf("%d minus %d is %d\n",
numb1, numb2, total );
}
The above program uses a switch statement to validate and select upon the users input choice, simulating a
simple menu of choices.
7.C programs related to problem solving.
8..C programs related to scientific problem solving.
UNIT -III
2 MARKS
1. What is an array?
An array is a group of similar data types stored under a common name. An array is used to store a
collection of data, but it is often more useful to think of an array as a collection of variables of the same
type.
Example:
int a[10];
Here a[10] is an array with 10 values.
2.
What
are
the
main
elements
of
an
array
declaration?
Type
and
Pointer
1.Pointer is explicitly assigned to point to an allocated
space.
2.It can be resized using realloc ().
3.Pointers can be reassigned.
4.Sezeof(pointer name) returns the number of bytes
used to store the pointer variable
6. List the characteristics of Arrays.
All elements of an array share the same name, and they are distinguished form one another with help of
an element number. Any particular element of an array can be modified separately without disturbing
other elements.
7. What are the types of Arrays?
1.One-Dimensional Array
2. Two-Dimensional Array
3. Multi-Dimensional Array
8. Define Strings.
Strings:
The group of characters, digit and symbols enclosed within quotes is called as Stirng (or) character
Arrays. Strings are always terminated with \0 (NULL) character. The compiler automatically adds \0 at
the end of the strings.
Example:
char name[]={C,O,L,L,E,G,E,E,\0};
uick
Sort.
1. Remove the topmost item (the largest) and replace it with the rightmost leaf. The topmost item is stored in
an array.
2. Re-establish the heap.
3. Repeat steps 1 and 2 until there are no more items left in the heap.
Mention
the
various
types
of
searching
techniques
in
UNIT III
16 MARKS
1. Define array. Explain the array types with an example program for each type.
Arrays are data structures which hold multiple variables of the same data type. Consider the case where a
programmer needs to keep track of a number of people within an organization. So far, our initial attempt will
be to create a specific variable for each user.
This might look like,
int
name1
101;
int
name2
232;
101;
names[1]
232;
names[2]
231;
names[3] = 0;
We created an array called names, which has space for four integer variables. You may also see that we
stored 0 in the last space of the array. This is a common technique used by C programmers to signify the
end of an array. Arrays have the following syntax, using square brackets to access each indexed value
(called an element).x[i]
so that x[5] refers to the sixth element in an array called x. In C, array elements start with 0. Assigning values
to array elements is done by, x[10] = g; and assigning array elements to a variable is done by, g = x[10]; In the
following
example,
character
based
array
named
word
is
declared,
and
each
element is assigned a character. The last element is filled with a zero value, to signify the end of the
character string (in C, there is no string type, so character based arrays are used to hold strings). A printf
statement is then used to print out all elements of the array.
/* Introducing array's, 2 */
#include <stdio.h>
main()
{
char
word[0]
word[1]
word[2]
word[3]
word[4]
word[5] = 0;
printf("The
contents
}
word[20];
'H';
'e';
'l';
'l';
'o';
=
=
=
=
=
of
word[]
is
-->%s\n",
word
);
m2[1][0]
m2[1][1] = 3
Example:
#include
<stdio.h>
main()
{
static int m[][] = { {10,5,-3}, {9, 0, 0}, {32,20,1}, {0,0,8} }; int row, column, sum;
sum = 0;
for( row = 0; row < 4; row++ )
for( column = 0; column < 3; column++ ) sum = sum + m[row][column];
printf("The
total
is
%d\n",
sum
);
}
3. Explain String Array with example program.
CHARACTER
ARRAYS
[STRINGS]
Consider
the
following
program,
#include <stdio.h>
main()
{
static
char
name1[]
{'H','e','l','l','o'};
static
char
name2[]
"Hello";
printf("%s\n", name1);
printf("%s\n", name2);
}
The difference between the two arrays is that name2 has a null placed at the end of the string, ie, in
name2[5], whilst name1 has not. To insert a null at the end of the name1 array, the initialization can be
changed to, static char name1[] = {'H','e','l','l','o','\0'};
Consider the following program, which initialises the contents of the character based array word during the
program, using the function strcpy, which necessitates using the include file string.h
Example:
#include <stdio.h>
#include
main()
{
Char word[20]; Char word[20]; strcpy(word, "hi there." )
printf("%s\n", word );
}
<string.h>
4. Explain the standard string functions with example to support each type.
Strings:
The group of characters, digits and symbols enclosed within quotes is called as strings or character arrays.
Strings are always terminated with \0 character(NULL).
Example:
char name[ ] = {H,E,L,L,O};
Standard String Functions:
strlen( )
strcpy(
strncpy( )
stricmp( )
strcmp(
strncmp(
strcat( )
strrev( ) etc.,
Example:Program
/*Illustration of string- handling functions*/ #include<string.h>
main()
{
char s1[20],s2[20],s3[20]; int x, l1, l2, l3;
printf(Enter two string constants \n); printf(?);
scanf(%s %s, s1, s2); x = strcmp(s1, s2); if(x != 0)
printf(Strings are not equal \n); strcat(s1, s2);
else
printf(Strings are equal \n); strcpy(s3,s1); l1 = strlen(s1);
l2
strlen(s2);
l3 = strlen(s3);
printf(\ns1 = %s \t length = %d characters \n,s1, l1); printf(\ns2= %s \t length = %d characters \n,s2, l2);
printf(\ns3 = %s \t length = %d characters \n,s3, l3);
}
OUTPUT
Enter two string constants
? New York
Strings are not equal
s1 = New York
length = 7 characters
s2 = York
length = 4 characters
s3 = New York
length = 7 characters
length = 6 characters
length = 6 characters
length = 6 characters
for(i=0;i<3;i++){
printf("\n");
for(j=0;j<3;j++)
printf("%d\t",a[i][j]);
}
printf("\nThe Second matrix is\n"); for(i=0;i<3;i++){
printf("\n");
for(j=0;j<3;j++)
printf("%d\t",b[i][j]);
}
for(i=0;i<3;i++)
for(j=0;j<3;j++)
c[i][j]=a[i][j]+b[i][j];
printf("\nThe Addition of two matrix is\n"); for(i=0;i<3;i++){
printf("\n");
for(j=0;j<3;j++)
printf("%d\t",c[i][j]);
}
return
}
6. Write a program for matrix multiplication in c
#include<stdio.h>
int main()
{
int a[5][5],b[5][5],c[5][5],i,j,k,sum=0,m,n,o,p;
printf("\nEnter the row and column of first matrix"); scanf("%d %d",&m,&n);
printf("\nEnter the row and column of second matrix");
0;
scanf("%d %d",&o,&p);
if(n!=o)
{
printf("Matrix mutiplication is not possible");
printf("\nColumn
of
first
matrix
must
be
same
as
row
of
second
matrix");
}
Else
{
printf("\nEnter the First matrix->"); for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf("%d",&a[i][j]);
printf("\nEnter the Second matrix->"); for(i=0;i<o;i++)
for(j=0;j<p;j++)
scanf("%d",&b[i][j]);
printf("\nThe First matrix is\n"); for(i=0;i<m;i++){
printf("\n");
for(j=0;j<n;j++){
printf("%d\t",a[i][j]);
}
}
printf("\nThe Second matrix is\n"); for(i=0;i<o;i++){
printf("\n");
for(j=0;j<p;j++){
printf("%d\t",b[i][j]);
}
}
for(i=0;i<m;i++)
for(j=0;j<p;j++)
c[i][j]=0;
for(i=0;i<m;i++){ //row of first matrix
for(j=0;j<p;j++){
//column
sum=0;
for(k=0;k<n;k++)
sum=sum+a[i][k]*b[k][j]; c[i][j]=sum;
of
second
matrix
}
}
printf("\nThe multiplication of two matrix is\n"); for(i=0;i<m;i++){
printf("\n");
for(j=0;j<p;j++){
printf("%d\t",c[i][j]);
}
}
return
}
0;
for(i=0;i<m;i++){
for(j=0;j<n;j++){
b[i][j]=a[j][i];
printf("\n%d",b[i][j]);
}
}
printf("\n\nTraspose of a matrix is -> "); for(i=0;i<m;i++){
printf("\n");
for(j=0;j<m;j++){
printf("%d\t",b[i][j]);
}
}
return
}
UNIT IV
2 MARKS
n
Page 87
0;
UNIT V
2 MARKS
1. Compare arrays and structures.
Comparison of arrays and structures is as follows.
Arrays
Structures
An array is a collection of data items of same data A structure is a collection of data items of different
type.Arrays can only be declared.
element.
Shorthand notation of the declaration.
An array cannot have bit fields.
Union
All members occupy separate memory location, hence different interpretations of the
Different interpretatio
Conservation of memo
Page 88
3. Define Structure in C.
C Structure is a collection of different data types which are grouped together and each element in a C
structure is called member.
structure members in C, structure variable should be declared.
each separately.
structure members.
4. What you meant by structure definition?
A structure type is usually defined near to the start of a file using a typedef statement. typedef defines and
names a new type, allowing its use throughout the program. typedefs usually occur just after the #define and
#include statements in a file.
Here is an example structure definition.
typedef struct {
char
name[64];
char
course[128];
int age;
int
year;
} student;
This defines a new type student variables of type student can be declared as follows.
student st_rec;
5. How to Declare a members in Structure?
A struct in C programming language is a structured (record) type [1] that aggregates a fixed set of labeled
objects, possibly of different types, into a single object. The syntax for a struct declaration in C is:
Page 89
struct tag_name
{
type
attribute;
type
attribute2;
/* ... */
};
6. What is meant by Union in C.?
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.
7. How to define a union in C.
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];
Page 90
int
}
Page 91
Miles;
Static is the default storage class for global variables. The two variables below (count and road) both have a
static storage class.
static int Count;
int Road;
{
printf("%d\n",
Road);
}
14. Define Auto storage class in C.
auto is the default storage class for all local variables.
{
int Count;
auto
int
Month;
}
The example above defines two variables with the same storage class. auto can only be used within
functions, i.e. local variables.
Page 92
Example:
#define
int
int table2[TABLE_SIZE];
TABLE_SIZE
100
table1[TABLE_SIZE];
#ifdef TABLE_SIZE
int table[TABLE_SIZE];
3 #endif
Page 93
A structure is a collection of one or more variables of different data types grouped together under a single
name. It contains different data types. C Structure is a collection of different data types which are grouped
together and each element in a C structure is called member.
cture variables can be declared for same structure and memory will be allocated for
each separately.
structure members.
Syntax:
struct
{
type variable 1;
Page 94
struct-name
type variable 2;
type variable n;
} structure_variables;
name[20];
float percentage; };
int
{
struct student record = {0}; //Initializing to null
main()
record.id=1;
strcpy(record.name,
record.percentage = 86.5;
printf(" Id is: %d \n", record.id);
printf(" Name is: %s \n", record.name);
printf("
Percentage
return 0;
Output:
Id is: 1
Name is: Raju
Percentage is: 86.500000
Page 95
"Raju");
is:
%f
\n",
record.percentage);
#include <stdio.h>
2.
#include <stdlib.h>
3.
4.
struct object {
5.
char id[20];
6.
int xpos;
7.
int ypos;
8.
};
9.
10.
11.
12.
13.
14.
void main() {
15.
16.
int i;
17.
18.
19.
20.
21.
22.
23.
24.
25.
gameobjs[1].xpos = 1;
26.
gameobjs[1].ypos = 2;
Page 96
27.
28.
29.
30.
printobj(gameobjs[i]);
}
31.
32.
33.
34.
strcpy(newobj.id, id);
35.
newobj.xpos = xpos;
36.
newobj.ypos = ypos;
37.
return newobj;
38.
39.
We create an array of structures called gamobjs and use the createobj function to initilize it's elements.
You can observer that there is not much difference between the two programs. We added an update for
the enemy1's position to show how to access a structure's members when it is an element within an array.
Output:
Page 97
name[20];
float percentage; };
"Raju");
func(record);
return 0;
}
void
func(struct
{
printf(" Id is: %d \n", record.id);
printf(" Name is: %s \n", record.name);
printf("
Percentage
}
student
is:
%f
\n",
record)
record.percentage);
Output:
Id is: 1
Name is: Raju
Percentage is: 86.500000
Page 99
structure_nm
element
1;
structure_nm
element
1;
element
n;
Example Program :
Program to demonstrate nested structures.
#include <stdio.h>
#include <conio.h>
struct
stud_Res
{
int rno;
char std[10];
struct
stud_Marks
{
char
subj_nm[30];
int subj_mark; }marks;
}result;
void
main()
{
clrscr();
printf("\n\t Enter Roll Number : "); scanf("%d",&result.rno);
printf("\n\t Enter Standard : "); scanf("%s",result.std);
printf("\n\t
Enter
Subject
scanf("%s",result.marks.subj_nm);
printf("\n\t Enter Marks : ");
scanf("%d",&result.marks.subj_mark);
printf("\n\n\t Roll Number : %d",result.rno);
printf("\n\n\t Standard : %s",result.std);
printf("\nSubject Code : %s",result.marks.subj_nm);
00
Code
");
Subject
Code
MCA(Sci)-I
:
SUB001
Marks : 63
5. Explain the concept of pointer to structure.
C structure can be accessed in 2 ways in a C program. They are,
1. Using normal structure variable
2. Using pointer variable
Dot(.) operator is used to access the data using normal structure variable and arrow (->) is used to
access the data using pointer variable. You have learnt how to access structure data using normal variable
in C - Structure topic. So, we are showing here how to access structure data using pointer variable in
below C program.
01
name[30];
float percentage; };
int
{
int i;
struct student record1 = {1, "Raju", 90.5}; struct student *ptr;
ptr = &record1;
printf("Records of STUDENT1: \n");
printf(" Id is: %d \n", ptr->id);
printf(" Name is: %s \n", ptr->name);
printf(" Percentage is: %f \n\n", ptr->percentage);
return 0;
}
02
main()
Output:
Records of STUDENT1:
Id
is:
Name
is:
Raju
student
{
char name[20];
int
rollno,m1,m2,m3,tot;
float avg;
}s1;
Union of structure
Union can be nested with another union.
Example program:
#include
#include <string.h>
<stdio.h>
union student
{
char name[20];
char subject[20];
float percentage; };
int
{
union student record1;
03
main()
%f
\n",
record2.percentage);
Output:
Union
Name :
Subject :
Percentage : 86.500000
record1
04
values
example
extern
auto - Storage Class
auto is the default storage class for all local variables.
{
int Count;
auto
int
Month;
}
The example above defines two variables with the same storage class. auto can only be used within
functions, i.e. local variables.
register - Storage Class
register is used to define local variables that should be stored in a register instead of RAM. This means that
the variable has a maximum size equal to the register size (usually one word) and cant have the unary '&'
operator applied to it (as it does not have a memory location).
{
register
int
}
Miles;
Register should only be used for variables that require quick access - such as counters. It should also be
noted that defining 'register' goes not mean that the variable will be stored in a register. It means that it
MIGHT be stored in a register - depending on hardware and implementation restrictions.
static - Storage Class
static is the default storage class for global variables. The two variables below (count and road) both have a
static storage class.
static
int
Count;
int Road;
{
printf("%d\n",
Road);
}
static variables can be 'seen' within all functions in this source file. At link time, the static variables
defined here will not be seen by the object modules that are brought in.
static can also be defined within a function. If this is done the variable is initialized at run time but is not
reinitialized when the function is called. This inside a function static variable retains its value during
various calls.
void func(void);
static count=10; /* Global variable - static is the default */
main()
{
while
{
func();
}
(count--)
}
void
func(
void
{
static
5;
i++;
printf("i
is
%d
and
count
is
%d\n",
i,
count);
}
This will produce following result
i is 6 and count is 9
i
is
and
count
is
is
and
count
is
is
and
count
is
is
10
and
count
is
is
11
and
count
is
is
12
and
count
is
is
13
and
count
is
is
14
and
count
is
i is 15 and count is 0
8. Describe in detail about the Preprocessors in C. (MAY 2009)
THE PREPROCESSOR
The define statement is used to make programs more readable, and allow the inclusion of macros.
Consider the following examples,
#define TRUE 1 /* Do not use a semi-colon , # must be first character on line */ #define FALSE 0
#define
#define AND &
NULL
#define OR |
#define
EQUALS
==
game_over = TRUE;
while( list_pointer != NULL )
MACROS
Macros are inline code which is substituted at compile time. The definition of a macro, which accepts an
argument when referenced,
#define SQUARE(x) (x)*(x) y = SQUARE(v);
In this case, v is equated with x in the macro definition of square, so the variable y is assigned the square of v.
The brackets in the macro definition of square are necessary for correct evaluation.
The expansion of the macro becomes y = (v) * (v);
Naturally, macro definitions can also contain other macro definitions,
#define IS_LOWERCASE(x) (( (x)>='a') && ( (x) <='z') )
#define TO_UPPERCASE(x) (IS_LOWERCASE (x)?(x)-'a'+'A':(x))
while(*string)
{
*string
TO_UPPERCASE
(*string);
++string;
}
CONDITIONAL COMPILATIONS
These are used to direct the
compiler
to
compile/or
not
compile
the
lines
that
follow
#ifdef
#define
#define SP 32
NULL
NL
10
#endif
In the preceding case, the definition of NL and SP will only occur if NULL has been defined prior to the
compiler encountering the #ifdef NULL statement. The scope of a definition may be limited by
#undef NULL
This renders the identification of NULL invalid from that point onwards in the source file.
Typedef
This statement is used to classify existing C data types, eg,
typedef int counter; /* redefines counter as an integer */
counter j, n; /* counter now used to define j and n as integers */ typedef struct {
int
month,
} DATE;
DATE todays_date; /* same as struct date todays_date */
day,
year;