SlideShare uma empresa Scribd logo
1 de 23
Baixar para ler offline
Kanpur Institute of Technology
Computer concept and C programming -Question Bank-3
somnath.gupta123@gmail.com Page 1
Question1Question1Question1Question1 What is string? Also explain different string functions with examples.
Answer
StringsStringsStringsStrings
A group of characters can be stored in a character array.
Character arrays are also called strings.
Character arrays or strings are used to manipulate text such as words and sentences.
A string constant is a one dimensional array of characters terminated by a null (‘0’).
EEEExamplexamplexamplexample
char name[ ] = { 'H', 'A', 'E', 'S', 'L', 'E', 'R', '0' } ;
Each character in the array occupies one byte of memory and the last character is always ‘0’. ‘0’ is called
null character. ASCII value of ‘0’ is 0.
Memory Representation of character ArrayMemory Representation of character ArrayMemory Representation of character ArrayMemory Representation of character Array
The elements of the character array are stored in contiguous memory locations.
The above string can also be initialized as
char name[ ] = "HAESLER" ;
NoteNoteNoteNote In this declaration ‘0’ is not necessary. C inserts the null character automatically.
Standard Library String FunctionsStandard Library String FunctionsStandard Library String FunctionsStandard Library String Functions
FunctionFunctionFunctionFunction UseUseUseUse
Strlen Finds length of a string
Strcpy Copies a string into another
strcmp Compares two strings
strcat Appends one string at the end of another
Strrev Reverses string
strupr Converts a string to uppercase
Strlwr Converts a string to lowercase
Kanpur Institute of Technology
Computer concept and C programming -Question Bank-3
somnath.gupta123@gmail.com Page 2
strlen( )strlen( )strlen( )strlen( ) FunctionFunctionFunctionFunction
ExplanationExplanationExplanationExplanation
This function counts the number of characters present in a string i.e. find length of the string.
int strlen(string);
ExampleExampleExampleExample
/*A program to find the length of input string using string/*A program to find the length of input string using string/*A program to find the length of input string using string/*A program to find the length of input string using string function*/function*/function*/function*/
#include<string.h>
void main()
{
char str[100];
int len;
printf("n Enter the string ");
gets(str);
len=strlen(str);
printf("n The length of the string is =%d",len);
}
OutputOutputOutputOutput
Enter the string Humpty Dumpty
The length of the string is = 13
strcpy (strcpy (strcpy (strcpy ( )))) FunctionFunctionFunctionFunction
Explanation This function copies the contents of source string into target string.
strcpy(target,source);
ExampleExampleExampleExample
/*A program to copy of one string into other string using string function*//*A program to copy of one string into other string using string function*//*A program to copy of one string into other string using string function*//*A program to copy of one string into other string using string function*/
#include<string.h>
void main()
{
char str1[100],str2[100];
printf("n Enter the string ");
gets(str1);
strcpy(str2,str1);
printf("n The input string is %s",str1);
printf("n The copy of input string is >%s",str2);
}
Kanpur Institute of Technology
Computer concept and C programming -Question Bank-3
somnath.gupta123@gmail.com Page 3
OutputOutputOutputOutput
Enter the string Kanpur
The input string is Kanpur
The copy of input string is >Kanpur
strcat (strcat (strcat (strcat ( )))) FunctionFunctionFunctionFunction
ExplanationExplanationExplanationExplanation This function appends the source string at the end of the target string.
For example, “Bombay” and “Nagpur” on concatenation would result into a string “BombayNagpur”.
/* A Program to append one string at the end of other string using strcat( ) function*//* A Program to append one string at the end of other string using strcat( ) function*//* A Program to append one string at the end of other string using strcat( ) function*//* A Program to append one string at the end of other string using strcat( ) function*/
#include<string.h>
void main()
{
char str1[10],str2[10];
printf("nEnter the first string ");
gets(str1);
printf("nEnter the second string ");
gets(str2);
strcat(str1,str2); // append str2 at the end of str1
printf("nAppend string is ");
puts(str1); // display str1
}
OutputOutputOutputOutput
Enter the first string Bombay
Enter the second string Nagpur
Append string is BombayNagpur
strcmp(strcmp(strcmp(strcmp( )))) FunctionFunctionFunctionFunction
This function compares two strings to find out whether they are identical or different. The two strings are
compared character by character until there is a mismatch or end of one of the strings is reached, whichever
occurs first. If the two strings are identical, strcmp( ) returns a value zero. If they’re not, it returns the
numeric difference between the ASCII values of the first non matching pairs of characters.
Kanpur Institute of Technology
Computer concept and C programming -Question Bank-3
somnath.gupta123@gmail.com Page 4
ExampleExampleExampleExample
/* A Program to compare one string to other string using strcmp( ) fu/* A Program to compare one string to other string using strcmp( ) fu/* A Program to compare one string to other string using strcmp( ) fu/* A Program to compare one string to other string using strcmp( ) function*/nction*/nction*/nction*/
#include<string.h>
void main()
{
int r;
char str1[10],str2[10];
printf("Enter the first string n");
gets(str1);
printf("Enter the second string n");
gets(str2);
r=strcmp(str1,str2);
if(r==0)
printf("n files are identical");
else
printf("n files are not identical");
}
Question 2Question 2Question 2Question 2 Write a user defined function to copy of one string into other string.
Answer
/*A program to copy of one string into other string without using string function*//*A program to copy of one string into other string without using string function*//*A program to copy of one string into other string without using string function*//*A program to copy of one string into other string without using string function*/
#include<stdio.h>
void xstrcpy(char *ptr2,char *ptr1); //prototype declaration
void main()
{
char str1[100],str2[100];
printf("n Enter the string ");
gets(str1);
printf("n The input string is %s",str1);
xstrcpy(str2,str1);
printf("n The copy of input string is >%s",str2);
}
void xstrcpy(char *ptr2,char *ptr1)
{
Kanpur Institute of Technology
Computer concept and C programming -Question Bank-3
somnath.gupta123@gmail.com Page 5
while(*ptr1!='0')
{
*ptr2=*ptr1;
ptr1++;
ptr2++;
}
*ptr2='0';
}
OutputOutputOutputOutput
Enter the string Kanpur
The input string is Kanpur
The copy of input string is Kanpur
Question 3Question 3Question 3Question 3 Write a user defined function to append two strings.
Answer
// A program to append two string without using string function
#include<stdio.h>
void xstrcat(char *t,char *s1); //function prototype declaration
void main()
{
char str1[10],str2[10],str3[20];
printf("nEnter the first string ");
gets(str1);
printf("nEnter the second string ");
gets(str2);
xstrcat(str1,str2);
printf("nAppend string is >");
puts(str1);
}
void xstrcat(char *t, char *s)
{
while(*t!='0')
{
t++;
Kanpur Institute of Technology
Computer concept and C programming -Question Bank-3
somnath.gupta123@gmail.com Page 6
}
while(*s!='0')
{
*t=*s;
t++;
s++;
}
*t='0';
}
OutputOutputOutputOutput
Enter the first string Bombay
Enter the second string Nagpur
Append string is BombayNagpur
Question 4Question 4Question 4Question 4 Write a user defined function to compare two strings where they are identical or not.
Answer
/*/*/*/* A program to compare the two string without using string functionA program to compare the two string without using string functionA program to compare the two string without using string functionA program to compare the two string without using string function */*/*/*/
#include<stdio.h>
#include<conio.h>
int xstrcmp(char *,char *); //function prototype declaration
void main()
{
int r;
char str1[10],str2[10];
printf("Enter the first string n");
gets(str1);
printf("Enter the second string n");
gets(str2);
r=xstrcmp(str1,str2);
if(r==0)
{
printf(" n both strings are identical");
}
else
{
Kanpur Institute of Technology
Computer concept and C programming -Question Bank-3
somnath.gupta123@gmail.com Page 7
printf("n Both strings are not identical");
}
}
int xstrcmp(char *ptr1,char *ptr2)
{
int i=0;
while(*ptr1!='0' || *ptr2!=’0’)
{
if(*ptr1!=*ptr2)
{
break;
}
ptr1++;
ptr2++;
}
return *ptr1 *ptr2;
}
Question5Question5Question5Question5 –––– How the two dimensional character array has been initialized? What are the drawbacks of it?
How can we overcome it?
Answer
InitializationInitializationInitializationInitialization twotwotwotwo dimensional character arraydimensional character arraydimensional character arraydimensional character array
char masterlist[6][10] = { "akshay", "parag", "raman", "srinivas", "gopal", "rajesh" } ;
The first subscript gives the number of names in the array, while the second subscript gives the length of each
item in the array.
Kanpur Institute of Technology
Computer concept and C programming -Question Bank-3
somnath.gupta123@gmail.com Page 8
Here 65454, 65464, 65474, is base addresses of successive names. Here 10 byte are reserved for storing the
name “akshay”, it occupies only 7 bytes. Thus 3 bytes go waste. Similarly for each name, some amount offor each name, some amount offor each name, some amount offor each name, some amount of
memories gomemories gomemories gomemories go wastagewastagewastagewastage.... ThisThisThisThis can be avoided by ucan be avoided by ucan be avoided by ucan be avoided by using array of pointer.sing array of pointer.sing array of pointer.sing array of pointer.
Array of Pointers to StringsArray of Pointers to StringsArray of Pointers to StringsArray of Pointers to Strings
A pointer variable always contains an address. Therefore, if we construct an array of pointers it would contain
a number of addresses.
Let us see how the names in the earlier example can be stored in the array of pointers.
char *names[ ] = { "akshay", "parag", "raman", "srinivas", "gopal", "rajesh" } ;
In this declaration names[ ] is an array of pointers. It contains base addresses of respective names. That is, base
address of “akshay” is stored in names[0], base address of “parag” is stored in names[1] and so on.
Advantages of array of pointer overAdvantages of array of pointer overAdvantages of array of pointer overAdvantages of array of pointer over 2222 D array:D array:D array:D array:
In the two dimensional array of characters, the strings occupied 60 bytes.
As against this, in array of pointers, the strings occupy only 41 bytes a net saving of 19 bytes.
Another reason to use an array of pointers to store strings is to obtain greater ease in manipulation of
the strings.
Kanpur Institute of Technology
Computer concept and C programming -Question Bank-3
somnath.gupta123@gmail.com Page 9
QuestionQuestionQuestionQuestion 6666––––Initialize a 2 D character array with "akshay", "parag", "raman", "srinivas", "gopal", "rajesh". Read a
name from the keyboard and find that name is available or not.
Answer
/* A program to/* A program to/* A program to/* A program to find name in the 2find name in the 2find name in the 2find name in the 2 D character array */D character array */D character array */D character array */
#include<stdio.h>
void main( )
{
char masterlist[6][10] = { "akshay", "parag", "raman", "srinivas", "gopal", "rajesh" } ;
int i, flag, a ;
char name[10] ;
printf ( "n Enter name " ) ;
scanf ( "%s",name ) ;
flag = 0 ;
for ( i = 0 ; i <= 5 ; i++ )
{
a = strcmp ( &masterlist[i][0],name ) ;
if ( a == 0 )
{
printf ( "n Name is available " ) ;
flag = 1 ;
break ;
}
}
if ( flag ==0 )
printf ( "n Sorry not available!" ) ;
}
OutpuOutpuOutpuOutputttt
Enter your name dinesh
Sorry not available!
Enter your name raman
Name is available
Kanpur Institute of Technology
Computer concept and C programming -Question Bank-3
somnath.gupta123@gmail.com Page 10
QuestionQuestionQuestionQuestion 7777 Write a program to sort a set of names stored in alphabetical order using array of pointer to
string.
AnswerAnswerAnswerAnswer
/*/*/*/*A program to sort the names of citiesA program to sort the names of citiesA program to sort the names of citiesA program to sort the names of cities alphabetically using array of pointer */alphabetically using array of pointer */alphabetically using array of pointer */alphabetically using array of pointer */
#include<stdio.h>
#include<string.h>
void main()
{
char *name[]={"kanpur","indore","delhi","lucknow","mumbai"};
char *t;
int i,j;
printf("n Before sorting the names of cities are >");
for(i=0;i<5;i++)
{
printf("n%s",name[i]);
}
for(i=1;i<5;i++)
{
for(j=0;j<5 i;j++)
{
if(strcmp(name[j],name[j+1])>0)
{
t=name[j];
name[j]=name[j+1];
name[j+1]=t;
}
}
}
printf("n After sorting the names of cities are >");
for(i=0;i<5;i++)
{
printf("n%s",name[i]);
}
}
Kanpur Institute of Technology
Computer concept and C programming -Question Bank-3
somnath.gupta123@gmail.com Page 11
QuestionQuestionQuestionQuestion8888 Define structure with syntax .Also write a program that compares two given dates. To store date
use structure say date that contains three members namely date, month and year. If the dates are equal then
display message as "Equal" otherwise "Unequal".
Answer
Structure
Structure is collection of data of dissimilar data types that are stored in adjacent memory location.
Two fundamental aspects of structures:
Declaration of a structure
Accessing of structure elements
Declaring a Structure:Declaring a Structure:Declaring a Structure:Declaring a Structure:
The general form of a structure declaration
struct structure_name
{
structure element 1 ;
structure element 2 ;
structure element 3 ;
} ;
Once the new structure data type has been defined, one or more variables can be declared to be of that type.
General form of declaring structure variable;
struct structure_name structure_variable;
Initialization of structure variable:Initialization of structure variable:Initialization of structure variable:Initialization of structure variable:
Like primary variables and arrays, structure variables can also be initialized where they are declared.
struct book
{
char name[10] ;
float price ;
int pages ;
} ;
struct book b1 = { "Basic", 130.00, 550 } ;
Kanpur Institute of Technology
Computer concept and C programming -Question Bank-3
somnath.gupta123@gmail.com Page 12
How Structure Elements areHow Structure Elements areHow Structure Elements areHow Structure Elements are StoredStoredStoredStored in Memoryin Memoryin Memoryin Memory????
Structure elements are always stored in contiguous memory locations.
b1.name b1.price b1.pages
Basic 130.00 550
65518 65528 65532
Accessing Structure ElementsAccessing Structure ElementsAccessing Structure ElementsAccessing Structure Elements
Structures elements are accessed using a dot (.) operator. For example, so to refer to pages of the structure
defined in program, we have to use, b1.pages. Similarly, to refer to price we would use, b1.price
NoteNoteNoteNote
Before the dot there must always be a structure variable and after the dot there must always be a
structure element.
/* A program to compare dates*//* A program to compare dates*//* A program to compare dates*//* A program to compare dates*/
#include<stdio.h>
struct date
{
int dd,mm,yy;
};
void main()
{
struct date d1,d2;
int i;
printf("n Enter first date ,month and year ");
scanf("%d%d%d",&d1.dd,&d1.mm,&d1.yy);
printf("n Enter second date ,month and year ");
scanf("%d%d%d",&d2.dd,&d2.mm,&d2.yy);
if((d1.dd==d2.dd)&& (d1.mm==d2.mm)&& (d1.yy==d2.yy))
printf("n Equal");
else
printf("n UnEqual");
}
Kanpur Institute of Technology
Computer concept and C programming -Question Bank-3
somnath.gupta123@gmail.com Page 13
QuestionQuestionQuestionQuestion 9999 Create a suitable structure for the preparation of award list for marks obtained in a single subject
using C for 500 students. Also display the roll no, name and marks of those students who secured greater than
70%.
AnswerAnswerAnswerAnswer
#include<stdio.h>
struct student
{
int rollno;
char name[10];
int marks;
};
void main()
{
struct student s[500];
int i;
printf("n Enter the roll number , name and marks >");
for(i=0;i<500;i++)
{
scanf("%d",&s[i].rollno);
gets(s[i].name);
scanf("%d",&s[i].marks);
}
printf("n Details of Those students who secure more than 70% ");
for(i=0;i<500;i++)
{
if(s[i].marks>70)
{
printf("%d",s[i].rollno);
puts(s[i].name);
printf("%d",s[i].marks);
}
}
}
Kanpur Institute of Technology
Computer concept and C programming -Question Bank-3
somnath.gupta123@gmail.com Page 14
QuestionQuestionQuestionQuestion 10101010–––– What is C Preprocessor? Explain various C preprocessor directives with example.
AnswerAnswerAnswerAnswer
CCCC PreprocessorPreprocessorPreprocessorPreprocessor
C preprocessor is a program that processes our source program before it is passed to the compiler.
Preprocessor directives in cPreprocessor directives in cPreprocessor directives in cPreprocessor directives in c
In c all the preprocessor directives start with # character. All the directives have different task which executes
just before the actual execution of c program which makes the program more portable. These directives are
used only to instruct compilers.
List all preprocessor directives in c.List all preprocessor directives in c.List all preprocessor directives in c.List all preprocessor directives in c.
#include directive in c#include directive in c#include directive in c#include directive in c
Task of include directive is to include or import any type file. There are two form of include directive.
SyntaxSyntaxSyntaxSyntax
#include <filename>
Or
#include “filename”
Kanpur Institute of Technology
Computer concept and C programming -Question Bank-3
somnath.gupta123@gmail.com Page 15
Form 1:Form 1:Form 1:Form 1:
#include<filename>: This statement will search the file in include directory. If that file is present then
#include statement is replaced by content of file. If that file is not present then it will cause of compilation
error.
Form 2:Form 2:Form 2:Form 2:
#include”filename”: This statement will first search the given file current working directory and if it is not
present then it will search include directory if it is also not present there then it will cause of compilation
error, unable to open the file. If that file is present then include statement is replaced by content of file.
# define directive in c# define directive in c# define directive in c# define directive in c
This directive is also called as Macro substitution directive. Task of macro substitution directive is to replace
the macro templates identifier with corresponding macro expansions.
Syntax:Syntax:Syntax:Syntax:
#define < macro templates> [(<Para1>, <Para2>)] < macro expansions >
NoteNoteNoteNote [] indicates optional term.
Example
#include<stdio.h>
#define pie 3.14
void main()
{
float r=3,area;
area = 3 * r * pie;
printf("%f",area);
}
ExplanationExplanationExplanationExplanation
In #define pie 3.14, pie is macro template and 3.14 are macro expansion. During preprocessing macro
template is replaced with macro expansion.
#if#if#if#if directive in cdirective in cdirective in cdirective in c
It is conditional compilation directive. That is if condition is true then it will compile the c programming code
otherwise it will not compile the c code.
SyntaxSyntaxSyntaxSyntax
#if <Constant_expression>
//Statements
#endif
Kanpur Institute of Technology
Computer concept and C programming -Question Bank-3
somnath.gupta123@gmail.com Page 16
If constant expression will return 0 then condition will true if it will return any non zero number condition
will true.
Example:Example:Example:Example:
#include<stdio.h>
#if 0
int main(){
printf("HELLO WORLD");
return 0;
}
#endif
Output:Output:Output:Output: Run time error, undefined symbol _main
Explanation:Explanation:Explanation:Explanation: Due to zero as a constant expression in #if condition will false. So c code inside the #if condition
will not execute. As we know without any main function we cannot execute any code.
Question 1Question 1Question 1Question 11111 What is Macros? How is it substituted? Write macro definition with arguments for calculation
of area and perimeter of a circle .Store these macro definitions in a file called “areaperi,h”. Include this file in
your program and call the macro definition for calculating area and perimeter for circle.
AnswerAnswerAnswerAnswer
# define directive in c# define directive in c# define directive in c# define directive in c
This directive is also called as Macro substitution directive or macromacromacromacro. Task of macro substitution directive is to
replace the macro templates identifier with corresponding macro expansions.
Syntax:Syntax:Syntax:Syntax:
#define < macro templates> [(<Para1>, <Para2>)] < macro expansions >
NoteNoteNoteNote [] indicates optional term.
ExampleExampleExampleExample
#include<stdio.h>
#define pie 3.14
void main()
{
float r=3,area;
area = 3 * r * pie;
printf("%f",area);
}
Kanpur Institute of Technology
Computer concept and C programming -Question Bank-3
somnath.gupta123@gmail.com Page 17
ExplanationExplanationExplanationExplanation
In #define pie 3.14, pie is macro template and 3.14 are macro expansion. During preprocessing macro
template is replaced with macro expansion.
/* A program macro with arguments for calculation of area and perimeter of a circle and rectangle */* A program macro with arguments for calculation of area and perimeter of a circle and rectangle */* A program macro with arguments for calculation of area and perimeter of a circle and rectangle */* A program macro with arguments for calculation of area and perimeter of a circle and rectangle *////
““““areaperi.hareaperi.hareaperi.hareaperi.h””””
#define PI 3.14
#define CArea(x) PI*x*x
#define CPeri(x) 2*PI*x
““““ProgramTest.cProgramTest.cProgramTest.cProgramTest.c””””
#include<stdio.h>
#include<areaperi.h>
void main()
{
int r;
float CA,CP;
printf("n Enter the radius of a circle ");
scanf("%d",r);
CA=CArea(r);
printf("n Radius of a circle is %f",CA);
CP=CPeri(r);
printf("n Perimeter of a circle is %f",CP);
}
QuestionQuestionQuestionQuestion12121212 What are the different file opening modes in C. Write a program to copy the contents of one file
into other file?
AnswerAnswerAnswerAnswer
File Opening ModesFile Opening ModesFile Opening ModesFile Opening Modes
The tasks performed by fopen( ) when a file is opened in each of these modes are
File ModeFile ModeFile ModeFile Mode OperationsOperationsOperationsOperations
"r""r""r""r" reading from the file.reading from the file.reading from the file.reading from the file.
It searches file. If the file is opened successfully, fopen( ) loadsitintomemory and sets up a pointer which points
to the first character in it. If the file cannot be opened fopen( ) returns NULL.
Kanpur Institute of Technology
Computer concept and C programming -Question Bank-3
somnath.gupta123@gmail.com Page 18
"w""w""w""w" writing to the file.writing to the file.writing to the file.writing to the file.
It searches file. If the file exists, its contents are overwritten. If the file doesn’t exist, a new file is created.
Returns NULL, if unable to open file.
"a""a""a""a" adding new contents at the end of file.adding new contents at the end of file.adding new contents at the end of file.adding new contents at the end of file.
It searches file. If the file is opened successfully fopen( ) loads it into memory and sets up a pointer that points
to the last character in it. If the file doesn’t exist, a new file is created. Returns NULL, if unable to open file.
"r+""r+""r+""r+" reading existing contents, writing new contents, modifying existing contents ofreading existing contents, writing new contents, modifying existing contents ofreading existing contents, writing new contents, modifying existing contents ofreading existing contents, writing new contents, modifying existing contents of the file.the file.the file.the file.
Searches file. If is opened successfully fopen( ) loads it into memory and sets up a pointer whichpointstothefirst
characterinit.ReturnsNULL,ifunabletoopenthefile.
"w+""w+""w+""w+" writing new contents, reading them back and modifying existing contents of thewriting new contents, reading them back and modifying existing contents of thewriting new contents, reading them back and modifying existing contents of thewriting new contents, reading them back and modifying existing contents of the file.file.file.file.
Searches file. If the file exists, its contents are overwritten. If the file doesn’t exist a new file is created. Returns
NULL, if unable to open file.
"a+""a+""a+""a+" reading existing contents, appending new contents to end of file. Cannotreading existing contents, appending new contents to end of file. Cannotreading existing contents, appending new contents to end of file. Cannotreading existing contents, appending new contents to end of file. Cannot modifyexistingcontents.modifyexistingcontents.modifyexistingcontents.modifyexistingcontents.
Searches file. If the file is opened successfully fopen( ) loads it into memory and sets up a pointer which points
to the first character in it. If the file doesn’t exist, a new file is created. Returns NULL, if unable to open file.
/*/*/*/*AAAA file copy program which copies the file “prog.c” to “prog.old”file copy program which copies the file “prog.c” to “prog.old”file copy program which copies the file “prog.c” to “prog.old”file copy program which copies the file “prog.c” to “prog.old” */*/*/*/
#include <stdio.h>
void main()
{
FILE *fp1, *fp2, *fopen();
char ch ;
fp1 = fopen( “prog.c”, “r” ); /* open for reading */
fp2 = fopen( “prog.old”, “w” ) ; ../* open for writing */
if ( fp1 == NULL ) /* check does file exist etc */
{
printf(“Cannot open prog.c for reading n” );
}
if ( fp2 == NULL )
{
printf(“Cannot open prog.old for writing n”);
}
Kanpur Institute of Technology
Computer concept and C programming -Question Bank-3
somnath.gupta123@gmail.com Page 19
while(1)
{
ch = getc(fp1) ;
if( ch== EOF)
{
break;
}
putc( c, fp2); /* copy to prog.old */
}
fclose ( fp1 ); /* Now close files */
fclose ( fp2 );
}
QuestionQuestionQuestionQuestion13131313 Write a program to compare two files specified by the user, displaying a message indicating
whether the files are identical or different. Both files should be read by the user.
AnswerAnswerAnswerAnswer
/*A program to/*A program to/*A program to/*A program to compare two files */compare two files */compare two files */compare two files */
#include <stdio.h>
void main()
{
FILE *fp1, *fp2;
int ca, cb;
char fname1[40], fname2[40] ;
printf(“Enter first filename:”) ;
gets(fname1);
printf(“Enter second filename:”);
gets(fname2);
fp1 = fopen( fname1, “r” ); /* open for reading */
fp2 = fopen( fname2, “r” ) ; /* open for writing */
if ( fp1 == NULL ) /* check does file exist etc */
{
printf(“Cannot open for reading n”);
exit(1); /* terminate program */
}
if ( fp2 == NULL )
Kanpur Institute of Technology
Computer concept and C programming -Question Bank-3
somnath.gupta123@gmail.com Page 20
{
printf(“Cannot open for reading n”, );
exit(1); /* terminate program */
}
else /* both files opened successfully */
{
ca = getc( fp1 ) ;
cb = getc( fp2 ) ;
while ( ca != EOF && cb != EOF && ca == cb )
{
ca = getc( fp1 ) ;
cb = getc( fp2 ) ;
}
if ( ca == cb )
printf(“Files are identical n”);
else if ( ca != cb )
printf(“Files differ n” );
fclose ( fp1 );
fclose ( fp2 );
}
}
QuestionQuestionQuestionQuestion 14141414––––Write short notes on following
A. Command line argument.
B. dynamic memory allocation and various functions for dynamic memory allocation
C. Stack with push and pop operation
D. Linked list
AnswerAnswerAnswerAnswer
A.A.A.A. Accepting command line argumentsAccepting command line argumentsAccepting command line argumentsAccepting command line arguments
Command line arguments are given after the name of a program in command line operating systems like
DOS or Linux, and are passed in to the program from the operating system.
To use command line arguments in your program, first understand the full declaration of the main function.
In fact, main can actually accept two arguments: one argument is number of command line arguments, and
the other argument is a full list of all of the command line arguments.
Kanpur Institute of Technology
Computer concept and C programming -Question Bank-3
somnath.gupta123@gmail.com Page 21
The full declaration of main looks like this:
int main ( int argc, char *argv[] )
The integer, argc is the argument count. It is the number of arguments passed into the program from the
command line, including the name of the program.
The argv is array of character pointers that contains the list of all the arguments. argv[0] is the name of the
program, or an empty string if the name is not available. After that, every element number less than argc is a
command line argument.
/* A program to find the length of a string which is given through command prompt. Program should give the
output as follows:
C:>length Hello
Length of string “Hello” is 5 */
AnswerAnswerAnswerAnswer
#include<stdio.h>
int main(int argc ,char *argv[])
{
char str[]=argv[1];
int len,i;
len=0;
for(i=0;str[i]!='0';i++)
{
len++;
}
printf("n Length of the string %s is %d",str,len);
}
B.B.B.B. DDDDynamic memory allocation and various functions for dynamic memory allocationynamic memory allocation and various functions for dynamic memory allocationynamic memory allocation and various functions for dynamic memory allocationynamic memory allocation and various functions for dynamic memory allocation
Dynamic memory allocation is also known as heap based memory allocation. It is used to allocate memory
dynamically at runtime. Dynamically allocated memory exists until it is released internally (by Garbage
Collector) or externally (by User).
Allocating new heap memoryAllocating new heap memoryAllocating new heap memoryAllocating new heap memory
voidvoidvoidvoid *malloc(size_t*malloc(size_t*malloc(size_t*malloc(size_t size);size);size);size);
Allocate a block of size bytes,return a pointer to the block.(NULL if unable to allocate block)
Kanpur Institute of Technology
Computer concept and C programming -Question Bank-3
somnath.gupta123@gmail.com Page 22
voidvoidvoidvoid *calloc(size_t*calloc(size_t*calloc(size_t*calloc(size_t num_elements, size_tnum_elements, size_tnum_elements, size_tnum_elements, size_t element_size);element_size);element_size);element_size);
Allocate a block of num_elements * element_size bytes, initialize every byte to zero, return pointer to the
block. (NULL if unable to allocate block)
void *realloc(voidvoid *realloc(voidvoid *realloc(voidvoid *realloc(void *ptr, size_t*ptr, size_t*ptr, size_t*ptr, size_t new_size);new_size);new_size);new_size);
Used to increase or decrease memory size that was previously allocated.
Given a previously allocated block starting at ptr,change the block size to new_size, return pointer to
resized block. If block size is increased, contents of old block may be copied to a completely different
region.
Deallocating heap memoryDeallocating heap memoryDeallocating heap memoryDeallocating heap memory
void free(void *pointer);void free(void *pointer);void free(void *pointer);void free(void *pointer);
It is used to deallocate memory that was previously allocated.
C. StackStackStackStack –––– Stack is linear data structure in which items are inserted and deleted at one end called top of the
stack. It is also called LIFO. It means the item that comes last into the stack; get removed first (LIFO) order.
Stack OperationsStack OperationsStack OperationsStack Operations – Stack has two operations
1. Push () is used to add an item into stack.
2. Pop () is used to remove an item from the stack.
Any operation can perform only at TOP end of the stack. It means any item input or output can be done form
TOP end.
PUSH operationPUSH operationPUSH operationPUSH operation –––– Adding an item in the stack is called PUSH operation and when we add an item into stack
the TOP pointer is incremented
Algorithm of PUSH operationAlgorithm of PUSH operationAlgorithm of PUSH operationAlgorithm of PUSH operation
An array STK [N] is stack.
1. IF Top = N then [print “STACK is Full”] and exit.
2. Top = Top + 1
3. STK [ TOP ] = ‘Element’
4. END
somnath.gupta123@gmail.com
Pop OperationPop OperationPop OperationPop Operation –––– To remove an item from the stack is called
required to be checked whether the stack is containing any item in it or it is already empty (i.e. TOP = 0)
Algorithm of POP operationAlgorithm of POP operationAlgorithm of POP operationAlgorithm of POP operation ––––
1. If TOP = Null then [print “stack is already empty”] and exit.
2. element = STK [Top]
3. Top = Top – 1
4. END
D.D.D.D. Linked ListLinked ListLinked ListLinked List
A linked list is collections of nodes that consists of two fields, one containing the information about that node,
data and second contain the address of next node.
Such a structure is represented as follows:
struct node
{
int data;
struct node *next;
};
Types of Linked ListTypes of Linked ListTypes of Linked ListTypes of Linked List
1. Linear Singly linked listLinear Singly linked listLinear Singly linked listLinear Singly linked list: A list type in which each node points to the
2. Circular linked list:Circular linked list:Circular linked list:Circular linked list: Lists which have no beginning and no end. The last
3. Doubly linked list or TwoDoubly linked list or TwoDoubly linked list or TwoDoubly linked list or Two way linked listway linked listway linked listway linked list
node and other pointing to the previous
Kanpur Institute of Technology
Computer concept and C programming
To remove an item from the stack is called POP operation Before removing an item, it is
required to be checked whether the stack is containing any item in it or it is already empty (i.e. TOP = 0)
print “stack is already empty”] and exit.
nodes that consists of two fields, one containing the information about that node,
and second contain the address of next node.
follows:
Node
Data Next
: A list type in which each node points to the next node and the last node points to NULL.
Lists which have no beginning and no end. The last node points back to the first
way linked listway linked listway linked listway linked list: These lists contain double set of pointers, one pointing to the next
vious node. So one can traverse the list in either direction.
Kanpur Institute of Technology
Computer concept and C programming -Question Bank-3
Page 23
operation Before removing an item, it is
required to be checked whether the stack is containing any item in it or it is already empty (i.e. TOP = 0)
nodes that consists of two fields, one containing the information about that node,
node and the last node points to NULL.
node points back to the first node.
pointers, one pointing to the next
one can traverse the list in either direction.

