Showing posts with label Fundamentals of Computer. Show all posts
Showing posts with label Fundamentals of Computer. Show all posts

Fundamentals of Computing and Programming (FOCP) Question Bank,Previous Year Question Paper,Lecture Notes and Lab Manual

FOCP - FUNCTIONS AND POINTERS (Unit 5)–16Mark Questions

FUNDAMENTALS OF COMPUTING & COMPUTER PROGRAMMING

UNIT V – 16 Marks

FUNCTIONS AND POINTERS


1. What are functions? Explain the types of functions in detail with an example program for each type.

A function is a self contained block or a sub program of one or more statements

that performs a special task when called.

Types:

· Library Functions

· User Defined functions

(a) Function Declaration

returntype function-name(Parameters);

Example:

int square(int, int);

(b) Function calling

function-name(actual parameters);

Example:

int square(a,b);

(c) Function Definition:

returntype function-name(formal parameters)

{

}

Example:

local variable declaration;

statement 1; statement 2; return(value);

void square(int a, int b)

{

printf(“%d”,(a*b));

}

Example for functions:

· Addition of two numbers where addition is a separate function

· Program using function for evaluating Fibonacci series.


2. Define arrays. 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; int name3 = 231;

It becomes increasingly more difficult to keep track of this as the number of variables increase. Arrays offer a solution to this problem. An array is a multi-element box, a bit like a filing cabinet, and uses an indexing system to find each variable stored within it. In C, indexing starts at zero. Arrays, like other variables in C, must be declared before they can be used. The replacement of the above example using arrays looks like,

int names[4]; names[0] = 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, a 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[20]; word[0] = 'H'; word[1] = 'e'; word[2] = 'l'; word[3] = 'l'; word[4] = 'o'; word[5] = 0;

printf("The contents of word[] is -->%s\n", word );

}

DECLARING ARRAYS

Arrays may consist of any of the valid data types. Arrays are declared along with all other variables in the declaration section of the program.

/* Introducing array's */

#include <stdio.h>

main()

{

int numbers[100]; float averages[20]; numbers[2] = 10;

--numbers[2];

printf("The 3rd element of array numbers is %d\n", numbers[2]);

}

The above program declares two arrays, assigns 10 to the value of the 3rd element of array numbers, decrements this value ( --numbers[2] ), and finally prints the value. The number of elements that each array is to have is included inside the square brackets

ASSIGNING INITIAL VALUES TO ARRAYS

The declaration is preceded by the word static. The initial values are enclosed in braces,

Example:

#include <stdio.h>

main()

{

int x;

static int values[] = { 1,2,3,4,5,6,7,8,9 };

static char word[] = { 'H','e','l','l','o' };

for( x = 0; x < 9; ++x )

printf("Values [%d] is %d\n", x, values[x]);

}

MULTI DIMENSIONED ARRAYS

Multi-dimensioned arrays have two or more index values which specify the element in the array.

multi[i][j];

In the above example, the first index value i specifies a row index, whilst j specifies a column index.

DECLARATION

int m1[10][10];

static int m2[2][2] = { {0,1}, {2,3} };

sum = m1[i][j] + m2[k][l];

NOTE the strange way that the initial values have been assigned to the two-dimensional array m2. Inside the braces are,

{ 0, 1 },

{ 2, 3 }

Remember that arrays are split up into row and columns. The first is the row, the second is the column. Looking at the initial values assigned to m2, they are,

m2[0][0] = 0 m2[0][1] = 1 m2[1][0] = 2 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 );

}

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 <string.h>

main()

{

char word[20];

strcpy( word, "hi there." );

printf("%s\n", word );

}


3. 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:

· To read and display a string.

· Program to count the number of lines, words and characters in a text.


4. What are pointers? When and why they are used? Explain in detail with sample programs. (JAN 2009/MAY 2009)

Pointer variable is needed to store the memory address of any variable. Denoted by

(*) asterisk.

Pointer Declaration: Syntax:

datatype *variable-name;

Exmaple:

int *a;

· Pointers and Arrays

· Pointers and Strings

· Pointer as function arguments

· Pointer too pointer

Example program:

· To add two numbers through variables and their pointers.

· To assign a pointer value to another variable.


5. 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 NULL 0

#define AND &

#define OR |

#define EQUALS ==

game_over = TRUE;

while( list_pointer != NULL )

................

MACROS

Macros are inline code which are 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 NULL

#define NL 10

#define SP 32

#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, day, year;

} DATE;

DATE todays_date; /* same as struct date todays_date */

ENUMERATED DATA TYPES

Enumerated data type variables can only assume values which have been previously

declared.

enum month { jan = 1, feb, mar, apr, may, jun, jul, aug, sep, oct, nov, dec };

enum month this_month;

this_month = feb;

In the above declaration, month is declared as an enumerated data type. It consists of a set of values, jan to dec. Numerically, jan is given the value 1, feb the value 2, and so on. The variable this_month is declared to be of the same type as month, then is assigned the value associated with feb. This_month cannot be assigned any values outside those specified in the initialization list for the declaration of month.

Example:

#include <stdio.h>

main()

{

char *pwest = "west",*pnorth = "north", *peast="east", *psouth = "south";

enum location { east=1, west=2, south=3, north=4};

enum location direction;

direction = east;

if( direction == east )

printf("Cannot go %s\n", peast);

}

The variables defined in the enumerated variable location should be assigned initial

values.

DECLARING VARIABLES TO BE REGISTER BASED

Some routines may be time or space critical. Variables can be defined as being register based by the following declaration,

register int index;

