0% found this document useful (0 votes)
8 views17 pages

PoP QB With Answers For Test-3

Question bank of my c programming
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views17 pages

PoP QB With Answers For Test-3

Question bank of my c programming
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

PoP Question Bank with answers for Test-3

Module-4: Strings and Pointers


1. Define Strings. Explain declaration and initialization of strings with syntax and example.
 Answer: A string is a sequence of characters that is considered as single data item and
terminated by the null character (\ 0). A string is also referred as one - dimensional character array.
 A string constant is written within a pair of double quotes.
 Example : - “ computer ”
 Array elements of character array are also stored in contiguous memory allocation.
 The above string is stored as follows: -

c o m p u t e r \0

 To hold the null character at the end of the array, the size of the character array containing the
string is one more than number of characters in the string

 Declaration of string variables: -


C program does not support String as data-type but it allows one – dimensional character arrays to
declare string variables.
 The general syntax: -
data-type string-name[size];
Where data-type is char, and string-name is any valid identifier and size indicates the length of the
string.
 Example: - char name[10];
char address[10];
char str[100];
 Initialization of string variables: -
 We can initialize the string as follows: -
char name[5]={‘j’,’o’,’h’,’n’,’\o’};
OR
char name[5] = ”john”;
Here each character occupies 1 byte of memory and last character is always NULL character.
From the above we can represent as;

J o h n \0
name[0] name[1] name[2] name[3] name[4]

1
2. Explain functions for reading and writing strings in c.
Answer:
 Reading strings:
If we declare a string by writing char str[100];
then str can be read from the user by using three ways;
1. Using scanf() function
2. Using gets() function
3. Using getchar(), getch(), or getche() function repeatedly

The string can be read using scanf() by writing scanf(“%s”,str);


Although the syntax of scanf() function is well known and easy to use, the main drawback with this function
is that it terminates as soon as it finds a blank space.
For example, if the user enters Hello World, then str will contain only Hello. This is because the
moment a blank space is encountered, the string is terminated by the scanf() function.
Example:
char str[10];
printf(“Enter a string\n”);
scanf(“%s”,str);

The next method of reading a string a string is by using gets() function. The string can be read by writing
gets(str);
gets() is a function that overcomes the drawbacks of scanf().
The gets() function takes the starting address of the string which will hold the input.
The string inputted using gets() is automatically terminated with a null character.
Example:
char str[10];
printf(“Enter a string\n”);
gets(str);

The string can also be read by calling the getchar() repeatedly to read a sequence of single characters
(unless a terminating character is encountered) and simultaneously storing it in a character array as follows:
int i=0;
char str[10],ch;
getchar(ch);
while(ch!=’\0’)
{
str[i]=ch; // store the read character in str
i++;
getch(ch); // get another character
}
str[i]=’\0’; // terminate str with null character

 Writing string
The string can be displayed on screen using three ways:
i.Using printf() function
ii.Using puts() function
iii.Using putchar() function repeatedly

2
 The string can be displayed using pintf() by writing
printf(“%s”,str); We can use width and precision specification along with
%s.
Example: printf(“%s”,str);
 The next method of writing a string is by using the puts() function. The string can be
displayed by writing:
puts(str);
It terminates the line with a newline character (‘\n’). It returns an EOF(-1) if an error occurs and
returns a positive number on success.
 Finally the string can be written by calling the putchar( ) function repeatedly to print
a sequence of single characters.
int i=0;
char str[10];
while(str[i]!=’\0’)
{
putchar(str[i]); // print the character on the screen
i++;
}
//Example:C program to read and display string
#include<stio.h>
#include<string.h>
main( )
{
char str[10];
printf(“\n Enter a string:”);
scanf(“%s”,str); /*reading the string*/
printf(“ \n Entered string is:”);
printf(“%s”,str); /* writing/displaying*/
}
Output:
Enter a string: program
Entered string is: program.

3.Write a C program to find length of a string without using built-in function.