Mais conteúdo relacionado

Mais procurados

Dynamic memory allocation in c++
Dynamic memory allocation in c++Dynamic memory allocation in c++
Dynamic memory allocation in c++
Tech_MX
 
仕事で使うF#
仕事で使うF#仕事で使うF#
仕事で使うF#
bleis tift
 

Mais procurados (20)

Functional programming
Functional programmingFunctional programming
Functional programming
 
CS4200 2019 | Lecture 2 | syntax-definition
CS4200 2019 | Lecture 2 | syntax-definitionCS4200 2019 | Lecture 2 | syntax-definition
CS4200 2019 | Lecture 2 | syntax-definition
 
Function Applicative for Great Good of Palindrome Checker Function - Polyglot...
Function Applicative for Great Good of Palindrome Checker Function - Polyglot...Function Applicative for Great Good of Palindrome Checker Function - Polyglot...
Function Applicative for Great Good of Palindrome Checker Function - Polyglot...
 
Functional programming ii
Functional programming iiFunctional programming ii
Functional programming ii
 
C Programming Unit-3
C Programming Unit-3C Programming Unit-3
C Programming Unit-3
 
C Assignment Help
C Assignment HelpC Assignment Help
C Assignment Help
 
Idiomatic C++
Idiomatic C++Idiomatic C++
Idiomatic C++
 