DECLARING VARIABLES TO BE EXTERNAL

Here variables may exist in separately compiled modules, and to declare that the

variable is external,

extern int move_number;

This means that the data storage for the variable move_number resides in another source

module, which will be linked with this module to form an executable program. In using a variable across a number of independently compiled modules, space should be allocated in only one module, whilst all other modules use the extern directive to access the variable.

NULL STATEMENTS

These are statements which do not have any body associated with them.

/* sums all integers in array a containing n elements and initializes */

/* two variables at the start of the for loop */

for( sum = 0, i = 0; i < n; sum += a[i++] )

;

/* Copies characters from standard input to standard output until EOF is reached */

for( ; (c = getchar ()) != EOF; putchar (c));

COMMAND LINE ARGUMENTS

It is possible to pass arguments to C programs when they are executed. The brackets which follow main are used for this purpose. argc refers to the number of arguments passed, and argv[] is a pointer array which points to each argument which is passed to main. A simple example follows, which checks to see if a single argument is supplied on the command line when the program is invoked.

#include <stdio.h>

main( int argc, char *argv[] )

{

if( argc == 2 )

printf("The argument supplied is %s\n", argv[1]);

else if( argc > 2 )

printf("Too many arguments supplied.\n");

else

printf("One argument expected.\n");

}

Note that *argv[0] is the name of the program invoked, which means that

*argv[1] is

a pointer to the first argument supplied, and *argv[n] is the last argument. If no arguments

are supplied, argc will be one. Thus for n arguments, argc will be equal to n + 1. The program is called by the command line, myprog argument1.


6. Brief call by value and call by reference in detail. (MAY 2009)

Call by value:

In call by value the value of the actual arguments are passed to the formal arguments and the operation is done on formal arguments.

Example program:

· To send two integer values using “call by value”.

Call by reference:

In call by reference the address of actual argument values are passed to formal argument values.

Example program:

· To send a value by reference to user defined function.


7. Discuss about function prototypes in detail. (or)

Explain about the different parameter passing methods with examples (JAN 2009)

· Function with arguments and return type.

· Function without arguments and return type.

· Function with arguments and no return type.

· Function without arguments and return type.


8. Define Structures. Explain structures in detail. (JAN 2009 / MAY 2009)

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.

Syntax:

struct struct-name

{

type variable 1; type variable 2; type variable n;

} structure_variables;

Example:

struct student

{

char name[25];

int rollno;

int m1,m2,m3,total;

float avg;

}s1,s2;

· Structure within structure

· Array of structures

· Pointers to structures

· Structures and functions

Example program:

· To define a structure and read the member variable values from user.

· To copy structure elements from one object to another object.


9. Define Union. Explain Union in detail. (JAN 2009)

Union is a collection of variables similar to structure. The union requires bytes that are equal to number of bytes required for the largest number.

Example:

union 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:

· Program to use structure within union. Display the contents of structure elements.


FOCP - FUNCTIONS AND POINTERS (Unit 5)–2 Marks with answers

FUNDAMENTALS OF COMPUTING & COMPUTER PROGRAMMING

UNIT V – 2 Marks

FUNCTIONS AND POINTERS


Handling of Character Strings – User-defined Functions – Definitions – Declarations - Call by reference – Call by value – Structures and Unions – Pointers – Arrays – The Preprocessor – Developing a C Program : Some Guidelines.


1. What is meant by Recursive function?

If a function calls itself again and again, then that function is called Recursive function.


2. What is an array?

An array is a group of similar data types stored under a common name. int a[10];

Here a[10] is an array with 10 values.


3. What is a Pointer? How a variable is declared to the pointer? (MAY 2009)

Pointer is a variable which holds the address of another variable.

Pointer Declaration:

datatype *variable-name;

Example:

int *x, c=5;

x=&a;


4. What are the uses of Pointers?

· Pointers are used to return more than one value to the function

· Pointers are more efficient in handling the data in arrays

· Pointers reduce the length and complexity of the program

· They increase the execution speed

· The pointers saves data storage space in memory


5. What is the output of the program?

main() junk(int i, int j)

{ {

int i=5;j=2; i=i*j; junk(i,j); j=i*j; printf(“\n %d %d”,i,j); }

}

Output:

1. 2

2.


6. What are * and & operators means?

‘*’ operator means ‘value at the address’

‘&’ operator means ‘address of’


7. What is meant by Preprocessor?

Preprocessor is the program, that process our source program before the compilation.


8. How can you return more than one value from a function?

A Function returns only one value. By using pointer we can return more than one value.


9. Is it possible to place a return statement anywhere in ‘C’ program?

Yes. The return statement can occur anywhere.


10. What are the main elements of an array declaration?

· Array name

· Type and

· Size


11. List the header files in ‘C’ language.

<stdio.h> contains standard I/O functions

<ctype.h> contains character handling functions

<stdlib.h> contains general utility functions

<string.h> contains string manipulation functions

<math.h> contains mathematical functions

<time.h> contains time manipulation functions


12. What are the steps involved in program development life cycle?

1. Program Design

2. Program Coding

3. Program Testing & Debugging


13. What are the types of errors occurred in C program?

1. Syntax errors

2. Runtime errors

3. Logical errors

4. Latent errors


14. What is testing?

Testing is the process of executing the program with sample or tested data.


15. What are the types of testing?

· Human testing

· Computer based testing


16. How do you define enumerated data type?

enum mar_status

{ single,married,widow }; enum mar_status person1,person2; person1=married;

Here the person1 is assigned to value zero.


17. What is meant by debugging?

