Sunteți pe pagina 1din 17

Programming C Answer

Q-1 a) Convert the binary no 1101101111110101 to hex.


(1101101111110101)2 = (DBF5)16

b)What is type casting in C? Give one example.


Type casting is a way to convert a variable from one data type to another data type. For example, if you want to
store a long value into a simple integer then you can typecast long to int. You can convert values from one type
to another explicitly using the cast operator. There are two types of type casting in c language that are Implicit
conversions and Explicit Conversions. In this article, we also learn about the difference between type casting
and type conversions.
# include<stdio.h>
void main()
{
float x;
x=(float)7/5;
printf(“%f”,x);
}

c)

d)What is the purpose of external/global variable? What is its scope ?


An external variable can be accessed by all the functions in all the modules of a program. It is a global
variable. For a function to be able to use the variable, a declaration or the definition of the external
variable must lie before the function definition in the source code.

In C, a global variable declared with the static specifier is said to have file scope. Avariable with file scope is
visible from its declaration point to the end of the file. Here the file refers to the program file that contains the
source code.

e) Define Bit-fields.
Bit field can be used to reduce memory consumption when it is known that only some bits would be used for a
variable. Bit fields allow efficient packaging of data in the memory.
As we know, integer takes two bytes(16-bits) in memory. Some times we need to store value that takes less
then 2-bytes. In such cases, there is wastages of memory. For example, if we use a variable temp to store value
either 0 or 1. In this case only one bit of memory will be used rather then 16-bits. By using bit field, we can
save lot of memory.

f)Differentiate call by value and call by reference.


Call By Value: In this parameter passing method, values of actual parameters are copied to function’s formal
parameters and the two types of parameters are stored in different memory locations. So any changes made
inside functions are not reflected in actual parameters of caller.
Call by Reference: Both the actual and formal parameters refer to same locations, so any changes made inside
the function are actually reflected in actual parameters of caller.

g) How to increment the value of a variable using pointer? Give example.


We can increment pointers by using ++point. However, the computer will NOT simply add 1 to the pointer’s
address.
When you increment a pointer, the computer will jump to the next block of memory. If you are using
an int variable, which takes up 2 bytes of memory, then the computer will increment by2, to reach the next
block.
If you are using a long variable, which takes up 4 bytes of memory, then the computer will increment
by 4, to reach the next block.
h) What is the use of atoi()?

atoi() function in C language converts string data type to int data type.
Syntax: int atoi (const char * str);

i)Write different modes in file handling.


1. Creation of a new file (fopen with attributes as “a” or “a+” or “w” or “w++”)
2. Opening an existing file (fopen)
3. Reading from file (fscanf or fgetc)
4. Writing to a file (filePointerrintf or filePointeruts)
5. Moving to a specific location in a file (fseek, rewind)
6. Closing a file (fclose)

j)What is macro and how do you use it?


The C preprocessor is a macro preprocessor (allows you to define macros) that transforms your program before
it is compiled. These transformations can be inclusion of header file, macro expansions etc.
All preprocessing directives begins with a # symbol. For example,

#define PI 3.14

Q-2 a)Discuss the structure of C programming.


Basic Structure of a C program contains following sections,

Documentation Section
Link Section
Definition Section
Global Declaration Section
main()
{
Declaration Section
Executable part
}
Subprogram section
Function 1
Function 2
.
.
function n

- The Documentation Section consists of a set of comment lines giving the name of the program and other
details.
-The Link Section provides instructions to the compiler to link functions from the system library. C program
depends upon some header files for function definition that are used in the program. Each header file has
extension ‘.h’. The header files are included at the beginning of the program in the C language. These files
should be included using #include directive as given below
Example:
#include

(This will find header file in standard directory)