Answer:
/* C program to find length of string without using strlen( ) */
#include<stdio.h>
void main( )
{
Char str[100];
int i=0,length;
printf(“\n enter the string:”);
gets(str);
while(str[i]!=’\0’)
{
i++;
}
3
length=i;
printf(“ \n the length of string is: %d”,length);
}
Output:
enter the string: programming
the length of string is: 11

4.Write a C program to concatenate two strings without using built-in function.


Answer: /* C program to concatenate two strings into new string without using strcat()*/
#include <stdio.h>
main()
{
char Str1[100], Str2[100],Str3[100];
int i=0, j=0;
printf("\n Enter the First String : ");
gets(Str1);
printf("\n Enter the Second String : ");
gets(Str2);
//copying contents of string1 to string3
while (Str1[i]!='\0')
{
Str3[j] = Str1[i];
i++;
j++;
}
i=0;
//copying contents of string1 to string3
while (Str2[i]!='\0')
{
Str3[j] = Str2[i];
i++;
j++;
}
Str3[j]=’\0’;
printf("\n Concatenated string is = %s", Str3);
}

Output:
Enter the First String: good
Enter the Second String: morning
Concatenated string is = good morning

4
5.Explain the string manipulation functions (strlen(),strcmp(),strcpy(),strrev(),strcat(),strstr()
etc) in C.
Answer: C language provides us lot of string functions for manipulating the string. All the string functions
are available in <string.h> header file.

i. strlen( ): - This string function is basically used for the purpose of computing the length of
string. Syntax: int strlen(char *str); Example: char str[10]=”computer”;
int length= strlen(str);
printf(“The length of the string is =%d”,length);

ii. strcmp ( ): - This string function is basically used for the purpose of comparing two string.
This string function compares two strings character by characters.
Syntax: int strcmp(char *str1,char *str2);
Thus it gives result in three cases:
Case 1: if first string > than second string then, result will be true.
Case 2: if first string < than second string then, result will be false.
Case 3: if first string = = to second string then, result will be zero.
Example: char str1[10]= “computer”;
char str2[10]= “science”;
int i=strcmp(str1,str2);
if(i==0)
printf(“strings are equal”);
else if(i>0)
printf(“str1 is greater than str2”);
else
printf(“str1 is less than str2”);

iii. strcat( ): - This string function is used for the purpose of concatenating two strings
ie.(merging two or more strings) Syntax: char * strcat(char *str1,char *str2);
Example: - char str1[10] = “computer”;
char str2[10] = “science”;
char str3[30];
str3=strcat(str1,str2);
printf(“%s”,str3);

iv. strcpy( ): - This string function is basically used for the purpose of copying one string into
another string.
Syntax: char * strcpy(char *str1,char *str2);
Example: - char str1[10]= “computer”;
char str2[20];
strcpy(str2,str1);
printf(“%s”,str2);

v. strrev( ): - This string function is basically used for the purpose of reversing
the string.
Syntax: char *strrev(char * str);
Example: - char str1[10]=”computer”;
5
char str2[20];
str2= strrev(str1); printf(“%s”,str2); //print “retupmoc”

vi. strstr( ): It is a two parameter function that can be used to locate a substring in a string.
The general format is

strstr(str1,str2);
or
strstr(str1,”ABC”);
The function strstr searches the str1 to see whether the str2 is contained in str1.if yes, the function returns the
position of the first occurrence of the string. Otherwise , it returns a null pointer.

6.Define Pointers. Illustrate declaration and Initialization of pointers with syntax and example.
Answer:
POINTERS:
A pointer is a derived data type in C. it is built from one of the fundamental data types available in C.
A pointer is a variable that holds address of other variable. Since these memory addresses are the
locations in the computer memory where program instructions and data are stored, pointers can be used to
access and manipulate data stored in the memory.
Declaration and Initialization of pointers
The operators used to represent pointers are:
 Address operator (&)
 Indirection operator (*)