Fun with functions
Fun with functionsFun with functions
Fun with functions
 
Python The basics
Python   The basicsPython   The basics
Python The basics
 
C++ references
C++ referencesC++ references
C++ references
 
Dynamic memory allocation in c++
Dynamic memory allocation in c++Dynamic memory allocation in c++
Dynamic memory allocation in c++
 
仕事で使うF#
仕事で使うF#仕事で使うF#
仕事で使うF#
 
Programming Homework Help
Programming Homework Help Programming Homework Help
Programming Homework Help
 
Hooking signals and dumping the callstack
Hooking signals and dumping the callstackHooking signals and dumping the callstack
Hooking signals and dumping the callstack
 
Python-02| Input, Output & Import
Python-02| Input, Output & ImportPython-02| Input, Output & Import
Python-02| Input, Output & Import
 
Python programming
Python  programmingPython  programming
Python programming
 
Advanced C - Part 2
Advanced C - Part 2Advanced C - Part 2
Advanced C - Part 2
 
Arrays
ArraysArrays
Arrays
 
BayFP: Concurrent and Multicore Haskell
BayFP: Concurrent and Multicore HaskellBayFP: Concurrent and Multicore Haskell
BayFP: Concurrent and Multicore Haskell
 
Pointers & References in C++
Pointers & References in C++Pointers & References in C++
Pointers & References in C++
 

