Documente Academic
Documente Profesional
Documente Cultură
c)
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.
atoi() function in C language converts string data type to int data type.
Syntax: int atoi (const char * str);
#define PI 3.14
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
b)What is the difference between flowchart and algorithm? Draw the flowchart to find the sum
of n natural numbers.
Flowchart Algorithm
It uses symbols for processes and I/O. No symbols are used, completely in text.
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;
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
#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;
}
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;
}
{
register int miles;
}
#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);
}
#include <stdio.h>
int count ;
extern void write_extern();
main() {
count = 5;
write_extern();
}
#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.
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.
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.
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.
#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;
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");
}
}
#include <stdio.h>
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];
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;
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.
#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 );
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.}
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.
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-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
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();
}