or
#include”stdio.h”( This will find header file in Current and Standard directory)
-The Definition Section defines all symbolic constants.
-The Global Declaration Section: There are some variables and those variables are declared in this section that
is outside of all functions.
-main() function: Every C program must have one main() function section. int main(void): This is the function
definition for main().Parenthesis followed to main is to tell the user again that main() is a function. Int
main(void) function return an integer.
void main(void): This function takes no arguments and return nothing.
void main(): This function returns nothing and takes no arguments. The program contains statements that are
enclosed within the braces. The opening braces “{“ and closing braces “}”.
In these two braces main() function contains two parts,
declaration and executable part. It is user defined function. The Opening braces sometimes called logical start
and Closing braces known as logical end of the program.
-Declaration Part declares all the variables used in the executable part. There should be at least one statement
in the executable partwhich contains instructions to perform certain task. The declaration and executable part
must appear between the opening and closing braces. All statements in the declaration part should end with the
semicolon.
-The Subprogram Section contains all the user defined functions that are called in the main function.

b)What is the difference between flowchart and algorithm? Draw the flowchart to find the sum
of n natural numbers.

Flowchart Algorithm

Block by block information diagram Step by step instruction representing the

representing the data flow. process of any solution.

Easy to understand by any person. Bit difficult for the layman.

It uses symbols for processes and I/O. No symbols are used, completely in text.

Have some rule to create. No hard and fast rule.

Difficult to debug errors. Easy to debug errors.

It is easy to make flowchart. It is difficult to write algorithm as compared

to flowchart.
c)Is switch case is better than nested if else? Justify your answer. Write a C program to check
whether an alphabet is vowel or consonant using switch case.
A switch statement is usually more efficient than a set of nested ifs. Deciding whether to use if-then-else
statements or a switch statement is based on readability and the expression that the statement is testing.

#include <stdio.h>

int main()
{
char ch;

printf("Enter a character: ");


scanf("%c",&ch);

//condition to check character is alphabet or not


if((ch>='A' && ch<='Z') || (ch>='a' && ch<='z'))
{
//check for VOWEL or CONSONANT
switch(ch)
{
case 'A':
case 'E':
case 'I':
case 'O':
case 'U':
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
printf("%c is a VOWEL.\n",ch);
break;
default:
printf("%c is a CONSONANT.\n",ch);
}
}
else
{
printf("%c is not an alphabet.\n",ch);
}

return 0;
}

d) What is an array? Explain the declaration and initialization of one and two dimensional arrays with
example.

Arrays a kind of data structure that can store a fixed-size sequential collection of elements of the same type.
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.
Arrays are of two types:
1. One-dimensional arrays
2. Multidimensional arrays

Declaration of one dimensional array:


double balance[5];

Initialization of one dimensional array:


Double balance[5]={50.0,10.2,23.5,100.0,2.5}

#include <stdio.h>
int main ()
{
int arr[5] = {1, 2, 3, 4, 5}; // array of 5 integers
for (int i = 0; i < 5; i++)
{
printf("value at %d location is: %d\n", i, arr[i]);
}
return 0;
}

Declaration of two dimensional array:


int balance[4] [3];

Initialization of two dimensional array:


int balance[4] [3]={{2,3,4},{4,5,6},{7,3,6},{6,3,2}}
1. #include<stdio.h>
2. int main(){
3. int i=0,j=0;
4. int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
5. //traversing 2D array
6. for(i=0;i<4;i++){
7. for(j=0;j<3;j++){
8. printf("arr[%d] [%d] = %d \n",i,j,arr[i][j]);
9. }//end of j
10. }//end of i
11. return 0;
12. }

e)Write a C program to read n unsorted numbers to an array of size n and pass the address of
this array to a function to sort the numbers in ascending order using bubble sort technique.

#include<stdio.h>
#include<conio.h>
void sort(int *a,int n);
void main()
{
int a[20];
int n,i;
clrscr();
printf("Program for BUBBLE SORT\n");
printf("Enter the Number of ELements you want in Array\n");
scanf("%d",&n);
printf("Enter the Elements in UNSOTED ARRAY\n");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
printf("The Unsorted ARRAY is:\n");
for(i=0;i<n;i++)
{
printf("%d\t",a[i]);
}
printf("\n");
sort(&a,n);
getch();
}
void sort(int *a,int n)
{
int i,temp,j;
for(i=1;i<n;i++)
{
for(j=0;j<n-i;j++)
{
if((*a+j)==(*a+j+1))
{
temp=*a+j;
*a+j=*a+j+1;
*a+j+1=temp;
}
}
}
}
f) Discuss different storage classes with example.