Debugging is the process of locating and isolating the errors.


18. Specify any five syntax error messages.

· Missing semicolon

· Missing braces

· Missing quotes

· Improper comment characters

· Undeclared variables


19. What are the pre-processor directives?

· Macro Inclusion

· Conditional Inclusion

· File Inclusion


20. What is dynamic memory allocation?

Allocating the memory at run time is called as dynamic memory allocation.


21. What are the various dynamic memory allocation functions?

malloc() - Used to allocate blocks of memory in required size of bytes.

free() - Used to release previously allocated memory space.

calloc() - Used to allocate memory space for an array of elements.

realloac() - Used to modify the size of the previously allocated memory space.


22. What is the deference between declaring a variable and defining a variable?

· Declaring a variable means describing its type to the compiler but not allocating any space for it.

· Defining a variable means declaring it and also allocating space to hold the variable.

A variable Can also be initialized at the time it is defined. To put it simply, a declaration says to the compiler,

· “Some where in the program there will be a variable with this name, and this is the kind of data

· Type it is.” On the other hand, a definition says, “Right here is this variable with this name and

· This data type”. Note that a variable can be declared any number of times, but it must be defied

· Exactly once. For this reason, definitions do not belong in header files, where they might get #included into more than one place in a program.


23. Why does n++ execute than n=n+1?

The expression n++ requires a single machine instruction such as INR to carry

out the increment operation whereas; n+1 requires more instructions to carry out this operation.


24. Why is it necessary to give the size of an array in an array declaration?

When an array is declared, the compiler allocates a base address and reserves enough space in the memory for all the elements of the array. The size is required to allocate the required space. Thus, the size must be mentioned.


25. Where in memory are variables stored?

Variables can be stored in several places in memory, depending on their lifetime.

(1) Variables that are defined outside any function (whether of global or file static scope), and variables that are defined inside a function as static variables, exist for the lifetime of the program’s execution. These variables are stored in the data segment. The data segment is a fixed-size area in memory set aside for these variables.

(2) Variables that are the arguments functions exist only during the execution of that function. These variables are stored on the stack. The stack is an area of memory that starts out as small and

grows automatically up to some predefined limit.

(3) The third area is the one that does not actually store variables but can be used to store data pointed to by variables. Pointer variables that are assigned to the result of a call to the function malloc() contain the address of a dynamically allocated area of memory. This memory is in an area called the heap.


26. What is an heap memory?

The heap is another area that starts out as small and grows, but it grows only when

the programmer explicitly calls malloc() or other memory allocation functions, such as calloc(). The heap can share a memory segment with either the data segment or the stack, or

it can have its own segment, it all depends on the compiler options and operating system. The heap, like the stack, has a limit on how much it can grow, and the same rules apply as to how that limit is determined.


27. What is the difference between an array and pointer?

Difference between arrays and pointers are as follows.

Array

Pointer

1.Array allocates space

automatically.

2.It cannot be resized.

3.It cannot be reassigned.

4.Size of(array name) gives the number of bytes occupied by the array.

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.


27. What is the purpose of the function main()? (MAY 2009)

The function main () invokes other functions within it. It is the first function to be called when the program starts execution.

Some salient points about main() are as follows:

1. It is the starting function .

2. It returns an int value to the environment that called the program.

3. Recursive call is allowed for main() also.

4. It is a user-defined function.

5. Program exection ends when the closing brace of the function main() is reached.

6. It has two arguments (a) argument count and (b)argument vector (reprensents strings passed.)

7. Any user-defined name can also be used as parameters for main() instead of argc and argv


28. What is dangling pointer?

In C, a pointer may be used to hold the address of dynamically allocated memory.

After this memory is freed with the free() function, the pointer itself will still contain the address of the released block. This is referred to as a dangling pointer. Using the pointer in this state is a serious programming error. Pointer should be assigned NULL after freeing memory to avoid this bug.


29. 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 type.

Arrays can only be declared. There is no keyword for arrays.

An array name represents the address of the starting element.

An array cannot have bit fields.

A structure is a collection of data items of different data types.

Structures can be declared and defined. The deyword for structures is struct.

A structrure name is known as tag. It is a shorthand notation of the declaration.

A structure may contain bit fields.


30. Compare structures and unions.

Structure

Union

Every member has its own memory.

The keyword used is struct.

All members occupy separate memory location, hence different interpretations of the same memory location are not possible. Consumes more space compared to union.

All members use the same memory.

The keyword used is union. Different interpretations for the same memory location are possible.

Conservation of memory is possible.


31. Is it better to use a macro or a function?

Macros are more efficient (and faster) than function, because their corresponding code is inserted directly at the point where the macro is called. There is no overhead involved in using a macro like there is in placing a call to a function.

However, macros are generally small and cannot handle large, complex coding constructs. In cases where large, complex constructs are to handled, functions are more suited, additionally; macros are expanded inline, which means that the code is replicated for each occurrence of a macro.


32. 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.


33. What are the types of Arrays?

1.One-Dimensional Array

2. Two-Dimensional Array

3. Multi-Dimensional Array


34. What is the use of ‘\0’ character?

When declaring character arrays (strings), ‘\0’ (NULL) character is automatically added

at end. The ‘\0’ character acts as an end of character array.


35. Define sscanf() and sprint() functions.

The sscanf():

This function allows to read character from a character Array and writes to another array. Similar to scanf(), but instead of reading from standard input, it reads from an array.

The sprintf():

This function writes the values of any data type to an array of characters.


36. Define Strings.

Strings:

The group of characters, digit and symnbols 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’};