Syntax:
ptr_data_type *ptr_variable_name;
ptr_variable_name = &variable_name; //where variable_name is the variable whose address has to
be stored in pointer.
Example: a 10
int a=10; if address of a is 1000
int *ptr; //pointer declaration ptr 1000
then ptr = &a //
*ptr = a;
i.e. ptr is a pointer holding address of variable ‘a’ and *ptr holds the value of a.

7.Explain two types of pointers with syntax and example.(null pointer and void/generic pointers)

Answer: There are two types of pointers:


1) Generic Pointers/void pointer
2) Null Pointer
 Generic Pointers/void pointer :
In C, void represents the absence of type. void pointers are pointers that point to a value that has
no specific type. This allows void pointers to point to any data type.The data pointed by void
pointers cannot be directly dereference We have to use explicit type casting before dereferencing it.
Syntax: void *identifier;
6
Example:
main()
{
int x = 4;
char ch
=’A’;
void *q:
q = &x; //q is pointing to int type
printf(“ the generic pointer points to the integer value =%d”, *(int*)q);
q=&ch;// q is pointing to char type
printf(“ the generic pointer points to character =%c”, *(char*)q);
}

 Null Pointer:
A null pointer is a special pointer that does not point to any valid memory address.
To declare a null pointer we use the pre defined constant NULL, which is defined in several header
files including <stdio.h>,<stdlib.h> and <string.h>
We can declare null pointer as follows,
int *ptr=NULL;

8.Develop a C program using pointers to compute the sum, mean and standard deviation of all elements
stored in an array of N real numbers.
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
void main()
{
float a[10],*ptr,mean,std,sum=0,sumstd=0;
int n,i;
printf("Enter the no of elements\n");
scanf("%d",&n);
printf("Enter the array elements\n");
for(i=0;i<n;i++)
{
scanf("%f",&a[i]);
}
ptr=a;
for(i=0;i<n;i++)
{
sum=sum+*ptr;
ptr++;
}
mean=sum/n;
ptr=a;
for(i=0;i<n;i++)
{
sumstd=sumstd+pow((*ptr-mean),2);
7
ptr++;
}
std=sqrt(sumstd/n);
printf("Sum=%.3f\t",sum);
printf("Mean=%.3f\t",mean);
printf("Standard Deviation=%.3f\t",std);
}
OUTPUT:
Enter the no of elements
4
Enter the array elements
2468
Sum=20.000 Mean=5.000 Standard Deviation=2.236

Module-5: Structures and Files


1. Define structures. Illustrate structure declaration and initialization with syntax and
example.

Answer:
 Structure : “A Structure is a user defined data type, which is used to store the values of
different data types together under the same name”.
or
 “A structure is a collection of one or more variables of same data type or dissimilar data
types grouped under a single name for convenient handling”.
 Each member of a structure is assigned a separate memory location.
A structure helps us to organize complicated data, particularly in large programs, because they permit
a group of related variables to be treated as a unit instead of as separate entities.
Structure Declaration:
Syntax: struct structure_name
{
datatype var_name;
datatype var_name;
datatype var_name;
};
where, struct is a keyword which informs the compiler that a structure is being defined.
structure name: name of the structure
var_names: are members of structure:
type1,type 2 : int, float, char, double
Memory is allocated for the structure when we declare a variable of the structure. For ex, we can define a
variable of student by writing
struct student stud1;
Example:
struct student
{
8
int usn;
char name[10];
float marks;
};
Initialization of structures
● The initializers are enclosed in braces and are separated by commas. Note that initializers match their
corresponding types in the structure definition.
● The general syntax to initialize a structure variable is given as follows.
struct struct_name
{ data_type member_name1;
data_type member_name2;
data_type member_name3;
.......................................
}struct_var = {constant1, constant2, constant 3,...};
Example:
struct student
{
int usn;
char name[10];
float marks;
} s1={01,“Rahul”, 56.0};