A storage class defines the scope (visibility) and life-time of variables and/or functions within a C Program.
They precede the type that they modify. We have four different storage classes in a C program −
 auto
 register
 static
 extern
The auto Storage Class
The auto storage class is the default storage class for all local variables.
{
int mount;
auto int month;
}

The register Storage Class


The register storage class 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 can't have
the unary '&' operator applied to it (as it does not have a memory location).

{
register int miles;
}

The static Storage Class


The static storage class instructs the compiler to keep a local variable in existence during the life-time of the
program instead of creating and destroying it each time it comes into and goes out of scope. Therefore, making
local variables static allows them to maintain their values between function calls.

#include <stdio.h>
/* function declaration */
void func(void);
static int count = 5; /* global variable */
main() {
while(count--) {
func();
}
return 0;
}
/* function definition */
void func( void ) {
static int i = 5; /* local static variable */
i++;
printf("i is %d and count is %d\n", i, count);
}

The extern Storage Class


The extern storage class is used to give a reference of a global variable that is visible to ALL the program files.
When you use 'extern', the variable cannot be initialized however, it points the variable name at a storage
location that has been previously defined.
First File: main.c

#include <stdio.h>
int count ;
extern void write_extern();

main() {
count = 5;
write_extern();
}

Second File: support.c

#include <stdio.h>
extern int count;
void write_extern(void) {
printf("count is %d\n", count);
}

g)What is meant by dynamic memory allocation? State its advantages. Differentiate between
malloc and calloc.

The concept of dynamic memory allocation in c language enables the C programmer


to allocate memory at runtime. Dynamic memory allocation in c language is possible by
4 functions of stdlib.h header file.

1. malloc()
2. calloc()
3. realloc()
4. free()
Advantage:- The main advantage of using dynamic memory allocation is preventing the wastage of
memory. This is because when we use static memory allocation, a lot of memory is wasted because all the
memory allocated cannot be utilised. Thus dynamic memory allocation helps us to allocate memory as and when
required and thus saves memory.
->In static memory allocation, if we allocate 1000 memory locations as int name[1000]; While running the
program only half of this may be used. The rest is unused and idle. It is a wastage of memory.
->If we want to change the size of the array in the program, it is possible by reediting the program. It is a
time consuming process.
In dynamic memory allocation the above two problems won't occur because, the memory space for variables is
allocated only during execution.

malloc calloc
The name malloc stands for memory allocation. The name calloc stands for contiguous allocation.
void *malloc(size_t n) returns a pointer to n bytes of void *calloc(size_t n, size_t size)returns a pointer to
uninitialized storage, or NULL if the request cannot enough free space for an array of n objects of the
be satisfied. If the space assigned by malloc() is specified size, or NULL if the request cannot be
overrun, the results are undefined. satisfied. The storage is initialized to zero.
malloc() takes one argument that is, number of bytes. calloc() take two arguments those are: number of
blocks and size of each block.
syntax of malloc(): syntax of calloc():
void *malloc(size_t n); void *calloc(size_t n, size_t size);
Allocates n bytes of memory. If the allocation Allocates a contiguous block of memory large enough
succeeds, a void pointer to the allocated memory is to hold n elements of sizebytes each. The allocated
returned. Otherwise NULL is returned. region is initialized to zero.
malloc is faster than calloc. calloc takes little longer than mallocbecause of the
extra step of initializing the allocated memory by zero.
However, in practice the difference in speed is very
tiny and not recognizable.
h)Define structure and union. Union consumes less memory than structure. True or false?
Justify your answer with example.

Structure:- A structure is a user defined data type in C. A structure creates a data type that can be used to group
items of possibly different types into a single type. To define a structure, you must use the struct statement. The struct
statement defines a new data type, with more than one member.

struct [structure tag] {

member definition;
member definition;
...
member definition;
} [one or more structure variables];

Union:- A union is a special data type available in C that allows to store different data types in the same
memory location. To define a union, you must use the union statement in the same way as you did while
defining a structure. The union statement defines a new data type with more than one member for your program.

union [union tag] {


member definition;
member definition;
...
member definition;
} [one or more union variables];