The character of a string are stored in contiguous memory locations as follows:

C

O

L

L

E

G

E

\0

1000 1001 1002 1003 1004 1005 1006 1007


37. What is the use of ‘typedef’’?

It is used to create a new data using the existing type. Syntax: typedef data type name;

Example:

typedef int hours: hours hrs;/* Now, hours can be used as new datatype */


38. What is ‘C’ functions? Why they are used?

A function is a self-contained block (or) a sub-program of one or more statements that

performs a special task when called. To perform a task repetitively then it is not necessary to re-write the particular block of the program again and again. The function defined can be used for any number of times to perform the task.


39. Differentiate library functions and User-defined functions.

Library Functions

User-defined Functions

a) Library functions are pre-defined set of

functions that are defined in C

libraries.

b) User can only use the function but cannot change (or) modify this function.

a) The User-defined functions are the

functions defined by the user according to his/her requirement.

b) User can use this type of function.

User can also modify this function.


40. What are the steps in writing a function in a program.

a) Function Declaration (Prototype declaration):

Every user-defined functions has to be declared before the main(). b) Function Callings:

The user-defined functions can be called inside any functions like main(), user-defined function, etc.

c) Function Definition:

The function definition block is used to define the user-defined functions with statements.


41. What is a use of ‘return’ Keyword?

The ‘return’ Keyword is used only when a function returns a value.


42. Give the syntax for using user-defined functions in a program.

Syntax for using user-defined functions in a program

Syntax:

function declaration; function definition;

main()                                                                main()

{                                                                          {

======

======

function calling;

(or)

function calling;

======

======

}

}

function definition;


43. Classify the functions based on arguments and return values.

Depending on the arguments and return values, functions are classified into four types.

a) Function without arguments and return values.

b) Function with arguments but without return values. c) Function without arguments but with return values. d) Function with arguments and return values.


44. Distinguish between Call by value Call by reference.

Call by value

Call by reference.

a) In call by value, the value of actual

agreements is passed to the formal arguments and the operation is done on formal arguments.

b) Formal arguments values are photocopies of actual arguments values.

c) Changes made in formal arguments valued do not affect the actual arguments values.

a) In call by reference, the address of

actual argurment values is passed to formal argument values.

b) Formal arguments values are pointers to the actual argument values.

c) Since Address is passed, the changes made in the both arguments values are permanent.

FOCP - INTRODUCTION TO C (Unit 4)–16marks with answers

FUNDAMENTALS OF COMPUTING & COMPUTER PROGRAMMING

UNIT IV – 16 Marks

INTRODUCTION TO C


1. Explain in detail about ‘C’ declarations and variables.

In C, lowercase and uppercase characters are very important. All commands in C

must be lowercase. The C programs starting point is identified by the word main( ). This informs the computer as to where the program actually starts.

The brackets that follow the keyword main indicate that there are no arguments supplied to this program.

The two braces, { and }, signify the begin and end segments of the program. The purpose of the statement

include <stdio.h> is to allow the use of the printf statement to provide program

output. Text to be displayed by printf() must be enclosed in double quotes. The program has only one statement printf("Programming in C is easy.\n");

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. Thus the program prints

Programming in C is easy.

and the cursor is set to the beginning of the next line. As we shall see later on, what follows the \ character will determine what is printed, ie, a tab, clear screen, clear line etc. Another important thing to remember is that all C statements are terminated by a semi-colon ;

General rules of ‘C’ language:

· program execution begins at main()

· keywords are written in lower-case

· statements are terminated with a semi-colon

· text strings are enclosed in double quotes

· C is case sensitive, use lower-case and try not to capitalize variable names

· \n means position the cursor on the beginning of the next line

· printf() can be used to display text to the screen

· The curly braces {} define the beginning and end of a program block.

BASIC STRUCTURE OF C PROGRAMS

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 */

/* CONSTANTS AND TYPES SECTION */

/* contains types and #defines */

/* GLOBAL VARIABLES SECTION */

/* any global variables declared here */

/* 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>

main()

{

printf(“Programming in C is easy.\n”); }

INITIALISING DATA VARIABLES AT DECLARATION TIME

In C, variables may be initialized with a value when they are declared. Consider

the following declaration, which declares an integer variable count which is initialized to

10. int count = 10;

SIMPLE ASSIGNMENT OF VALUES TO VARIABLES

The = operator is used to assign values to data variables. Consider the following statement, which assigns the value 32 an integer variable count, and the letter A to the character variable letter

count = 32;

letter = ‘A’

Variable Formatters

%d decimal integer

%c character

%s string or character array

%f float

%e double

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. Explain in detail about the constants, expressions and statements in ‘C’.

1. Constants: (with examples)

1. Numeric constants

a. Integer Constants

b. Real Constants

2. Character constants

a. Single character Constants b. String Constants

2. Expressions:

An expression represents a single data item, such as number or a character. Logical conditions that are true or false are represented by expressions.

Example: a = p – q / 3 + r * 2 - 1

3. Statements

· Assignment Statements – Definition and examples

· Null Statements – Definition and examples

· Block of statements – Definition and examples

· Expression statements – Definition and examples

· Declaration statements – Definition and examples


3. 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 variable called sum is,

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 variable called big is,

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.

#include < stdio.h >

main()

{

int sum;

float money; char letter; double pi;

sum = 10; /* assign integer value */ money = 2.21; /* assign float value */ letter = ‘A’; /* assign character value */ pi = 2.01E6; /* assign a double value */ printf(“value of sum = %d\n”, sum );