Destaque (13)

Student Voice 2011_2012
Student Voice 2011_2012Student Voice 2011_2012
Student Voice 2011_2012
 
The truth is out there
The truth is out thereThe truth is out there
The truth is out there
 
El cuerpo humano
El cuerpo humanoEl cuerpo humano
El cuerpo humano
 
The right-fit-how-top-employers-find-the-perfect-candidate
The right-fit-how-top-employers-find-the-perfect-candidateThe right-fit-how-top-employers-find-the-perfect-candidate
The right-fit-how-top-employers-find-the-perfect-candidate
 
Shooting Schedule
Shooting ScheduleShooting Schedule
Shooting Schedule
 
Pág. 3 6
Pág. 3   6Pág. 3   6
Pág. 3 6
 
CV Aleem
CV AleemCV Aleem
CV Aleem
 
Abramova_O_poster presentation_Eafo
Abramova_O_poster presentation_EafoAbramova_O_poster presentation_Eafo
Abramova_O_poster presentation_Eafo
 
Cuidados del agua
Cuidados del aguaCuidados del agua
Cuidados del agua
 
Unlock the future of mobile growth
Unlock the future of mobile growthUnlock the future of mobile growth
Unlock the future of mobile growth
 
ETDs in Agriculture
ETDs in AgricultureETDs in Agriculture
ETDs in Agriculture
 