OR
struct student
{
int roll_no, age;
char name[20],grade;
float fee;
} student1;
student1.roll_no=50;
student1.age=18;
student1.name= “Rama”;
student1.name= ‘A’;
student1.fee=35500.00;

2.Differentiate between structures and unions.


structures unions.
1. The struct keyword is used to define 1. The keyword union is used to define
structures. unions

2. The size of the structure is equal to the 2. Size of the unions is equal to the
sum of the sizes of its members. sum of its largest member.

9
3. Each member within a structure is 3. Memory allocated is shared by
assigned a unique storage of allocation individual members of unions.

4. All members can be initialized. 4. Only one member is initialized at any


time.

5. Consume more space than unions 5. Conservation of memory is possible

6. Syntax: 6.Syntax:
struct structure_name union union_name
{ {
datatype var_name; data_type var_name;
datatype var_name; data_type var_name;
}; };

3.Explain how to declare and access structures variable with suitable syntax and example.
Declaring Structure Variables:
 We can declare variables of the structure name in the same way as we declare variables of
predefined data type.

Syntax:
struct structure_name variable_name;
Example:
struct student
{
int roll_no, age;
char name[20], grade;
float collg_fee;
};

struct student student1; //student1 is structure variable

 We can also declare multiple structure variables using a single line of code by using
following syntax:

Syntax:
struct structure_type variable1,variable2,… ............. variable-n;

10
 The definition of a structure and declaration of structure variables can be done together.

struct structure_name
{
data_type1 variable1;
data_type2 variable2;
…………………………
data_type n variablen;
} structure_variable1, structure_variable2,………, structure_variable-n;

Example: struct student


{ int roll_no, age;
char name[20], grade;
float collg_fee;
}student1,student2;

 Structure name is student and we have declared two variables of type student: student1 and
student2.

Accessing members of a Structure:


 A member of a structure is identified and accessed using the (.) Dot Operator. The Dot
Operator connects the member name to the name of its containing Structure.

Syntax:
structure_variable_name.member;

Example: student1.roll_no;
student1.name;

11
4.Implement structures to read ,write and compute average marks of the students ,display number of
students scored above and below average marks of class of n students.
#include<stdio.h>
#include<stdlib.h>
struct student
{
char usn[50];
char name[50];
int marks;
}s[10];
void main()
{
int i,n,countav=0,countbv=0;
float sum,average;
printf("Enter number of Students :\n");
scanf("%d",&n);
printf("Enter information of students :\n");
for(i=0;i<n;i++)
{
printf("Enter USN:");
scanf("%s",s[i].usn);
printf("Enter name:");
scanf("%s",s[i].name);
printf("Enter marks:");
scanf("%d",&s[i].marks);
printf("\n");
}
printf("Displaying information:\n\n");
for(i=0;i<n;i++)
{
printf("\nUSN:%s\n",s[i].usn);
printf("\nName:%s\n",s[i].name);
printf("Marks:%d",s[i].marks);
printf("\n");
}
for(i=0;i<n;i++)
{
sum=sum+s[i].marks;
}
average=sum/n;
printf("\n Average marks:%f",average);
for(i=0;i<n;i++)
{
if(s[i].marks>=average)
countav++;
else
countbv++;
}
printf("\n Total No of students above average=%d",countav);
printf("\n Total No of students below average=%d",countbv);
}
12
5.Define file. Demonstrate how to declare file pointer, file open function along with modes and file close
function with syntax and example.
Answer:
File
 “A File is a collection of data or information stored on computer memory or the secondary device
such as disk”.
 An Input file (data file) contains the same item what we have typed in from the keyboard during
interactive data entry.
 An Output file contains the same information that might have been sent to the screen as the output
from our program.
To use files in C, we must follow the steps given below:
 Declare a file pointer variable
 Open the file
 Process the file
 Close the file

Declaring a file pointer variable