printf(“value of money = %f\n”, money ); printf(“value of letter = %c\n”, letter ); printf(“value of pi = %e\n”, pi );

}

Sample program output

value of sum = 10

value of money = 2.210000 value of letter = A

value of pi = 2.010000e+06


4. Describe the various types of operators in ‘C’ language along with its priority.

An ex pr e s s I o 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.

clip_image001[5]

1. ARITHMETIC OPERATORS:

The symbols of the arithmetic operators are:-

Example:

#include <stdio.h>

main()

{

int sum = 50; float modulus; modulus = sum % 10;

printf(“The %% of %d by 10 is %f\n”, sum, modulus);

}

PRE/POST INCREMENT/DECREMENT OPERATORS

PRE means do the operation first followed by any assignment operation. POST

means do the operation after any assignment operation. Consider the following statements ++count; /* PRE Increment, means add one to count */ count++; /* P OST Increment, means add one to count */

Example:

#include <stdio.h>

main()

{

int count = 0, loop;

loop = ++count; /* same as count = count + 1; loop = count; */

printf(“loop = %d, count = %d\n”, loop, count);

loop = count++; /* same as loop = count; count = count + 1; */

printf(“loop = %d, count = %d\n”, loop, count);

}

If the operator precedes (is on the left hand side) of the variable, the operation is performed first, so the statement

loop = ++count;

really means increment count first, then assign the new value of count to loop.

2. THE RELATIONAL OPERATORS

These allow the comparison of two or more variables.

= = equal to

! = not equal

< less than

< = less than or equal to

> greater than

> = greater than or equal to

Example:

#include <stdio.h>

main() /* Program introduces the for statement, counts to ten */

{

int count;

for( count = 1; count <= 10; count = count + 1 )

printf(“%d “, count );

printf(“\n”);

}

3. LOGICAL OPERATORS (AND, NOT, OR, EOR) Combining more than one condition

These allow the testing of more than one condition as part of selection

statements. The symbols are

LOGICAL AND &&

Logical and requires all conditions to evaluate as TRUE (non-zero).

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 eor will be excuted if either condition is TRUE, but NOT if they are all true.

The following program uses an if statement with logical AND to validate the users input to be in the range 1-10.

#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 ) || (number > 10) ){

printf(“Number is outside range 1-10. Please re-enter\n”);

valid = 0;

}

else

valid = 1;

}

printf(“The number is %d\n”, number );

} Example: NEGATION

#include <stdio.h>

main()

{

int flag = 0;

if( ! flag ) {

printf(“The flag is not set.\n”);

flag = ! flag;

}

printf(“The value of flag is %d\n”, flag);

}

Example:

Consider where a value is to be inputted from the user, and checked for validity to be within a certain range, lets say between the integer values 1 and 100.

#include <stdio.h>

main()

{

int number;

int valid = 0;

while( valid == 0 ) {

printf(“Enter a number between 1 and 100”);

scanf(“%d”, &number );

if( (number < 1) || (number > 100) ) printf(“Number is outside legal range\n”); else

valid = 1;

}

printf(“Number is %d\n”, number );

}

4. THE CONDITIONAL EXPRESSION OPERATOR or TERNARY OPERATOR

This conditional expression operator takes THREE operators. The two symbols used to denote this operator are the ? and the :. The first operand is placed before the ?, the second operand between the ? and the :, and the third after the :. The general format is,

condition ? expression1 : expression2.

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; If x is less than zero then s = -1

If x is greater than zero then s = x * x

Example:

#include <stdio.h>

main()

{

int input;

printf(“I will tell you if the number is positive, negative or zero!”\n”);

printf(“please enter your number now-à”);

scanf(“%d”, &input );

(input < 0) ? printf(“negative\n”) : ((input > 0) ? printf(“positive\n”) :

printf(“zero\n”));

}

5. BIT OPERATIONS

clip_image002[5]

C has the advantage of direct bit manipulation and the operations available are,

Example:

/* Example program illustrating << and >> */

#include <stdio.h>

main()

{

int n1 = 10, n2 = 20, I = 0;

I = n2 << 4; /* n2 shifted left four times */

printf(“%d\n”, i);

I = n1 >> 5; /* n1 shifted right five times */

printf(“%d\n”, i);

}

Example:

/* Example program using EOR operator */

#include <stdio.h>

main()

{

int value1 = 2, value2 = 4;

value1 ^= value2;

value2 ^= value1;

value1 ^= value2;

printf(“Value1 = %d, Value2 = %d\n”, value1, value2);

}

Example:

/* Example program using AND operator */

#include <stdio.h>

main()

{

int loop;

for( loop = ‘A’; loop <= ‘Z’; loop++ )

printf(“Loop = %c, AND 0xdf = %c\n”, loop, loop & 0xdf);

}


5. Explain about the various decision making statements in ‘C’ language.

(JAN 2009/FEB2010)

1. IF STATEMENTS

DECISION MAKING

The if statements allows branching (decision making) depending upon the value or state of variables. This allows statements to be executed or skipped, depending upon decisions.

The basic format is,

if( expression )

program statement;

Example:

if( students < 65 )

++student_count;

In the above example, the variable student_count is incremented by one only if the value of the integer variable students is less than 65. The following program uses an if statement to validate the users input to be in the range 1-10.

#include <stdio.h>

main()

{

int number;

int valid = 0;

while( valid == 0 ) {

printf(“Enter a number between 1 and 10 à”);

scanf(“%d”, &number);

/* assume number is valid */

valid = 1;

if( number < 1 ) {

printf(“Number is below 1. Please re-enter\n”);

valid = 0;

}

if( number > 10 ) {

printf(“Number is above 10. Please re-enter\n”);

valid = 0;

}

}

printf(“The number is %d\n”, number );

}