Beta Staff Detailed Profile 2015
Beta Staff Detailed Profile 2015Beta Staff Detailed Profile 2015
Beta Staff Detailed Profile 2015
 
Ryerson Arch Cons Diploma
Ryerson Arch Cons DiplomaRyerson Arch Cons Diploma
Ryerson Arch Cons Diploma
 

Semelhante a C q 3

Lecture 15_Strings and Dynamic Memory Allocation.pptx
Lecture 15_Strings and  Dynamic Memory Allocation.pptxLecture 15_Strings and  Dynamic Memory Allocation.pptx
Lecture 15_Strings and Dynamic Memory Allocation.pptx
JawadTanvir
 
06 -working_with_strings
06  -working_with_strings06  -working_with_strings
06 -working_with_strings
Hector Garzo
 
Frequency .java Word frequency counter package frequ.pdf
Frequency .java  Word frequency counter  package frequ.pdfFrequency .java  Word frequency counter  package frequ.pdf
Frequency .java Word frequency counter package frequ.pdf
arshiartpalace
 

Semelhante a C q 3 (20)

Strings in c
Strings in cStrings in c
Strings in c
 
Strings part2
Strings part2Strings part2
Strings part2
 
Strings
StringsStrings
Strings
 
[ITP - Lecture 17] Strings in C/C++
[ITP - Lecture 17] Strings in C/C++[ITP - Lecture 17] Strings in C/C++
[ITP - Lecture 17] Strings in C/C++
 
Strings
StringsStrings
Strings
 
9 character string &amp; string library
9  character string &amp; string library9  character string &amp; string library
9 character string &amp; string library
 
String notes
String notesString notes
String notes
 
Lecture 15_Strings and Dynamic Memory Allocation.pptx
Lecture 15_Strings and  Dynamic Memory Allocation.pptxLecture 15_Strings and  Dynamic Memory Allocation.pptx
Lecture 15_Strings and Dynamic Memory Allocation.pptx
 
Team 1
Team 1Team 1
Team 1
 
c programming
c programmingc programming
c programming
 
introduction to strings in c programming
introduction to strings in c programmingintroduction to strings in c programming
introduction to strings in c programming
 
06 -working_with_strings
06  -working_with_strings06  -working_with_strings
06 -working_with_strings
 
Strings
StringsStrings
Strings
 
Find an LCS of X = and Y = Show the c and b table. Attach File .docx
  Find an LCS of X =  and Y =   Show the c and b table.  Attach File  .docx  Find an LCS of X =  and Y =   Show the c and b table.  Attach File  .docx
Find an LCS of X = and Y = Show the c and b table. Attach File .docx
 
Unitii string
Unitii stringUnitii string
Unitii string
 
Frequency .java Word frequency counter package frequ.pdf
Frequency .java  Word frequency counter  package frequ.pdfFrequency .java  Word frequency counter  package frequ.pdf
Frequency .java Word frequency counter package frequ.pdf
 
Computer programming 2 Lesson 12
Computer programming 2  Lesson 12Computer programming 2  Lesson 12
Computer programming 2 Lesson 12
 
14 strings
14 strings14 strings
14 strings
 
Strings
StringsStrings
Strings
 
Strings
StringsStrings
Strings
 

Último

1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
QucHHunhnh
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please Practise
AnaAcapella
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
heathfieldcps1
 
Vishram Singh - Textbook of Anatomy Upper Limb and Thorax.. Volume 1 (1).pdf
Vishram Singh - Textbook of Anatomy  Upper Limb and Thorax.. Volume 1 (1).pdfVishram Singh - Textbook of Anatomy  Upper Limb and Thorax.. Volume 1 (1).pdf
Vishram Singh - Textbook of Anatomy Upper Limb and Thorax.. Volume 1 (1).pdf
ssuserdda66b
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
ZurliaSoop
 

Último (20)

FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please Practise
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
Vishram Singh - Textbook of Anatomy Upper Limb and Thorax.. Volume 1 (1).pdf
Vishram Singh - Textbook of Anatomy  Upper Limb and Thorax.. Volume 1 (1).pdfVishram Singh - Textbook of Anatomy  Upper Limb and Thorax.. Volume 1 (1).pdf
Vishram Singh - Textbook of Anatomy Upper Limb and Thorax.. Volume 1 (1).pdf
 
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxSKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - English
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 

