Академический Документы
Профессиональный Документы
Культура Документы
ANSWERS
1 a. Here is list of possible names for variables in C language. Which are valid
names and invalid names? If name is invalid, explain why?
viii). help+me Invalid Variable Because variable or identifier cannot have (+)
or identifier plus symbol.
1b. What is the purpose of a printf() statement? Explain the formatted printf()
along with the respective examples.
SYNTAX
Output:
Character is A
String is HELLO
Float value is 10.234000
Integer value is 150
Double value is 20.123456
Octal value is 226
Hexadecimal value is 96
.
2 a. Write a C program to find area of a triangle when we know the lengths of all
three of its sides.
#include <stdio.h>
#include <math.h>
#include <conio.h>
int main()
{
float a, b, c, s, area;
printf("Enter the length of three sides of triangle\n");
scanf("%f %f %f", &a, &b, &c);
s = (a + b + c)/2;
area = sqrt(s*(s-a)*(s-b)*(s-c));
printf("Area of triangle : %0.2f\n", area);
getch();
return 0;
}
Program Output
Enter the length of three sides of triangle
3 4 5
Area of triangle : 6.00
2b. Write a C program that computes the size of int, float, double and char variables.
#include<stdio.h>
#include<conio.h>
void main()
{
int x;
float y;
double z;
char ch;
clrscr();
printf("Size of integer variable x:%d\n",sizeof(x));
printf("Size of float variable y:%d\n",sizeof(y));
printf("Size of double variable z:%d\n",sizeof(z));
printf("Size of character variable char:%d\n",sizeof(char));
getch();
}
OUTPUT:
Size of integer variable x:2
Size of float variable y:4
Size of double variable z:8
Size of character variable char: 1
2c. What are Operators? Explain the relational and logical operators supported in
C Language.
Arithmetic Operators
Relational Operators
Logical Operators
Bitwise Operators
Assignment Operators
Relational Operators
The following table shows all the relational operators supported by C. Assume
variable A holds 10 and variable B holds 20 then
Description Example
Operator
== Checks if the values of two operands are equal or not. If (A == B) is not true.
yes, then the condition becomes true.
!= Checks if the values of two operands are equal or not. If the (A != B) is true.
values are not equal, then the condition becomes true.
> Checks if the value of left operand is greater than the value (A > B) is not true.
of right operand. If yes, then the condition becomes true.
< Checks if the value of left operand is less than the value of (A < B) is true.
right operand. If yes, then the condition becomes true.
>= Checks if the value of left operand is greater than or equal (A >= B) is not true.
to the value of right operand. If yes, then the condition
becomes true.
<= Checks if the value of left operand is less than or equal to (A <= B) is true.
the value of right operand. If yes, then the condition
becomes true.
Logical Operators
Following table shows all the logical operators supported by C language.
&& Called Logical AND operator. If both the operands are non- (A && B) is false.
zero, then the condition becomes true.
! Called Logical NOT Operator. It is used to reverse the !(A && B) is true.
logical state of its operand. If a condition is true, then
Logical NOT operator will make it false.
3b. Explain the syntax of do-while statement. Write a C program to find the
factorial of a number using while loop, where the number n is entered by the
user. (Hint: factorial of n = 1*2*3*….*n).
printf("Factorial = %ld\n",fact);
getch();
}
Output:
Another Example:
#include<stdio.h>
#include<conio.h>
void main()
{
int n;
long int f=1;
clrscr();
printf("enter any number\n");
scanf("%d",&n);
do
{
f=f*n;
n--;
}while(n>0);
printf("factorial is=%d\n",f);
getch();
}
4 a. Write a C Program to find GCD of two numbers using ternary operator and for
loop.
This program is little optimized than the other GCD programs to find GCD/H.C.F. In this program,
smallest of two integers entered by user is stored in variable min. Then i is initialized to min and
for loop is executed. In each looping iteration, whether i is factor of these two numbers is checked.
If i is a factor of these two numbers then, i will be the Greatest Common Divisor / Highest Common
Factor and loop is terminated using break statement.
#include <stdio.h>
void main()
{
int n1, n2, min,i,gcd;
printf("Enter two Numbers:\n");
scanf("%d%d", &n1, &n2);
for(i=min;i>0;i--)
if(n1%i==0 && n2%i==0)
{
gcd=i;
break;
}
Output
Enter two Numbers:
20 35
HCF/GCD of 20 and 35 is 5
ARRAY
• Array is a collection of elements of same data type.
• The elements are stored sequentially one after the other in memory.
• Any element can be accessed by using
→ name of the array
→ position of element in the array
• Arrays are of 2 types:
1) Single dimensional array
2) Multi dimensional array
• A single dimensional array is a linear list consisting of related elements of same type.
• In memory, all the elements are stored in continuous memory-location one after the
other.
Declaration of Single Dimensional Arrays
• The syntax is shown below:
data_type array_name[array_size]
where data_type can be int, float or char array_name is name of the array
array_size indicates number of elements in the array
• For ex:
int age[5];
• The above code can be pictorially represented as shown below:
• For ex:
int age[5]={2,4,34,3,4};
#include <stdio.h>
void main()
{
char s1[100], s2[100], i, j;
printf("Enter first string:");
scanf("%s",s1);
printf("Enter second string: ");
scanf("%s",s2);
for(i=0; s1[i]!='\0'; i++); /* i contains length of string s1. */
for(j=0; s2[j]!='\0'; j++)
{
s1[i]=s2[j];
i++;
}
s1[i]='\0';
printf("After concatenation: %s\n",s1);
}
Output:
Enter first string: HKBK
Enter second string: College
After concatenation: HKBKCollege
#include<stdio.h>
int isPrime(int,int);
void main( )
{
int num,prime;
printf("Enter a positive number: ");
scanf("%d",&num);
prime = isPrime(num,num/2);
if(prime==1)
printf("%d is a prime number",num);
else
printf("%d is not a prime number",num);
}
{
if(i==1)
return 1;
else
{
if(num%i==0)
return 0;
else
isPrime(num, i-1);
}
}
Output:
Enter a positive number: 13
13 is a prime number
Function Declaration
Every function in C program should be declared before they are used.
• Function declaration gives compiler information about
→ function name
→ type of arguments to be passed and return type
Function Definition
• Function definition contains programming codes to perform specific task.
• The syntax is shown below:
return_type function_name(type argument1,..,type argumentn)
{
//body of function
}
#include<stdio.h>
#include<conio.h>
int cube(int n);
void main()
{
int n,c;
clrscr();
c=cube(n);
int cube(int n)
{
return(n*n*n);
}
Output:
Enter Any Number : 5
Cube of 5 is 125
6b. List string manipulation library functions and explain any two of them with
Example
• All string manipulation can be done manually by the programmer but, this makes
programming complex and large.
• To solve this, the C supports a large number of string handling functions.
• There are numerous functions defined in <string.h> header file.
#include <stdio.h>
#include <string.h>
void main( )
{
int len;
char a[20]="Bengaluru" ;
len = strlen(a) ;
printf ( "\string length = %d \n" , len ) ;
}
Output:
string length = 9
#include <stdio.h>
#include <string.h>
void main()
{
char s1[10] = "Hello";
char s2[10] = "World";
strcat(s1,s2);
printf("Output string after concatenation: %s", s1);
}
Output:
Output string after concatenation: HelloWorld
6c. Write a C Program to find greatest number from two dimensional array.
#include<stdio.h>
#include<conio.h>
main()
{
int m, n, i, j, a[10][10], maximum;
maximum = a[0][0];
for( i = 0 ; i < m ; i++ )
for( j = 0 ; j < n ; j++ )
if (a[i][j] > maximum )
maximum = a[i][j];
Output:
Enter the number of rows and columns of matrix
3 4
Enter the elements of matrix
3 2 6 1
9 45 33 22
11 34 32 -3
Maximum element in matrix is 45
STRUCTURE:
Structure is a collection of elements of different data type.
Structure is a user-defined data type in C which allows you to combine different data
types to store a particular type of record. Structure helps to construct a complex data
type in more meaningful way.
Structure is composition of the different variables of different data types , grouped under
same name.
C Structure is a collection of different data types which are grouped together and each
element in a C structure is called member.
The variables that are used to store the data are called members of the structure.
Another way of creating sturcture variable using the keyword typedef is:
typedef struct person
{
char name[50];
int age;
float salary;
} EMP;
EMP p1 ,p2 ;
Here the above statement declares that the variables p1 and p2 are variables of type EMP(which is of type as
struct person).
struct Student
{
int rollno;
char name[20];
floar marks;
} S1, S2 ;
7b. What is a file? Explain file open and close functions with arguments.
A file represents a sequence of bytes on the disk where a group of related data is stored. File
is created for permanent storage of data. C programming language can handle files as Stream-
oriented data (Text) files and System oriented data Binary) files.
Defining a File
• While working with file, we need to declare a pointer of type “FILE‟. This declaration is
needed for communication between file and program.
FILE *ptr;
Opening a File
• fopen( ) function can be used
to create a new
file or to open
an existing file
• This function will initialize an object of the type FILE, which contains all the information
necessary to control the stream.
• The syntax is shown below:
FILE *fopen( const char *filename, const char *access_mode );
where filename is string literal, which you will use to name your file.
Opening Modes in Standard I/O
r Open for reading. If the file does not exist, fopen() returns NULL.
If the file exists, its contents are overwritten.
w Open for writing. If the file does not exist, it will be created.
Open for append. i.e, Data is
a added to end of file. If the file does not exists, it will be created.
Open for both reading and
r+ writing. If the file does not exist, fopen() returns NULL.
Open for both reading and If the file exists, its contents are overwritten.
w+ writing. If the file does not exist, it will be created.
Open for both reading and
a+ appending. If the file does not exists, it will be created.
Closing a File
The file should be closed after reading/writing of a file.
fclose( ) function can be used to close a file. The syntax is shown below:
7.c Explain fputc( ), fputs( ), fgetc( ) and fgets() functions with syntax.
INPUT AND OUTPUT OPERATIONS
• The fgetc() function reads a character from the input file referenced by fp.
• This function returns the character being read on success; otherwise returns EOF if there
is an error.
• The functions fgets() reads up to n-1 characters from the input stream referenced by fp.
• It copies the read string into the buffer buf, appending a null character to terminate the
string.
• If this function encounters a newline character '\n‟, then it returns only the characters
read up to that point including new line character.
void main( )
{
struct student s1; /* declaring structure variable */
clrscr();
8b. Explain how the structure variable passed as a parameter to a function with
Example
#include <stdio.h>
#include <conio.h>
void getdetails(EMP *e1 ) /* function reads employee details by call / pass by reference*/
{
printf("\nEnter Employee name:");
gets(e1 name);
printf("\nEnter age:");
scanf("%d",&e1 age);
printf("\nEnter Salary:");
scanf("%f",&e1 salary);
}
int main( )
{
EMP e1;
clrscr();
getdetails(&e1); /* function call to read employee details using call by reference*/
displaydetails(e1); /* function call to display employee details using call by value */
getch();
}
Output:
Enter Employee name: Pranab singh
Enter age: 25
Enter Salary: 25000
Eg: getdetails(&e1); e1 member values are initialized and changed by this function.
8c. Write a C program to read and display a text from the file.
#include <stdio.h>
#include <stdlib.h>
void main( )
{
char ch, fname[25];
FILE *fp;
if( fp = = NULL )
{
perror("Error while opening the file.\n");
exit(0);
}
while( ( ch = fgetc(fp) ) != EOF ) /* reading each character from file till end of file */
printf("%c",ch);
Example:
#include “demo.h”
--tells CPP to get demo.h from the local directory and add the content to the current source file.
#include<stdio.h>
#define MAX 100
void main( )
{
#if (MAX)
printf("MAX is defined");
#else
printf ("MAX is not defined");
#endif
}
CALL BY ADDRESS/POINTER
The call to the function passes variable’s address to the called function. The actual arguments
are not copied to the formal arguments, the addresses of actual arguments (or parameters)
are passed to the formal parameters. Hence any operation performed by function on formal
arguments / parameters affects actual parameters.
void swap(int *x, int *y) /* function to swap 2 values using pointers as call by address */
{
int t;
t = *x;
*x = *y;
*y = t;
}
void main( )
{
int a=5, b=10 ;
printf("Before swap: a=%d,b=%d",a,b);
swap(&a, &b); /*calling swap function by passing address*/
printf("After swap: a= %d,b=%d",a,b);
}
Output:
Because variable declared ‘a’, ‘b’ in main() is different from variable ‘x’, ’y’ in swap().
Only variable names are different but both a and x, b and y point to the same memory
address locations respectively.
The above code will allocate 200 bytes assuming sizeof(int)=2 bytes
2. calloc( ) - contiguous allocation
This function is used to allocate the required memory-size during execution-time and at the same time,
automatically initialize memory with 0's.
syntax :
data_type *p;
p=(data_type*)calloc(n,size);
Ex:
p=(int*)calloc(25,sizeof(int));
3. free( )
Dynamically allocated memory with either calloc( ) or malloc( ) can be deallocated using free( )
explicitly to release space.
syntax:
free(ptr);
4. realloc() -reallocation
If the previously allocated memory is insufficient or more than sufficient. Then, we can change memory-
size previously allocated using realloc().
Example: Program to find the print 5 values using dynamic memory allocation & pointers
void main( )
{
int i;
int *a= (int *)malloc(10);
for(i=0;i<5;i++)
*(a+i)=i+10;
for(i=0;i<5;i++)
printf(“%d\t”,*(a+i)10;
}
Output: 10 11 12 13 14
10 a. Explain stack and queue related terms and give their applications.
STACKS
• A stack is a special type of data structure where elements are inserted from one end and elements
are deleted from the same end.
• Using this approach, the Last element Inserted is the First element to be deleted Out, and hence,
stack is also called LIFO data structure.
• The various operations performed on stack:
Insert: An element is inserted from top end. Insertion operation is called push
operation. Delete: An element is deleted from top end. Deletion operation is called
pop operation. Overflow: Check whether the stack is full or not.
Underflow: Check whether the stack is empty or not.
• This can be pictorially represented as shown below:
APPLICATIONS OF STACK
1) Conversion of expressions: The compiler converts the infix expressions into postfix expressions
using stack.
2) Evaluation of expression: An arithmetic expression represented in the form of either postfix or
prefix can be easily evaluated using stack.
3) Recursion: A function which calls itself is called recursive function.
4) Other applications: To find whether the string is a palindrome, to check whether a given
expression is valid or not.
QUEUES
• A queue is a special type of data structure where elements are inserted from one end and
elements are deleted from the other end.
• The end at which new elements are added is called the rear and the end from which elements
are deleted is called the front.
• The first element inserted is the first element to be deleted out, and hence queue is also called
FIFO data structure.
• The various operations performed on queue are
1) Insert: An element is inserted from rear end.
2) Delete: An element is deleted from front end.
3) Overflow: If queue is full and we try to insert an item, overflow condition occurs.
4) Underflow: If queue is empty and try to delete an item, underflow condition occurs.
• This can be pictorially represented as shown below:
‘ * ’ used to declare a pointer variable and also used to retrieve the value from the pointed
memory location. ‘ * ’ is also called as derefence operator.
#include <stdio.h>
void main ()
{
int a = 20; /* actual variable declaration */
int *ip; /* pointer variable declaration */
ip = &a; /* store address of var in pointer variable*/
printf("Address of variable a is: %x\n", &a );
/* address stored in pointer variable */
ADVANTAGES OF POINTERS