2. IF ELSE

The general format for these are,

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 = 0;

}

else if( number > 10 ) {

printf(“Number is above 10. Please re-enter\n”);

valid = 0;

}

else

valid = 1;

}

printf(“The number is %d\n”, number );

}

This program is slightly different from the previous example in that an else clause is used to set the variable valid to 1. In this program, the logic should be easier to follow.

3. NESTED IF ELSE

/* Illustates nested if else and multiple arguments to the scanf function. */

Example:

#include <stdio.h>

main()

{

int invalid_operator = 0;

char operator;

float number1, number2, result;

printf(“Enter two numbers and an operator in the format\n”);

printf(“ number1 operator number2\n”);

scanf(“%f %c %f”, &number1, &operator, &number2);

if(operator == ‘*’)

result = number1 * number2;

else if(operator == ‘/’)

result = number1 / number2;

else if(operator == ‘+’)

result = number1 + number2;

else if(operator == ‘-‘)

result = number1 – number2;

else

invalid_operator = 1;

if( invalid_operator != 1 )

printf(“%f %c %f is %f\n”, number1, operator, number2, result );

else

printf(“Invalid operator.\n”);


6. Write short notes on the following: (JAN 2009)

‘for’ loop

‘while’ loop

‘dowhile’ loop

‘Switch case ‘ (MAY 2009/FEB 2009/FEB 2010)

BRANCHING AND LOOPING

1. ITERATION, FOR LOOPS

The basic format of the for statement is,

for( start condition; continue condition; re-evaulation )

program statement;

/* sample program using a for statement */

#include <stdio.h>

main() /* Program introduces the for statement, counts to ten */

{

int count;

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; initialized the value of count to 1.

The for loop continues with the condition count <= 10; evaluates as TRUE. As

the variable count has just been initialized 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.

2. 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 while */

#include <stdio.h>

main()

{

int loop = 0;

while( loop <= 10 ) {

printf(“%d\n”, loop);

++loop;

}

}

The above program uses a while loop to repeat the statements

printf(“%d\n”,loop); ++loop; the value of the variable loop is less than or

equal to 10.

3. 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 = value % 10; printf(“%d”, r_digit); value = value / 10;

} while( value != 0 );

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 digit 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.

4. 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;

}

The 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 two numbers à”); scanf(“%d %d”, &numb1, &numb2 ); printf(“enter in choice\n”); printf(“1=addition\n”); printf(“2=subtraction\n”);

scanf(“%d”, &menu );