Yes Union consumes less memory than structure because, the size of the structure is sum of the size of each
member in the struchture .but size of the union is size of Largest member in the union because union members
are overlaps on each other in memory. If we declare two structure variables,Both variables are stored in different
location
but union stored in same location.

i)Distinguish between break and continue with suitable example.


Difference Between break and continue
break continue
A break can appear in both switch and loop A continue can appear only in loop (for, while, do) statements.
(for, while, do) statements.
A break causes the switch or loop A continue doesn't terminate the loop, it causes the loop to go to
statements to terminate the moment it is the next iteration. All iterations of the loop are executed even
executed. Loop or switch ends abruptly if continue is encountered. The continue statement is used to skip
when break is encountered. statements in the loop that appear after the continue.
The break statement can be used in The continue statement can appear only in loops. You will get an
both switch and loop statements. error if this appears in switch statement.
When a break statement is encountered, it When a continue statement is encountered, it gets the control to
terminates the block and gets the control the next iteration of the loop.
out of the switch or loop.
A break causes the innermost enclosing A continue inside a loop nested within a switch causes the next
loop or switch to be exited immediately. loop iteration.

Example using break


The following function, trim, removes trailing blanks, tabs and newlines from the end of a string, using a break
to exit from a loop when the rightmost non-blank, non-tab, non-newline is found.

/* trim: remove trailing blanks, tabs, newlines */


int trim(char s[])
{
int n;
for (n = strlen(s)-1; n >= 0; n--)
if (s[n] != ' ' && s[n] != '\t' && s[n] != '\n')
break;
s[n+1] = '\0';
return n;
}

Example using continue


As an example, the following piece of code sums up the non-negative elements in the array a; negative values
are skipped.

/* sum up non-negative elements of an array */

#include <stdio.h>

int main()
{
int a[10] = {-1, 2, -3, 4, -5, 6, -7, 8, -9, 10};
int i, sum = 0;
for (i = 0; i < 10; i++)
{
if (a[i] < 0) /* skip negative elements */
continue;
sum += a[i]; /* sum positive elements */
}
printf("Sum of positive elements: %d\n", sum);
}

OUTPUT
======
Sum of positive elements: 30

j)What is recursion? Write a program to print the Fibonacci series using recursion.
Recursion is the process of repeating items in a self-similar way. In programming languages, if a program
allows you to call a function inside the same function, then it is called a recursive call of the function.

void recursion() {
recursion(); /* function calls itself */
}

int main() {
recursion();
}

The following example generates the Fibonacci series for a given number using a recursive function −

#include <stdio.h>

int fibonacci(int i) {
if(i == 0) {
return 0;
}

if(i == 1) {
return 1;
}
return fibonacci(i-1) + fibonacci(i-2);
}

int main() {

int i;

for (i = 0; i < 10; i++) {


printf("%d\t\n", fibonacci(i));
}

return 0;
}

When the above code is compiled and executed, it produces the following result −

0
1
1
2
3
5
8
13
21
34

k) Discuss enumerated data type. Describe its importance with suitable example.
The Enumerated data type allows the programmer to invent his own data type and decide what value the
variables of this data type may carry. Enum or enumerator is an integer or number with defined meaningful
names. Enum is often used inside C programs to replace a hard coded numbers with some meaningful symbols.
Advantages of Enumerated Data Type:
1. Makes program listing more readable.
2. Using enumerators reduces programming error.

enum state_t {
TASK_ADDED,
TASK_READY,
TASK_RUNNING,
TASK_WAITING,
TASK_TERMINATED
};
void print_task_state (enum state_t state)
{
switch (state) {
csase TASK_ADDED:
printf ("Task has been added.\n");
break;
case TASK_READY:
printf("Task is ready.\n");
break;
case TASK_RUNNING:
printf("Task is running.\n");
break;
case TASK_TERMINATED:
printf("Task has been terminated.\n");
break;
default:
printf("Task in undefined state.\n");
}
}

l) Write a C program to calculate addition, subtraction, multiplication using command line


arguments argc and argv.

#include <stdio.h>

int main(int argc, char *argv[])