● There can be a number of files on the disk. In order to access a particular file, you must specify the
name of the file that has to be used. This is accomplished by using a file pointer variable that points to
a structure FILE (defined in stdio.h). The file pointer will then be used in all subsequent operations in
the file.
● The syntax for declaring a file pointer is
FILE *file_pointer_name;
For example, if we write
FILE *fp;
Then, fp is declared as a file pointer.
● An error will be generated if you use the filename to access a file rather than the file pointer
Opening a file using fopen() function:
● A file must be first opened before data can be read from it or written to it. In order to open a file and
associate it with a stream, the fopen() function is used.
● The syntax of fopen() can be given as:
● FILE *fopen(const char *file_name, const char *mode);

● Using the above prototype, the file whose pathname is the string pointed to by file_name is opened in
the mode specified using the mode. If successful, fopen() returns a pointer-to-structure and if it fails,
it returns NULL.

13
MODE DESCRIPTION

Open a text file for reading. If the stream (file) does not exist then an error will be
r
reported.
Open a text file for writing. If the stream does not exist then it is created otherwise if the
w file already exists, then its contents would be deleted

a Append to a text file. if the file does not exist, it is created.

Open a binary file for reading. B indicates binary. By default this will be a sequential file
rb
in Media 4 format

wb Open a binary file for writing

ab Append to a binary file

Open a text file for both reading and writing. The stream will be positioned at the
r+ beginning of the file. When you specify "r+", you indicate that you want to read the file
before you write to it. Thus the file must already exist.
Open a text file for both reading and writing. The stream will be created if it does not
w+ exist, and will be truncated if it exist.

Open a text file for both reading and writing. The stream will be positioned at the end of
a+
the file content.

r+b/ rb+ Open a binary file for read/write

w+b/wb+ Create a binary file for read/write

a+b/ab+ Append a binary file for read/write

The fopen() can fail to open the specified file under certain conditions that are listed below:
● Opening a file that is not ready for usage
● Opening a file that is specified to be on a non-existent directory/drive
● Opening a non-existent file for reading
● Opening a file to which access is not permitted
FILE *fp;
fp = fopen("Student.txt", "r");
if(fp==NULL)
{
printf("\n The file could not be opened");
exit(1);

14
CLOSING A FILE USING fclose():
● To close an open file, the fclose() function is used which disconnects a file pointer from a file. After
the fclose() has disconnected the file pointer from the file, the pointer can be used to access a different
file or the same file but in a different mode.
● The fclose() function not only closes the file but also flushed all the buffers that are maintained for that
file
● If you do not close a file after using it, the system closes it automatically when the program exits.
However, since there is a limit on the number of files which can be open simultaneously; the
programmer must close a file when it has been used.
● The prototype of the fclose() function can be given as,
int fclose(FILE *fp);
Here, fp is a file pointer which points to the file that has to be closed. The function returns an integer value
which indicates whether the fclose() was successful or not. A zero is returned if the function was successful;
and a non-zero value is returned if an error occurred.
Example Program:
#include<stdio.h>
void main()
{
FILE * fp;
fp = fopen(“student.txt”, “r”);
if ( fp==NULL)
{
printf (“Error in Opening file\n”);
exit(0);
}/* Using fp access file contents*/
…………..
fclose(fp);
}

6.Write a c program to copy a text file to another, read both the input file name and target filename.
#include<stdio.h>
int main()
{
char ch,fileName1[20],fileName2[20];
FILE *fs,*ft;
printf("Enter Source File name(with extension):");
gets(fileName1);
fs=fopen(fileName1,"r");
if(fs==NULL)
{
printf("\nError in opening the file,%s",fileName1);
return 0;
}
printf("Enter Target File name(with extension):");
gets(fileName2);
ft=fopen(fileName2,"w");

15
if(ft==NULL)
{
printf("\nError in opening the file,%s",fileName2);
return 0;
}
ch=fgetc(fs);
while(ch!=EOF)
{
fputc(ch,ft);
ch=fgetc(fs);
}
printf("\nFile coppied successfully.");
fclose(fs);
fclose(ft);
return 0;
}

************************************************************************************

16
17

You might also like