C q 3

  • 1. Kanpur Institute of Technology Computer concept and C programming -Question Bank-3 somnath.gupta123@gmail.com Page 1 Question1Question1Question1Question1 What is string? Also explain different string functions with examples. Answer StringsStringsStringsStrings A group of characters can be stored in a character array. Character arrays are also called strings. Character arrays or strings are used to manipulate text such as words and sentences. A string constant is a one dimensional array of characters terminated by a null (‘0’). EEEExamplexamplexamplexample char name[ ] = { 'H', 'A', 'E', 'S', 'L', 'E', 'R', '0' } ; Each character in the array occupies one byte of memory and the last character is always ‘0’. ‘0’ is called null character. ASCII value of ‘0’ is 0. Memory Representation of character ArrayMemory Representation of character ArrayMemory Representation of character ArrayMemory Representation of character Array The elements of the character array are stored in contiguous memory locations. The above string can also be initialized as char name[ ] = "HAESLER" ; NoteNoteNoteNote In this declaration ‘0’ is not necessary. C inserts the null character automatically. Standard Library String FunctionsStandard Library String FunctionsStandard Library String FunctionsStandard Library String Functions FunctionFunctionFunctionFunction UseUseUseUse Strlen Finds length of a string Strcpy Copies a string into another strcmp Compares two strings strcat Appends one string at the end of another Strrev Reverses string strupr Converts a string to uppercase Strlwr Converts a string to lowercase
  • 2. Kanpur Institute of Technology Computer concept and C programming -Question Bank-3 somnath.gupta123@gmail.com Page 2 strlen( )strlen( )strlen( )strlen( ) FunctionFunctionFunctionFunction ExplanationExplanationExplanationExplanation This function counts the number of characters present in a string i.e. find length of the string. int strlen(string); ExampleExampleExampleExample /*A program to find the length of input string using string/*A program to find the length of input string using string/*A program to find the length of input string using string/*A program to find the length of input string using string function*/function*/function*/function*/ #include<string.h> void main() { char str[100]; int len; printf("n Enter the string "); gets(str); len=strlen(str); printf("n The length of the string is =%d",len); } OutputOutputOutputOutput Enter the string Humpty Dumpty The length of the string is = 13 strcpy (strcpy (strcpy (strcpy ( )))) FunctionFunctionFunctionFunction Explanation This function copies the contents of source string into target string. strcpy(target,source); ExampleExampleExampleExample /*A program to copy of one string into other string using string function*//*A program to copy of one string into other string using string function*//*A program to copy of one string into other string using string function*//*A program to copy of one string into other string using string function*/ #include<string.h> void main() { char str1[100],str2[100]; printf("n Enter the string "); gets(str1); strcpy(str2,str1); printf("n The input string is %s",str1); printf("n The copy of input string is >%s",str2); }
  • 3. Kanpur Institute of Technology Computer concept and C programming -Question Bank-3 somnath.gupta123@gmail.com Page 3 OutputOutputOutputOutput Enter the string Kanpur The input string is Kanpur The copy of input string is >Kanpur strcat (strcat (strcat (strcat ( )))) FunctionFunctionFunctionFunction ExplanationExplanationExplanationExplanation This function appends the source string at the end of the target string. For example, “Bombay” and “Nagpur” on concatenation would result into a string “BombayNagpur”. /* A Program to append one string at the end of other string using strcat( ) function*//* A Program to append one string at the end of other string using strcat( ) function*//* A Program to append one string at the end of other string using strcat( ) function*//* A Program to append one string at the end of other string using strcat( ) function*/ #include<string.h> void main() { char str1[10],str2[10]; printf("nEnter the first string "); gets(str1); printf("nEnter the second string "); gets(str2); strcat(str1,str2); // append str2 at the end of str1 printf("nAppend string is "); puts(str1); // display str1 } OutputOutputOutputOutput Enter the first string Bombay Enter the second string Nagpur Append string is BombayNagpur strcmp(strcmp(strcmp(strcmp( )))) FunctionFunctionFunctionFunction This function compares two strings to find out whether they are identical or different. The two strings are compared character by character until there is a mismatch or end of one of the strings is reached, whichever occurs first. If the two strings are identical, strcmp( ) returns a value zero. If they’re not, it returns the numeric difference between the ASCII values of the first non matching pairs of characters.
  • 4. Kanpur Institute of Technology Computer concept and C programming -Question Bank-3 somnath.gupta123@gmail.com Page 4 ExampleExampleExampleExample /* A Program to compare one string to other string using strcmp( ) fu/* A Program to compare one string to other string using strcmp( ) fu/* A Program to compare one string to other string using strcmp( ) fu/* A Program to compare one string to other string using strcmp( ) function*/nction*/nction*/nction*/ #include<string.h> void main() { int r; char str1[10],str2[10]; printf("Enter the first string n"); gets(str1); printf("Enter the second string n"); gets(str2); r=strcmp(str1,str2); if(r==0) printf("n files are identical"); else printf("n files are not identical"); } Question 2Question 2Question 2Question 2 Write a user defined function to copy of one string into other string. Answer /*A program to copy of one string into other string without using string function*//*A program to copy of one string into other string without using string function*//*A program to copy of one string into other string without using string function*//*A program to copy of one string into other string without using string function*/ #include<stdio.h> void xstrcpy(char *ptr2,char *ptr1); //prototype declaration void main() { char str1[100],str2[100]; printf("n Enter the string "); gets(str1); printf("n The input string is %s",str1); xstrcpy(str2,str1); printf("n The copy of input string is >%s",str2); } void xstrcpy(char *ptr2,char *ptr1) {
  • 5. Kanpur Institute of Technology Computer concept and C programming -Question Bank-3 somnath.gupta123@gmail.com Page 5 while(*ptr1!='0') { *ptr2=*ptr1; ptr1++; ptr2++; } *ptr2='0'; } OutputOutputOutputOutput Enter the string Kanpur The input string is Kanpur The copy of input string is Kanpur Question 3Question 3Question 3Question 3 Write a user defined function to append two strings. Answer // A program to append two string without using string function #include<stdio.h> void xstrcat(char *t,char *s1); //function prototype declaration void main() { char str1[10],str2[10],str3[20]; printf("nEnter the first string "); gets(str1); printf("nEnter the second string "); gets(str2); xstrcat(str1,str2); printf("nAppend string is >"); puts(str1); } void xstrcat(char *t, char *s) { while(*t!='0') { t++;
  • 6. Kanpur Institute of Technology Computer concept and C programming -Question Bank-3 somnath.gupta123@gmail.com Page 6 } while(*s!='0') { *t=*s; t++; s++; } *t='0'; } OutputOutputOutputOutput Enter the first string Bombay Enter the second string Nagpur Append string is BombayNagpur Question 4Question 4Question 4Question 4 Write a user defined function to compare two strings where they are identical or not. Answer /*/*/*/* A program to compare the two string without using string functionA program to compare the two string without using string functionA program to compare the two string without using string functionA program to compare the two string without using string function */*/*/*/ #include<stdio.h> #include<conio.h> int xstrcmp(char *,char *); //function prototype declaration void main() { int r; char str1[10],str2[10]; printf("Enter the first string n"); gets(str1); printf("Enter the second string n"); gets(str2); r=xstrcmp(str1,str2); if(r==0) { printf(" n both strings are identical"); } else {
  • 7. Kanpur Institute of Technology Computer concept and C programming -Question Bank-3 somnath.gupta123@gmail.com Page 7 printf("n Both strings are not identical"); } } int xstrcmp(char *ptr1,char *ptr2) { int i=0; while(*ptr1!='0' || *ptr2!=’0’) { if(*ptr1!=*ptr2) { break; } ptr1++; ptr2++; } return *ptr1 *ptr2; } Question5Question5Question5Question5 –––– How the two dimensional character array has been initialized? What are the drawbacks of it? How can we overcome it? Answer InitializationInitializationInitializationInitialization twotwotwotwo dimensional character arraydimensional character arraydimensional character arraydimensional character array char masterlist[6][10] = { "akshay", "parag", "raman", "srinivas", "gopal", "rajesh" } ; The first subscript gives the number of names in the array, while the second subscript gives the length of each item in the array.
  • 8. Kanpur Institute of Technology Computer concept and C programming -Question Bank-3 somnath.gupta123@gmail.com Page 8 Here 65454, 65464, 65474, is base addresses of successive names. Here 10 byte are reserved for storing the name “akshay”, it occupies only 7 bytes. Thus 3 bytes go waste. Similarly for each name, some amount offor each name, some amount offor each name, some amount offor each name, some amount of memories gomemories gomemories gomemories go wastagewastagewastagewastage.... ThisThisThisThis can be avoided by ucan be avoided by ucan be avoided by ucan be avoided by using array of pointer.sing array of pointer.sing array of pointer.sing array of pointer. Array of Pointers to StringsArray of Pointers to StringsArray of Pointers to StringsArray of Pointers to Strings A pointer variable always contains an address. Therefore, if we construct an array of pointers it would contain a number of addresses. Let us see how the names in the earlier example can be stored in the array of pointers. char *names[ ] = { "akshay", "parag", "raman", "srinivas", "gopal", "rajesh" } ; In this declaration names[ ] is an array of pointers. It contains base addresses of respective names. That is, base address of “akshay” is stored in names[0], base address of “parag” is stored in names[1] and so on. Advantages of array of pointer overAdvantages of array of pointer overAdvantages of array of pointer overAdvantages of array of pointer over 2222 D array:D array:D array:D array: In the two dimensional array of characters, the strings occupied 60 bytes. As against this, in array of pointers, the strings occupy only 41 bytes a net saving of 19 bytes. Another reason to use an array of pointers to store strings is to obtain greater ease in manipulation of the strings.
  • 9. Kanpur Institute of Technology Computer concept and C programming -Question Bank-3 somnath.gupta123@gmail.com Page 9 QuestionQuestionQuestionQuestion 6666––––Initialize a 2 D character array with "akshay", "parag", "raman", "srinivas", "gopal", "rajesh". Read a name from the keyboard and find that name is available or not. Answer /* A program to/* A program to/* A program to/* A program to find name in the 2find name in the 2find name in the 2find name in the 2 D character array */D character array */D character array */D character array */ #include<stdio.h> void main( ) { char masterlist[6][10] = { "akshay", "parag", "raman", "srinivas", "gopal", "rajesh" } ; int i, flag, a ; char name[10] ; printf ( "n Enter name " ) ; scanf ( "%s",name ) ; flag = 0 ; for ( i = 0 ; i <= 5 ; i++ ) { a = strcmp ( &masterlist[i][0],name ) ; if ( a == 0 ) { printf ( "n Name is available " ) ; flag = 1 ; break ; } } if ( flag ==0 ) printf ( "n Sorry not available!" ) ; } OutpuOutpuOutpuOutputttt Enter your name dinesh Sorry not available! Enter your name raman Name is available
  • 10. Kanpur Institute of Technology Computer concept and C programming -Question Bank-3 somnath.gupta123@gmail.com Page 10 QuestionQuestionQuestionQuestion 7777 Write a program to sort a set of names stored in alphabetical order using array of pointer to string. AnswerAnswerAnswerAnswer /*/*/*/*A program to sort the names of citiesA program to sort the names of citiesA program to sort the names of citiesA program to sort the names of cities alphabetically using array of pointer */alphabetically using array of pointer */alphabetically using array of pointer */alphabetically using array of pointer */ #include<stdio.h> #include<string.h> void main() { char *name[]={"kanpur","indore","delhi","lucknow","mumbai"}; char *t; int i,j; printf("n Before sorting the names of cities are >"); for(i=0;i<5;i++) { printf("n%s",name[i]); } for(i=1;i<5;i++) { for(j=0;j<5 i;j++) { if(strcmp(name[j],name[j+1])>0) { t=name[j]; name[j]=name[j+1]; name[j+1]=t; } } } printf("n After sorting the names of cities are >"); for(i=0;i<5;i++) { printf("n%s",name[i]); } }
  • 11. Kanpur Institute of Technology Computer concept and C programming -Question Bank-3 somnath.gupta123@gmail.com Page 11 QuestionQuestionQuestionQuestion8888 Define structure with syntax .Also write a program that compares two given dates. To store date use structure say date that contains three members namely date, month and year. If the dates are equal then display message as "Equal" otherwise "Unequal". Answer Structure Structure is collection of data of dissimilar data types that are stored in adjacent memory location. Two fundamental aspects of structures: Declaration of a structure Accessing of structure elements Declaring a Structure:Declaring a Structure:Declaring a Structure:Declaring a Structure: The general form of a structure declaration struct structure_name { structure element 1 ; structure element 2 ; structure element 3 ; } ; Once the new structure data type has been defined, one or more variables can be declared to be of that type. General form of declaring structure variable; struct structure_name structure_variable; Initialization of structure variable:Initialization of structure variable:Initialization of structure variable:Initialization of structure variable: Like primary variables and arrays, structure variables can also be initialized where they are declared. struct book { char name[10] ; float price ; int pages ; } ; struct book b1 = { "Basic", 130.00, 550 } ;
  • 12. Kanpur Institute of Technology Computer concept and C programming -Question Bank-3 somnath.gupta123@gmail.com Page 12 How Structure Elements areHow Structure Elements areHow Structure Elements areHow Structure Elements are StoredStoredStoredStored in Memoryin Memoryin Memoryin Memory???? Structure elements are always stored in contiguous memory locations. b1.name b1.price b1.pages Basic 130.00 550 65518 65528 65532 Accessing Structure ElementsAccessing Structure ElementsAccessing Structure ElementsAccessing Structure Elements Structures elements are accessed using a dot (.) operator. For example, so to refer to pages of the structure defined in program, we have to use, b1.pages. Similarly, to refer to price we would use, b1.price NoteNoteNoteNote Before the dot there must always be a structure variable and after the dot there must always be a structure element. /* A program to compare dates*//* A program to compare dates*//* A program to compare dates*//* A program to compare dates*/ #include<stdio.h> struct date { int dd,mm,yy; }; void main() { struct date d1,d2; int i; printf("n Enter first date ,month and year "); scanf("%d%d%d",&d1.dd,&d1.mm,&d1.yy); printf("n Enter second date ,month and year "); scanf("%d%d%d",&d2.dd,&d2.mm,&d2.yy); if((d1.dd==d2.dd)&& (d1.mm==d2.mm)&& (d1.yy==d2.yy)) printf("n Equal"); else printf("n UnEqual"); }
  • 13. Kanpur Institute of Technology Computer concept and C programming -Question Bank-3 somnath.gupta123@gmail.com Page 13 QuestionQuestionQuestionQuestion 9999 Create a suitable structure for the preparation of award list for marks obtained in a single subject using C for 500 students. Also display the roll no, name and marks of those students who secured greater than 70%. AnswerAnswerAnswerAnswer #include<stdio.h> struct student { int rollno; char name[10]; int marks; }; void main() { struct student s[500]; int i; printf("n Enter the roll number , name and marks >"); for(i=0;i<500;i++) { scanf("%d",&s[i].rollno); gets(s[i].name); scanf("%d",&s[i].marks); } printf("n Details of Those students who secure more than 70% "); for(i=0;i<500;i++) { if(s[i].marks>70) { printf("%d",s[i].rollno); puts(s[i].name); printf("%d",s[i].marks); } } }
  • 14. Kanpur Institute of Technology Computer concept and C programming -Question Bank-3 somnath.gupta123@gmail.com Page 14 QuestionQuestionQuestionQuestion 10101010–––– What is C Preprocessor? Explain various C preprocessor directives with example. AnswerAnswerAnswerAnswer CCCC PreprocessorPreprocessorPreprocessorPreprocessor C preprocessor is a program that processes our source program before it is passed to the compiler. Preprocessor directives in cPreprocessor directives in cPreprocessor directives in cPreprocessor directives in c In c all the preprocessor directives start with # character. All the directives have different task which executes just before the actual execution of c program which makes the program more portable. These directives are used only to instruct compilers. List all preprocessor directives in c.List all preprocessor directives in c.List all preprocessor directives in c.List all preprocessor directives in c. #include directive in c#include directive in c#include directive in c#include directive in c Task of include directive is to include or import any type file. There are two form of include directive. SyntaxSyntaxSyntaxSyntax #include <filename> Or #include “filename”
  • 15. Kanpur Institute of Technology Computer concept and C programming -Question Bank-3 somnath.gupta123@gmail.com Page 15 Form 1:Form 1:Form 1:Form 1: #include<filename>: This statement will search the file in include directory. If that file is present then #include statement is replaced by content of file. If that file is not present then it will cause of compilation error. Form 2:Form 2:Form 2:Form 2: #include”filename”: This statement will first search the given file current working directory and if it is not present then it will search include directory if it is also not present there then it will cause of compilation error, unable to open the file. If that file is present then include statement is replaced by content of file. # define directive in c# define directive in c# define directive in c# define directive in c This directive is also called as Macro substitution directive. Task of macro substitution directive is to replace the macro templates identifier with corresponding macro expansions. Syntax:Syntax:Syntax:Syntax: #define < macro templates> [(<Para1>, <Para2>)] < macro expansions > NoteNoteNoteNote [] indicates optional term. Example #include<stdio.h> #define pie 3.14 void main() { float r=3,area; area = 3 * r * pie; printf("%f",area); } ExplanationExplanationExplanationExplanation In #define pie 3.14, pie is macro template and 3.14 are macro expansion. During preprocessing macro template is replaced with macro expansion. #if#if#if#if directive in cdirective in cdirective in cdirective in c It is conditional compilation directive. That is if condition is true then it will compile the c programming code otherwise it will not compile the c code. SyntaxSyntaxSyntaxSyntax #if <Constant_expression> //Statements #endif
  • 16. Kanpur Institute of Technology Computer concept and C programming -Question Bank-3 somnath.gupta123@gmail.com Page 16 If constant expression will return 0 then condition will true if it will return any non zero number condition will true. Example:Example:Example:Example: #include<stdio.h> #if 0 int main(){ printf("HELLO WORLD"); return 0; } #endif Output:Output:Output:Output: Run time error, undefined symbol _main Explanation:Explanation:Explanation:Explanation: Due to zero as a constant expression in #if condition will false. So c code inside the #if condition will not execute. As we know without any main function we cannot execute any code. Question 1Question 1Question 1Question 11111 What is Macros? How is it substituted? Write macro definition with arguments for calculation of area and perimeter of a circle .Store these macro definitions in a file called “areaperi,h”. Include this file in your program and call the macro definition for calculating area and perimeter for circle. AnswerAnswerAnswerAnswer # define directive in c# define directive in c# define directive in c# define directive in c This directive is also called as Macro substitution directive or macromacromacromacro. Task of macro substitution directive is to replace the macro templates identifier with corresponding macro expansions. Syntax:Syntax:Syntax:Syntax: #define < macro templates> [(<Para1>, <Para2>)] < macro expansions > NoteNoteNoteNote [] indicates optional term. ExampleExampleExampleExample #include<stdio.h> #define pie 3.14 void main() { float r=3,area; area = 3 * r * pie; printf("%f",area); }
  • 17. Kanpur Institute of Technology Computer concept and C programming -Question Bank-3 somnath.gupta123@gmail.com Page 17 ExplanationExplanationExplanationExplanation In #define pie 3.14, pie is macro template and 3.14 are macro expansion. During preprocessing macro template is replaced with macro expansion. /* A program macro with arguments for calculation of area and perimeter of a circle and rectangle */* A program macro with arguments for calculation of area and perimeter of a circle and rectangle */* A program macro with arguments for calculation of area and perimeter of a circle and rectangle */* A program macro with arguments for calculation of area and perimeter of a circle and rectangle *//// ““““areaperi.hareaperi.hareaperi.hareaperi.h”””” #define PI 3.14 #define CArea(x) PI*x*x #define CPeri(x) 2*PI*x ““““ProgramTest.cProgramTest.cProgramTest.cProgramTest.c”””” #include<stdio.h> #include<areaperi.h> void main() { int r; float CA,CP; printf("n Enter the radius of a circle "); scanf("%d",r); CA=CArea(r); printf("n Radius of a circle is %f",CA); CP=CPeri(r); printf("n Perimeter of a circle is %f",CP); } QuestionQuestionQuestionQuestion12121212 What are the different file opening modes in C. Write a program to copy the contents of one file into other file? AnswerAnswerAnswerAnswer File Opening ModesFile Opening ModesFile Opening ModesFile Opening Modes The tasks performed by fopen( ) when a file is opened in each of these modes are File ModeFile ModeFile ModeFile Mode OperationsOperationsOperationsOperations "r""r""r""r" reading from the file.reading from the file.reading from the file.reading from the file. It searches file. If the file is opened successfully, fopen( ) loadsitintomemory and sets up a pointer which points to the first character in it. If the file cannot be opened fopen( ) returns NULL.
  • 18. Kanpur Institute of Technology Computer concept and C programming -Question Bank-3 somnath.gupta123@gmail.com Page 18 "w""w""w""w" writing to the file.writing to the file.writing to the file.writing to the file. It searches file. If the file exists, its contents are overwritten. If the file doesn’t exist, a new file is created. Returns NULL, if unable to open file. "a""a""a""a" adding new contents at the end of file.adding new contents at the end of file.adding new contents at the end of file.adding new contents at the end of file. It searches file. If the file is opened successfully fopen( ) loads it into memory and sets up a pointer that points to the last character in it. If the file doesn’t exist, a new file is created. Returns NULL, if unable to open file. "r+""r+""r+""r+" reading existing contents, writing new contents, modifying existing contents ofreading existing contents, writing new contents, modifying existing contents ofreading existing contents, writing new contents, modifying existing contents ofreading existing contents, writing new contents, modifying existing contents of the file.the file.the file.the file. Searches file. If is opened successfully fopen( ) loads it into memory and sets up a pointer whichpointstothefirst characterinit.ReturnsNULL,ifunabletoopenthefile. "w+""w+""w+""w+" writing new contents, reading them back and modifying existing contents of thewriting new contents, reading them back and modifying existing contents of thewriting new contents, reading them back and modifying existing contents of thewriting new contents, reading them back and modifying existing contents of the file.file.file.file. Searches file. If the file exists, its contents are overwritten. If the file doesn’t exist a new file is created. Returns NULL, if unable to open file. "a+""a+""a+""a+" reading existing contents, appending new contents to end of file. Cannotreading existing contents, appending new contents to end of file. Cannotreading existing contents, appending new contents to end of file. Cannotreading existing contents, appending new contents to end of file. Cannot modifyexistingcontents.modifyexistingcontents.modifyexistingcontents.modifyexistingcontents. Searches file. If the file is opened successfully fopen( ) loads it into memory and sets up a pointer which points to the first character in it. If the file doesn’t exist, a new file is created. Returns NULL, if unable to open file. /*/*/*/*AAAA file copy program which copies the file “prog.c” to “prog.old”file copy program which copies the file “prog.c” to “prog.old”file copy program which copies the file “prog.c” to “prog.old”file copy program which copies the file “prog.c” to “prog.old” */*/*/*/ #include <stdio.h> void main() { FILE *fp1, *fp2, *fopen(); char ch ; fp1 = fopen( “prog.c”, “r” ); /* open for reading */ fp2 = fopen( “prog.old”, “w” ) ; ../* open for writing */ if ( fp1 == NULL ) /* check does file exist etc */ { printf(“Cannot open prog.c for reading n” ); } if ( fp2 == NULL ) { printf(“Cannot open prog.old for writing n”); }
  • 19. Kanpur Institute of Technology Computer concept and C programming -Question Bank-3 somnath.gupta123@gmail.com Page 19 while(1) { ch = getc(fp1) ; if( ch== EOF) { break; } putc( c, fp2); /* copy to prog.old */ } fclose ( fp1 ); /* Now close files */ fclose ( fp2 ); } QuestionQuestionQuestionQuestion13131313 Write a program to compare two files specified by the user, displaying a message indicating whether the files are identical or different. Both files should be read by the user. AnswerAnswerAnswerAnswer /*A program to/*A program to/*A program to/*A program to compare two files */compare two files */compare two files */compare two files */ #include <stdio.h> void main() { FILE *fp1, *fp2; int ca, cb; char fname1[40], fname2[40] ; printf(“Enter first filename:”) ; gets(fname1); printf(“Enter second filename:”); gets(fname2); fp1 = fopen( fname1, “r” ); /* open for reading */ fp2 = fopen( fname2, “r” ) ; /* open for writing */ if ( fp1 == NULL ) /* check does file exist etc */ { printf(“Cannot open for reading n”); exit(1); /* terminate program */ } if ( fp2 == NULL )
  • 20. Kanpur Institute of Technology Computer concept and C programming -Question Bank-3 somnath.gupta123@gmail.com Page 20 { printf(“Cannot open for reading n”, ); exit(1); /* terminate program */ } else /* both files opened successfully */ { ca = getc( fp1 ) ; cb = getc( fp2 ) ; while ( ca != EOF && cb != EOF && ca == cb ) { ca = getc( fp1 ) ; cb = getc( fp2 ) ; } if ( ca == cb ) printf(“Files are identical n”); else if ( ca != cb ) printf(“Files differ n” ); fclose ( fp1 ); fclose ( fp2 ); } } QuestionQuestionQuestionQuestion 14141414––––Write short notes on following A. Command line argument. B. dynamic memory allocation and various functions for dynamic memory allocation C. Stack with push and pop operation D. Linked list AnswerAnswerAnswerAnswer A.A.A.A. Accepting command line argumentsAccepting command line argumentsAccepting command line argumentsAccepting command line arguments Command line arguments are given after the name of a program in command line operating systems like DOS or Linux, and are passed in to the program from the operating system. To use command line arguments in your program, first understand the full declaration of the main function. In fact, main can actually accept two arguments: one argument is number of command line arguments, and the other argument is a full list of all of the command line arguments.
  • 21. Kanpur Institute of Technology Computer concept and C programming -Question Bank-3 somnath.gupta123@gmail.com Page 21 The full declaration of main looks like this: int main ( int argc, char *argv[] ) The integer, argc is the argument count. It is the number of arguments passed into the program from the command line, including the name of the program. The argv is array of character pointers that contains the list of all the arguments. argv[0] is the name of the program, or an empty string if the name is not available. After that, every element number less than argc is a command line argument. /* A program to find the length of a string which is given through command prompt. Program should give the output as follows: C:>length Hello Length of string “Hello” is 5 */ AnswerAnswerAnswerAnswer #include<stdio.h> int main(int argc ,char *argv[]) { char str[]=argv[1]; int len,i; len=0; for(i=0;str[i]!='0';i++) { len++; } printf("n Length of the string %s is %d",str,len); } B.B.B.B. DDDDynamic memory allocation and various functions for dynamic memory allocationynamic memory allocation and various functions for dynamic memory allocationynamic memory allocation and various functions for dynamic memory allocationynamic memory allocation and various functions for dynamic memory allocation Dynamic memory allocation is also known as heap based memory allocation. It is used to allocate memory dynamically at runtime. Dynamically allocated memory exists until it is released internally (by Garbage Collector) or externally (by User). Allocating new heap memoryAllocating new heap memoryAllocating new heap memoryAllocating new heap memory voidvoidvoidvoid *malloc(size_t*malloc(size_t*malloc(size_t*malloc(size_t size);size);size);size); Allocate a block of size bytes,return a pointer to the block.(NULL if unable to allocate block)
  • 22. Kanpur Institute of Technology Computer concept and C programming -Question Bank-3 somnath.gupta123@gmail.com Page 22 voidvoidvoidvoid *calloc(size_t*calloc(size_t*calloc(size_t*calloc(size_t num_elements, size_tnum_elements, size_tnum_elements, size_tnum_elements, size_t element_size);element_size);element_size);element_size); Allocate a block of num_elements * element_size bytes, initialize every byte to zero, return pointer to the block. (NULL if unable to allocate block) void *realloc(voidvoid *realloc(voidvoid *realloc(voidvoid *realloc(void *ptr, size_t*ptr, size_t*ptr, size_t*ptr, size_t new_size);new_size);new_size);new_size); Used to increase or decrease memory size that was previously allocated. Given a previously allocated block starting at ptr,change the block size to new_size, return pointer to resized block. If block size is increased, contents of old block may be copied to a completely different region. Deallocating heap memoryDeallocating heap memoryDeallocating heap memoryDeallocating heap memory void free(void *pointer);void free(void *pointer);void free(void *pointer);void free(void *pointer); It is used to deallocate memory that was previously allocated. C. StackStackStackStack –––– Stack is linear data structure in which items are inserted and deleted at one end called top of the stack. It is also called LIFO. It means the item that comes last into the stack; get removed first (LIFO) order. Stack OperationsStack OperationsStack OperationsStack Operations – Stack has two operations 1. Push () is used to add an item into stack. 2. Pop () is used to remove an item from the stack. Any operation can perform only at TOP end of the stack. It means any item input or output can be done form TOP end. PUSH operationPUSH operationPUSH operationPUSH operation –––– Adding an item in the stack is called PUSH operation and when we add an item into stack the TOP pointer is incremented Algorithm of PUSH operationAlgorithm of PUSH operationAlgorithm of PUSH operationAlgorithm of PUSH operation An array STK [N] is stack. 1. IF Top = N then [print “STACK is Full”] and exit. 2. Top = Top + 1 3. STK [ TOP ] = ‘Element’ 4. END
  • 23. somnath.gupta123@gmail.com Pop OperationPop OperationPop OperationPop Operation –––– To remove an item from the stack is called required to be checked whether the stack is containing any item in it or it is already empty (i.e. TOP = 0) Algorithm of POP operationAlgorithm of POP operationAlgorithm of POP operationAlgorithm of POP operation –––– 1. If TOP = Null then [print “stack is already empty”] and exit. 2. element = STK [Top] 3. Top = Top – 1 4. END D.D.D.D. Linked ListLinked ListLinked ListLinked List A linked list is collections of nodes that consists of two fields, one containing the information about that node, data and second contain the address of next node. Such a structure is represented as follows: struct node { int data; struct node *next; }; Types of Linked ListTypes of Linked ListTypes of Linked ListTypes of Linked List 1. Linear Singly linked listLinear Singly linked listLinear Singly linked listLinear Singly linked list: A list type in which each node points to the 2. Circular linked list:Circular linked list:Circular linked list:Circular linked list: Lists which have no beginning and no end. The last 3. Doubly linked list or TwoDoubly linked list or TwoDoubly linked list or TwoDoubly linked list or Two way linked listway linked listway linked listway linked list node and other pointing to the previous Kanpur Institute of Technology Computer concept and C programming To remove an item from the stack is called POP operation Before removing an item, it is required to be checked whether the stack is containing any item in it or it is already empty (i.e. TOP = 0) print “stack is already empty”] and exit. nodes that consists of two fields, one containing the information about that node, and second contain the address of next node. follows: Node Data Next : A list type in which each node points to the next node and the last node points to NULL. Lists which have no beginning and no end. The last node points back to the first way linked listway linked listway linked listway linked list: These lists contain double set of pointers, one pointing to the next vious node. So one can traverse the list in either direction. Kanpur Institute of Technology Computer concept and C programming -Question Bank-3 Page 23 operation Before removing an item, it is required to be checked whether the stack is containing any item in it or it is already empty (i.e. TOP = 0) nodes that consists of two fields, one containing the information about that node, node and the last node points to NULL. node points back to the first node. pointers, one pointing to the next one can traverse the list in either direction.