switch( menu ) {

case 1: total = numb1 + numb2; break;

case 2: total = numb1 – numb2; break;

default: printf(“Invalid option 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. Explain briefly about the input and output function in ‘C’. (MAY 2009/FEB 2009)

1 printf ():

MANAGING INPUT AND OUTPUT OPERATORS

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 modifiers, and

for the present the \ followed by the n character represents a newline character.

Example:

#include <stdio.h>

main()

{

printf(“Programming in C is easy.\n”);

printf(“And so is Pascal.\n”);

}

@ Programming in C is easy. And so is Pascal.

FORMATTERS for printf are, Cursor Control Formatters

\n newline

\t tab

\r carriage return

\f form feed

\v vertical tab

2. Scanf ():

Scanf () is a function in C which allows the programmer to accept input from a

keyboard.

Example:

#include <stdio.h>

main() /* program which introduces keyboard input */

{

int number;

printf(“Type in a number \n”);

scanf(“%d”, &number);

printf(“The number you typed was %d\n”, number);

}

FORMATTERS FOR scanf()

The following characters, after the % character, in a scanf argument, have the

following effect.

D read a decimal integer o read an octal value

x read a hexadecimal value h read a short integer

l read a long integer

f read a float value

e read a double value

c read a single character

s read a sequence of characters

[...] Read a character string. The characters inside the brackets

3. ACCEPTING SINGLE CHARACTERS FROM THE KEYBOARD Getchar, Putchar

getchar() gets a single character from the keyboard, and putchar() writes a single character from the keyboard.

Example:

The following program illustrates this,

#include <stdio.h>

main()

{

int i;

int ch;

for( i = 1; i<= 5; ++i ) { ch = getchar(); putchar(ch);

}

}

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.


8. (a) Describe in detail about type conversions in ‘C’ with example.

(b) Define delimiters. List them. Give an example program using various delimiters.


9. Explain the following:

· Keywords

· Identifiers

· C character set

· Constant and Volatile variables.


10. Explain the following:

· break statement with example program

· continue statement with example program

· goto statement with example program

FOCP–Introduction to C (Unit 4)–2 marks with answers

FUNDAMENTALS OF COMPUTING & COMPUTER PROGRAMMING

UNIT IV

INTRODUCTION TO C


Overview of C – Constants, Variables and Data Types – Operators and Expressions– Managing Input and Output operators – Decision Making - Branching and Looping.


2 MARKS


1. 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


2. 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.


3. What is an Operator and Operand?

An operator is a symbol that specifies an operation to be performed on operands.

Example: *, +, -, / are called arithmetic operators.

The data items that operators act upon are called operands.

Example: a+b; In this statement a and b are called operands.


4. What is Ternary operators or Conditional operators?

Ternary operators is a conditional operator with symbols ? and :

Syntax: variable = exp1 ? exp2 : exp3

If the exp1 is true variable takes value of exp2. If the exp2 is false, variable takes the value of exp3.


5. What are the Bitwise operators available in ‘C’?

& - Bitwise AND

| - Bitwise OR

~ - One’s Complement

>> - Right shift

<< - Left shift

^ - Bitwise XOR are called bit field operators

Example: k=~j; where ~ take one’s complement of j and the result is stored in k.


6. What are the logical operators available in ‘C’?

The logical operators available in ‘C’ are

&& - Logical AND

|| - Logical OR

! - Logical NOT


7. What is the difference between Logical AND and Bitwise AND?

Logical AND (&&): Only used in conjunction with two expressions, to test more than one condition. If both the conditions are true the returns 1. If false then return

0.

AND (&): Only used in Bitwise manipulation. It is a unary operator.


8. What is the difference between ‘=’ and ‘==’ operator?

Where = is an assignment operator and == is a relational operator.

Example:

while (i=5) is an infinite loop because it is a non zero value and while (i==5) is true only when i=5.


9. What is type casting?

Type casting is the process of converting the value of an expression to a particular data type.

Example:

int x,y;

c = (float) x/y; where a and y are defined as integers. Then the result of x/y is converted into float.


10. What is conversion specification?

The conversion specifications are used to accept or display the data using the

INPUT/OUTPUT statements.


11. What is the difference between ‘a’ and “a”?

‘a’ is a character constant and “a” is a string.


12. What is the difference between if and while statement?

if

while

(i) It is a conditional statement

(i) It is a loop control statement

(ii) If the condition is true, it executes

some statements.

(ii) Executes the statements within the

while block if the condition is true.

(iii) If the condition is false then it stops the execution the statements.

(iii) If the condition is false the control is

transferred to the next statement of the loop.


13. What is the difference between while loop and do…while loop?

In the while loop the condition is first executed. If the condition is true then it executes the body of the loop. When the condition is false it comes of the loop. In the do…while loop first the statement is executed and then the condition is checked. The do…while loop will execute at least one time even though the condition is false at the very first time.


14. What is a Modulo Operator?

‘%’ is modulo operator. It gives the remainder of an integer division

Example:

a=17, b=6. Then c=%b gives 5.


15. How many bytes are occupied by the int, char, float, long int and double?

int - 2 Bytes

char - 1 Byte float - 4 Bytes long int - 4 Bytes double - 8 Bytes


16. What are the types of I/O statements available in ‘C’?

There are two types of I/O statements available in ‘C’.

· Formatted I/O Statements

· Unformatted I/O Statements


17. What is the difference between ++a and a++?

++a means do the increment before the operation (pre increment) a++ means do the increment after the operation (post increment) Example:

a=5;

x=a++; /* assign x=5*/

y=a; /*now y assigns y=6*/

x=++a; /*assigns x=7*/


18. What is a String?

String is an array of characters.


19. What is a global variable?

The global variable is a variable that is declared outside of all the functions. The

global variable is stored in memory, the default value is zero. Scope of this variable is available in all the functions. Life as long as the program’s execution doesn’t come to an end.


20. What are the Escape Sequences present in ‘C’

\n - New Line

\b - Backspace

\t - Form feed

\’ - Single quote

\\ - Backspace

\t - Tab

\r - Carriage return

\a - Alert

\” - Double quotes


21. Construct an infinite loop using while?

while (1)

{

}

Here 1 is a non zero, value so the condition is always true. So it is an infinite loop.


22. What will happen when you access the array more than its dimension?

When you access the array more than its dimensions some garbage value is

stored in the array.


23. Write the limitations of getchar( ) and sacnf( ) functions for reading strings (JAN 2009)

getchar( )

To read a single character from stdin, then getchar() is the appropriate.

scanf( )

scanf( ) allows to read more than just a single character at a time.


24. What is the difference between scanf() and gets() function?

In scanf() when there is a blank was typed, the scanf() assumes that it is an end.

gets() assumes the enter key as end. That is gets() gets a new line (\n) terminated string of characters from the keyboard and replaces the ‘\n’ with ‘\0’.


25. What is a Structure?

Structure is a group name in which dissimilar data’s are grouped together.


26. What is meant by Control String in Input/Output Statements?

Control Statements contains the format code characters, specifies the type of data that the user accessed within the Input/Output statements.


27. What is Union?

Union is a group name used to define dissimilar data types. The union occupies only the maximum byte of the data type. If you declare integer and character, then the union occupies only 2 bytes, whereas structure occupies only 3 bytes.


28. What is the output of the programs given below?

main() main()

{ {

float a; float a;

int x=6, y=4; int x=6, y=4;

a=x\y; a=(float) x\y;

printf(“Value of a=%f”, a); printf(“Value of a=%f”,a);

} }

Output: Output:

1. 1.500000


29. Declare the Structure with an example?

struct name

{

char name[10];

int age;

float salary;

} e1, e2;


30. Declare the Union with an example?

union name

{

char name[10];

int age;

float salary;

} e1, e2;


31. What is the output of the following program when, the name given with spaces?

main()

{

char name[50]; printf(“\n name\n”); scanf(“%s, name); printf(“%s”,name);

}

Output:

Lachi (It only accepts the data upto the spaces)


32. What is the difference between while(a) and while(!a)?

while(a) means while(a!=0)

while(!a) means while(a==0)


33. Why we don’t use the symbol ‘&’ symbol, while reading a String through scanf()?

The ‘&’ is not used in scanf() while reading string, because the character variable

itself specifies as a base address.

Example: name, &name[0] both the declarations are same.


34. What is the difference between static and auto storage classes?

Static

Auto

Storage

Initial value

Scope

Life

Memory

Zero

Local to the block in which the variables is defined

Value of the variable persists

between different function calls.

Memory

Garbage value

Local to the block in which the variable is defined.

The block in which the

variable is defined.


35. What is the output of the program?

main()

increment()

{

{

increment();

static int i=1;

increment();

printf(“%d\n”,i)

increment();

}

i=i+1;

}

OUTPUT:

1 2

3


36. 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.


37. List out some of the rules used for ‘C’ programming.

· All statements should be written in lower case letters. Upper case letters are only for

symbolic constants.

· Blank spaces may be inserted between the words. This improves the readability of statements.

· It is a free-form language; we can write statements anywhere between ‘{‘ and ‘}’. a = b + c;

d = b*c;

(or)

a = b+c; d = b*c;

· Opening and closing braces should be balanced.


38. Define delimiters in ‘C’.

Delimiters

Use

:

;

( ) [ ]

{ }

#

,

Colon

Semicolon Parenthesis Square Bracket Curly Brace Hash

Comma

Useful for label

Terminates Statement

Used in expression and functions

Used for array declaration Scope of statement Preprocessor directive Variable Separator


39. What do you mean by variables in ‘C’?

· A variable is a data name used for storing a data value.

· Can be assigned different values at different times during program execution.

· Can be chosen by programmer in a meaningful way so as to reflect its function in the program.

· Some examples are: Sum percent_1 class_total


40. List the difference between float and double datatype.

S No

Float

Double Float / Double

1

2

3

4

Occupies 4 bytes in memory

Range : 3.4 e-38 to 3.8e+38

Format Specifier: % f

Example : float a;

Occupies 8 bytes in memory

Range : 1.7 e-308 to 1.7e+308

Format Specifier: % lf

Example : double y;

There exists long double having a range of 3.4 e -4932 to 3.4 e +4932 and occupies 10 bytes in memory.

Example: long double k;


41. Differentiate break and continue statement

S No

break

continue

1

2

3

Exits from current block / loop

Control passes to next statement

Terminates the program

Loop takes next iteration

Control passes to beginning of loop

Never terminates the program


42. List the types of operators.

S No

Operators Types

Symbolic Representation

1

2

3

4

5

6

7

8

Arithmetic operators

Relational operators

Logical operators

Increment and Decrement operators

Assignment operators Bitwise operators Comma operator Conditional operator

= , - , * , / and %

> , < , == , >=, <= and !=

&& , || and !

++ and –

= , + = , - = , * = , / = , ^ = , ; = , & =

& , | , ^ , >> , << , and ~

,

? :


43. Distinguish between while..do and do..while statement in C. (JAN 2009)

While..DO                                                    DO..while

(i) Executes the statements within the

while block if only the condition is true.

(i) Executes the statements within the

while block at least once.

(ii) The condition is checked at the

starting of the loop

(ii) The condition is checked at the end of

the loop


44. Compare switch( ) and nestedif statement.

S No

switch( ) case

nested if

1

2

3

4

Test for equality ie., only constant

values are applicable.

No two case statements in same switch.

Character constants are automatically converted to integers.

In switch( ) case statement nested if can be used.

It can equate relational (or)

logical expressions.

Same conditions may be repeated for a number of times.

Character constants are automatically converted to integers.

In nested if statement switch case can be used.


45. Distinguish Increment and Decrement operators.

S No

Increment ++

Decrement --

1

2

3

4

Adds one to its operand

Equivalent x = x + 1

Either follow or precede operand

Example : ++x; x++;

Subtracts one from its operand

Equivalent x = x - 1

Either follow or precede operand

Example : --x; x--;


46. Give the syntax for the ‘for’ loop statement

for (Initialize counter; Test condition; Increment / Decrement)

{

statements;

}

· Initialization counter sets the loop to an initial value. This statement is executed only once.

· The test condition is a relational expression that determines the number of iterations desired or it determines when to exit from the loop. The ‘for’ loop continues to execute as long as conditional test is satisfied. When condition becomes false, the control of program exists the body of the ‘for’ loop and executes next statement after the body of the loop.

· The increment / decrement parameter decides how to make changes in the loop.

· The body of the loop may contain either a single statement or multiple statements.


47. What is the use of sizeof( ) operator?

· The sizeof ( ) operator gives the bytes occupied by a variable.

· No of bytes occupied varies from variable to variable depending upon its data types.

Example:

int x,y;

printf(“%d”,sizeof(x));

Output:

2


48. What is a loop control statement?

Many tasks done with the help of a computer are repetitive in nature. Such tasks

can be done with loop control statements.


49. What are global variable in ‘C’?

· This section declares some variables that are used in more than one function. such

variable are called as global variables.

· It should be declared outside all functions.


50. Write a program to swap the values of two variables (without temporary variable).

#include <stdio.h>

#include <conio.h>

void main( )

{

int a =5; b = 10;

clrscr( );

prinf(“Before swapping a = %d b = %d “, a , b);

a = a + b; B = a – b;

a = a – b;

prinf(“After swapping a = %d b = %d”, a,b);

getch( );

}

Output:

Before swapping a = 5 b = 10

After swapping a = 10 b = 5


51. Write short notes about main ( ) function in ’C’ program. (MAY 2009)

· Every C program must have main ( ) function.

· All functions in C, has to end with ‘( )’ parenthesis.

· It is a starting point of all ‘C’ programs.

· The program execution starts from the opening brace ‘{‘ and ends with closing brace

‘}’, within which executable part of the program exists.