{
int a,b, result;
char opr;

if(argc!=4)
{
printf("Invalid arguments...\n");
return -1;
}

//get values
a = atoi(argv[1]);
b = atoi(argv[3]);

//get operator
opr=argv[2][0];

//calculate according to operator


switch(opr)
{
case '+':
result=a+b;
break;
case '-':
result=a-b;
break;
case '*':
result=a*b;
break;
default:
result=0;
break;
}

if(opr=='+' || opr=='-' || opr=='*')


printf("Result: %d %c %d = %d\n",a,opr,b,result);
else
printf("Undefined Operator...\n");
return 0;
}

Long Answer

Q-3 Discuss the various operators used in C programming. Write a program to check
whether a year is leap year or not using ternary/conditional operator.
An operator is a symbol that tells the compiler to perform specific mathematical or logical functions. C
language is rich in built-in operators and provides the following types of operators −

 Arithmetic Operators
 Relational Operators
 Logical Operators
 Bitwise Operators
 Assignment Operators
 Misc Operators
/**
C program to check leap year using ternary operator
**/

#include <stdio.h>

int main()
{
int year;

printf("Enter the year: ");


scanf("%d", &year);

(year%4==0 && year%100!=0) ? printf("LEAP YEAR") : printf("COMMON YEAR");

return 0;

Q-4 Explain any five string manipulation library functions with examples. Write a program to
find the total number of words in a string.

1-strcpy(s1, s2); Copies string s2 into string s1.


2- strcat(s1, s2); Concatenates string s2 onto the end of string s1.
3- strlen(s1); Returns the length of string s1.
4- strcmp(s1, s2); Returns 0 if s1 and s2 are the same; less than 0 if s1<s2; greater than 0 if s1>s2.
5- strchr(s1, ch); Returns a pointer to the first occurrence of character ch in string s1.
6- strstr(s1, s2); Returns a pointer to the first occurrence of string s2 in string s1.

#include <stdio.h>
#include <string.h>
int main () {
char str1[12] = "Hello";
char str2[12] = "World";
char str3[12];
int len ;
/* copy str1 into str3 */
strcpy(str3, str1);
printf("strcpy( str3, str1) : %s\n", str3 );

/* concatenates str1 and str2 */


strcat( str1, str2);
printf("strcat( str1, str2): %s\n", str1 );

/* total lenghth of str1 after concatenation */


len = strlen(str1);
printf("strlen(str1) : %d\n", len );

return 0;
}
1. /*
2. * C Program to Count Number of Words in a given Text Or Sentence
3. */
4. #include <stdio.h>
5. #include <string.h>
6.
7. void main()
8. {
9. char s[200];
10. int count = 0, i;
11.
12. printf("enter the string\n");
13. scanf("%[^\n]s", s);
14. for (i = 0;s[i] != '\0';i++)
15. {
16. if (s[i] == ' ')
17. count++;
18. }
19. printf("number of words in given string are: %d\n", count + 1);
20.}

Q-5 a) Explain Macro Substitution Directives in brief.


Macro substitution directives

The macro substitution is a process where an identifier in a program is replaced by a predefined string or a
value.
Different forms of macro substitution:
1. Simple macro substitution.
2. Argumented macro substitution.

1. Simple macro substitution:


In simple macro substitution, an identifier (macro) is simply replaced by a string. This can be done by using
the directive #define. It takes the following general form:
#define identifier string
Where Identifier must be a valid C name and string may be any text. When we use this identifier in our
program then this identifier is known as MACRO and #define directive only replaces the MACRO by string.
Simple macro substitution is commonly used to define symbolic constants.
Examples of Symbolic constants:
#define PI 3.14
#define X 100
#define P printf
Note : It is a convention to write all macros( identifiers) in capitals to identify them as symbolic constants.

2 Argumented macro substitution:


As the function, macro can have arguments. The preprocessor permits us to define more complex and more
useful form of replacements it takes the following form:
# define identifier( f1,f2,f3…..fn) string Note: There is no space between identifier and left parentheses and
the identifier f1, f2, f3 …. fn is analogous to formal arguments in a function definition. A simple example of a
macro with arguments is
# define CUBE (x) (x*x*x)
CUBE(x) is macro with arguments

If the following statements appears later in the program,


Volume=CUBE (3);
The preprocessor would expand the statement to
volume =(3*3*3);
Then the variable volume value will be 27.

Undefining a macro:
A macro defined with #define directives can be undefined with #undef directive.
Syntax: #undef identifier
Where identifier is the name of macro It is useful when we do not want to allow the use of macros in any
portion of the program.

Q-5 b)Explain Conditional Compiler directives in details.


Compiler control directives: These directives allow the compiler to compile selected portion of the source
code based on some condition. This is known as "conditional compilation".
Conditional Compilation directives help to compile a specific portion of the program or let us skip compilation
of some specific part of the program based on some conditions.
such directives are ‘ifdef‘ and ‘endif, #ifndef, #if, #else and #elif.
1. #ifdef: This directive is the simplest conditional directive. This block is called a conditional group. The
controlled text will get included in the preprocessor output iff the macroname is defined. The controlled
text inside a conditional will embrace preprocessing directives. They are executed only if the conditional
succeeds. You can nest these in multiple layers, but they must be completely nested. In other words,
‘#endif’ always matches the nearest ‘#ifdef’ (or ‘#ifndef’, or ‘#if’). Also, you can’t begin a conditional
group in one file and finish it in another.
Syntax:
#ifdef MACRO
controlled text
#endif /* macroname */
2. #ifndef: We know that the in #ifdef directive if the macroname is defined, then the block of statements
following the #ifdef directive will execute normally but if it is not defined, the compiler will simply skip
this block of statements. The #ifndef directive is simply opposite to that of the #ifdef directive. In case of
#ifndef , the block of statements between #ifndef and #endif will be executed only if the macro or the
identifier with #ifndef is not defined.
Syntax :
ifndef macro_name
statement1;
statement2;
statement3;
.
.
.
statementN;
3. endif
If the macro with name as ‘macroname‘ is not defined using the #define directive then only the block of
statements will execute.
4. #if, #else and #elif: These directives works together and control compilation of portions of the program
using some conditions. If the condition with the #if directive evaluates to a non zero value, then the group
of line immediately after the #if directive will be executed otherwise if the condition with the #elif
directive evaluates to a non zero value, then the group of line immediately after the #elif directive will be
executed else the lines after #else directive will be executed.
Syntax:
#if macro_condition
statements
#elif macro_condition
statements
#else
statements
#endif

Q-6 Explain all input output functions of file handling. Explain each with example.
(fopen(),fclose(),getc(),putc(),fprint(),fscanf(),getw(),putw(),fseek(),ftell(),rewind()).Write a C
program to copy the contents of one file to another file in reverse order.
1- fopen():create a new file or open a existing file
2- fclose():closes a file
3- getc(): reads a character from a file
4- putc(): writes a character to a file
5- fscanf(): reads a set of data from a file
6- fprintf(): writes a set of data to a file
7- getw(): reads a integer from a file
8- putw(): writes a integer to a file
9- fseek(): set the position to desire point
10- ftell(): gives current position in the file
11- rewind():set the position to the beginning point

Copy contents of one file to another in reverse order


#include<stdio.h>
#include<conio.h>
void main()
{
FILE *in,*out;
char ch,f1[80],f2[80];
long loc;
clrscr();
printf("\n Enter Name of Source File:");
scanf("%s",&f1);
printf("\n Enter Name of Target File:");
scanf("%s",&f2);
in=fopen(f1,"w");
if(f1==NULL)
{
printf("\nCannot open file");
exit(0);
}

else
{
printf("\nEnter data in file %s(Press q to stop):",f1);
while(1)
{
ch=getchar();
if(ch=='q')
break;
else
fputc(ch,in);
}
fclose(in);
}
in=fopen(f1,"r");
if(f1==NULL)
{
printf("\nfile does not exist");
exit(0);
}
out=fopen(f2,"w");
if(f2==NULL)
{
printf("\ncannot open file");
exit(0);
}
fseek(in, 0, SEEK_END);
loc = ftell(in);
loc = loc-1;
while(loc >= 0)
{
fseek(in, loc, SEEK_END);
ch = fgetc(in);
fputc(ch, out);
loc--;
}
printf("\nfile copied in reverse order successfully");
fcloseall();
getch();
}

S-ar putea să vă placă și