AKTU 1st Year Sem 1 Solved Paper 2017-18 | COMP. SYSTEM & C PROGRAMMING | Sec C
Last Updated :
01 Mar, 2023
Paper download link: Paper | Sem 1 | 2017-18
B.Tech. (SEM-I) THEORY EXAMINATION 2017-18 COMPUTER SYSTEM & PROGRAMMING IN C
Time: 3hrs Total Marks: 100 Note:-
- There are three sections. Section A carries 20 marks, Section B carries 30 marks and Section C carries 50 marks.
- Attempt all questions. Marks are indicated against each question.
- Assume suitable data wherever necessary.
Section – C
3. Attempt any two of the following: (2*5 = 10)
- What is meant by Storage Classes of a variable? Define all types of storage classes with example.
Storage Classes are used to describe about the features of a variable/function. These features basically include the scope, visibility and life-time which help us to trace the existence of a particular variable during the runtime of a program. C language uses 4 storage classes, namely:
- auto: This is the default storage class for all the variables declared inside a function or a block. Hence, the keyword auto is rarely used while writing programs in C language. Auto variables can be only accessed within the block/function they have been declared and not outside them (which defines their scope). Of course, these can be accessed within nested blocks within the parent block/function in which the auto variable was declared. However, they can be accessed outside their scope as well using the concept of pointers given here by pointing to the very exact memory location where the variables resides. They are assigned a garbage value by default whenever they are declared.
- extern: Extern storage class simply tells us that the variable is defined elsewhere and not within the same block where it is used. Basically, the value is assigned to it in a different block and this can be overwritten/changed in a different block as well. So an extern variable is nothing but a global variable initialized with a legal value where it is declared in order to be used elsewhere. It can be accessed within any function/block. Also, a normal global variable can be made extern as well by placing the ‘extern’ keyword before its declaration/definition in any function/block. This basically signifies that we are not initializing a new variable but instead we are using/accessing the global variable only. The main purpose of using extern variables is that they can be accessed between two different files which are part of a large program. For more information on how extern variables work, have a look at this link.
- static: This storage class is used to declare static variables which are popularly used while writing programs in C language. Static variables have a property of preserving their value even after they are out of their scope! Hence, static variables preserve the value of their last use in their scope. So we can say that they are initialized only once and exist till the termination of the program. Thus, no new memory is allocated because they are not re-declared. Their scope is local to the function to which they were defined. Global static variables can be accessed anywhere in the program. By default, they are assigned the value 0 by the compiler.
- register: This storage class declares register variables which have the same functionality as that of the auto variables. The only difference is that the compiler tries to store these variables in the register of the microprocessor if a free register is available. This makes the use of register variables to be much faster than that of the variables stored in the memory during the runtime of the program. If a free register is not available, these are then stored in the memory only. Usually few variables which are to be accessed very frequently in a program are declared with the register keyword which improves the running time of the program. An important and interesting point to be noted here is that we cannot obtain the address of a register variable using pointers.
- Write a program to multiply two matrices ( read size and number of element of matrices from the keyboard).
C
#include <stdio.h>
const int MAX = 100;
void printMatrix( int M[][MAX], int rowSize, int colSize)
{
for ( int i = 0; i < rowSize; i++) {
for ( int j = 0; j < colSize; j++)
printf ("%d ", M[i][j]);
printf ("\n");
}
}
void multiplyMatrix( int row1, int col1, int A[][MAX],
int row2, int col2, int B[][MAX])
{
int i, j, k;
int C[MAX][MAX];
if (row2 != col1) {
printf ("Not Possible\n");
return ;
}
for (i = 0; i < row1; i++) {
for (j = 0; j < col2; j++) {
C[i][j] = 0;
for (k = 0; k < row2; k++)
C[i][j] += A[i][k] * B[k][j];
}
}
printf ("\nResultant Matrix: \n");
printMatrix(C, row1, col2);
}
int main()
{
int row1, col1, row2, col2, i, j;
int A[MAX][MAX], B[MAX][MAX];
printf ("Enter the number of rows of First Matrix: ");
scanf ("%d", &row1);
printf ("%d", row1);
printf ("\nEnter the number of columns of First Matrix: ");
scanf ("%d", &col1);
printf ("%d", col1);
printf ("\nEnter the elements of First Matrix: ");
for (i = 0; i < row1; i++) {
for (j = 0; j < col1; j++) {
printf ("\nA[%d][%d]: ", i, j);
scanf ("%d", &A[i][j]);
printf ("%d", A[i][j]);
}
}
printf ("\nEnter the number of rows of Second Matrix: ");
scanf ("%d", &row2);
printf ("%d", row2);
printf ("\nEnter the number of columns of Second Matrix: ");
scanf ("%d", &col2);
printf ("%d", col2);
printf ("\nEnter the elements of First Matrix: ");
for (i = 0; i < row2; i++) {
for (j = 0; j < col2; j++) {
printf ("\nB[%d][%d]: ", i, j);
scanf ("%d", &B[i][j]);
printf ("%d", B[i][j]);
}
}
printf ("\n\nFirst Matrix: \n");
printMatrix(A, row1, col1);
printf ("\nSecond Matrix: \n");
printMatrix(B, row2, col2);
multiplyMatrix(row1, col1, A, row2, col2, B);
return 0;
}
|
Output:
Enter the number of rows of First Matrix: 2
Enter the number of columns of First Matrix: 3
Enter the elements of First Matrix:
A[0][0]: 1
A[0][1]: 2
A[0][2]: 3
A[1][0]: 4
A[1][1]: 5
A[1][2]: 6
Enter the number of rows of Second Matrix: 3
Enter the number of columns of Second Matrix: 2
Enter the elements of First Matrix:
B[0][0]: 1
B[0][1]: 2
B[1][0]: 3
B[1][1]: 4
B[2][0]: 5
B[2][1]: 6
First Matrix:
1 2 3
4 5 6
Second Matrix:
1 2
3 4
5 6
Resultant Matrix:
22 28
49 64
- Discuss various data-types used in C with suitable examples.
Each variable in C has an associated data type. Each data type requires different amounts of memory and has some specific operations which can be performed over it. Let us briefly describe them one by one: Following are the examples of some very common data types used in C:
- char: The most basic data type in C. It stores a single character and requires a single byte of memory in almost all compilers.
- int: As the name suggests, an int variable is used to store an integer.
- float: It is used to store decimal numbers (numbers with floating point value) with single precision.
- double: It is used to store decimal numbers (numbers with floating point value) with double precision.
4. Attempt any two of the following: (2*5 = 10)
- What is recursion? Write a recursive program to find factorial of a number.
Recursion: The process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called as recursive function. Using recursive algorithm, certain problems can be solved quite easily. Examples of such problems are Towers of Hanoi (TOH), Inorder/Preorder/Postorder Tree Traversals, DFS of Graph, etc. Base condition in recursion: In recursive program, the solution to base case is provided and solution of bigger problem is expressed in terms of smaller problems. Program to find factorial of a number:
C
#include <stdio.h>
unsigned int factorial(unsigned int n)
{
if (n == 0)
return 1;
return n * factorial(n - 1);
}
int main()
{
int num;
scanf ("%d", &num);
printf ("Enter the number: %d", num);
printf ("\nFactorial of %d is %d",
num, factorial(num));
return 0;
}
|
- Output:
Enter the number: 5
Factorial of 5 is 120
- Explain the difference between parameter passing mechanism call by value and call by reference. Which is more efficient and why?
There are different ways in which parameter data can be passed into and out of methods and functions. Let us assume that a function B() is called from another function A(). In this case A is called the “caller function” and B is called the “called function or callee function”. Also, the arguments which A sends to B are called actual arguments and the parameters of B are called formal arguments.
Terminology
- Formal Parameter : A variable and its type as they appear in the prototype of the function or method.
- Actual Parameter : The variable or expression corresponding to a formal parameter that appears in the function or method call in the calling environment.
- Modes:
- IN: Passes info from caller to callee.
- OUT: Callee writes values in caller.
- IN/OUT: Caller tells callee value of variable, which may be updated by callee.
- Pass By Value : This method uses in-mode semantics. Changes made to formal parameter do not get transmitted back to the caller. Any modifications to the formal parameter variable inside the called function or method affect only the separate storage location and will not be reflected in the actual parameter in the calling environment. This method is also called as call by value.
C
#include <stdio.h>
void func( int a, int b)
{
a += b;
printf ("In func, a = %d b = %d\n", a, b);
}
int main( void )
{
int x = 5, y = 7;
func(x, y);
printf ("In main, x = %d y = %d\n", x, y);
return 0;
}
|
- Output:
In func, a = 12 b = 7
In main, x = 5 y = 7
- Languages like C, C++, Java support this type of parameter passing. Java in fact is strictly call by value. Shortcomings:
- Inefficiency in storage allocation
- For objects and arrays, the copy semantics are costly
- Pass by reference(aliasing) : This technique uses in/out-mode semantics. Changes made to formal parameter do get transmitted back to the caller through parameter passing. Any changes to the formal parameter are reflected in the actual parameter in the calling environment as formal parameter receives a reference (or pointer) to the actual data. This method is also called as <em>call by reference. This method is efficient in both time and space.
C
#include <stdio.h>
void swapnum( int * i, int * j)
{
int temp = *i;
*i = *j;
*j = temp;
}
int main( void )
{
int a = 10, b = 20;
swapnum(&a, &b);
printf ("a is %d and b is %d\n", a, b);
return 0;
}
|
- Output:
a is 20 and b is 10
- C and C++ both support call by value as well as call by reference whereas Java does’nt support call by reference. Shortcomings:
- Many potential scenarios can occur
- Programs are difficult to understand sometimes
- Write a program to check a number is prime number or not.
Program to check a number is prime or not:
C
#include <stdio.h>
int isPrime( int n)
{
if (n <= 1)
return 0;
for ( int i = 2; i < n; i++)
if (n % i == 0)
return 0;
return 1;
}
int main()
{
int num;
scanf ("%d", &num);
printf ("Enter the number: %d", num);
printf ("\nIs %d prime: ", num);
if (isPrime(num) == 1) {
printf ("Yes");
}
else {
printf ("No");
}
return 0;
}
|
- Output:
Enter the number: 5
Is 5 prime: Yes
5. Attempt any two of the following: (2*5 = 10)
- What is Macros? How it is substituted? Write macro definition with arguments for calculation of area and perimeter of a circle and rectangle. 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.
- Creating areaperi.h : Write the below code and then save the file as areaperi.h. The extension should be .h indicating its a header file.
C
#define AREA_OF_CIRCLE(r) (3.14 * r * r)
#define PERIMETER_OF_CIRCLE(r) (3.14 * 2 * r)
#define AREA_OF_RECTANGLE(l, b) (l * b)
#define AREA_OF_RECTANGLE(l, b) (2 * (l * b))
|
- Including the areaperi.h file in other program : Now as we need to include stdio.h as #include in order to use printf() function. We will also need to include the above header file areaperi.h as #include”areaperi.h”. The ” ” here are used to instructs the preprocessor to look into the present folder and into the standard folder of all header files if not found in present folder. So, if you wish to use angular brackets instead of ” ” to include your header file you can save it in the standard folder of header files otherwise. If you are using ” ” you need to ensure that the header file you created is saved in the same folder in which you will save the C file using this header file.
- Using the created header file :
C
#include "areaperi.h"
#include <stdio.h>
int main()
{
float radius, length, breadth;
scanf ("%f", &radius);
printf ("Enter the radius of the circle: %f", radius);
printf ("\nThe area of circle: %f",
AREA_OF_CIRCLE(radius));
printf ("\nThe perimeter of circle: %f",
PERIMETER_OF_CIRCLE(radius));
scanf ("%f", &length);
printf ("\nEnter the length of the Rectangle: %f", length);
scanf ("%f", &breadth);
printf ("\nEnter the breadth of the Rectangle: %f", breadth);
printf ("\nThe area of Rectangle: %f",
AREA_OF_RECTANGLE(length, breadth));
printf ("\nThe perimeter of Rectangle: %f",
PERIMETER_OF_CIRCLE(length, breadth));
}
|
- Output:
- What are the different file opening modes in C? Write a program to copy the contents of one file into other file?
File opening modes in C:
- “r” – 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 cannot be opened fopen( ) returns NULL.
- “w” – 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” – 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+” – Searches file. If is opened successfully fopen( ) loads it into memory and sets up a pointer which points to the first character in it. Returns NULL, if unable to open the file.
- “w+” – 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+” – Searches file. If the file is opened successfully fopen( ) loads it into memory and sets up a pointer which 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.
- 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”.
A structure is a user-defined data type in C/C++. A structure creates a data type that can be used to group items of possibly different types into a single type. How to create a structure? ‘struct’ keyword is used to create a structure. Following is an example.
C
struct address {
char name[50];
char street[100];
char city[50];
char state[20];
int pin;
};
|
- How to declare structure variables? A structure variable can either be declared with structure declaration or as a separate declaration like basic types.
C
struct Point {
int x, y;
} p1;
struct Point {
int x, y;
};
int main()
{
struct Point p1;
}
|
- Note: In C++, the struct keyword is optional before in declaration of a variable. In C, it is mandatory. Program that compares two given dates:
C
#include <stdio.h>
struct Date {
int date;
int month;
int year;
};
int main()
{
int date1, date2, month1,
month2, year1, year2;
scanf ("%d", &date1);
printf ("Enter the first date: %d", date1);
scanf ("%d", &month1);
printf ("\nEnter the first month: %d", month1);
scanf ("%d", &year1);
printf ("\nEnter the first year: %d", year1);
struct Date Date1 = { date1, month1, year1 };
scanf ("%d", &date2);
printf ("\nEnter the second date: %d", date2);
scanf ("%d", &month2);
printf ("\nEnter the second month: %d", month2);
scanf ("%d", &year2);
printf ("\nEnter the second year: %d", year2);
struct Date Date2 = { date2, month2, year2 };
printf ("\nThe given dates are: ");
if (Date1.date == Date2.date
&& Date1.month == Date2.month
&& Date1.year == Date2.year) {
printf ("Equal");
}
else {
printf ("Unequal");
}
return 0;
}
|
- Output:
Enter the first date: 10
Enter the first month: 11
Enter the first year: 2018
Enter the second date: 10
Enter the second month: 11
Enter the second year: 2018
The given dates are: Equal
6. Attempt any two of the following: (2*5 = 10)
- Suppose a file contains student’s records with each record containing name and age of a student. Write a C program to read these records and display them in sorted order by name.
C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Student {
char * name;
int id;
char age;
};
int comparator( const void * p, const void * q)
{
return strcmp ((( struct Student*)p)->name,
(( struct Student*)q)->name);
}
int main()
{
int i = 0, n = 5;
struct Student arr[n];
arr[0].id = 1;
arr[0].name = "bd";
arr[0].age = 12;
arr[1].id = 2;
arr[1].name = "ba";
arr[1].age = 10;
arr[2].id = 3;
arr[2].name = "bc";
arr[2].age = 8;
arr[3].id = 4;
arr[3].name = "aaz";
arr[3].age = 9;
arr[4].id = 5;
arr[4].name = "az";
arr[4].age = 10;
printf ("Unsorted Student Records:\n");
for (i = 0; i < n; i++) {
printf ("Id = %d, Name = %s, Age = %d \n",
arr[i].id, arr[i].name, arr[i].age);
}
qsort (arr, n, sizeof ( struct Student), comparator);
printf ("\n\nStudent Records sorted by Name:\n");
for (i = 0; i < n; i++) {
printf ("Id = %d, Name = %s, Age = %d \n",
arr[i].id, arr[i].name, arr[i].age);
}
return 0;
}
|
- Output:
Unsorted Student Records:
Id = 1, Name = bd, Age = 12
Id = 2, Name = ba, Age = 10
Id = 3, Name = bc, Age = 8
Id = 4, Name = aaz, Age = 9
Id = 5, Name = az, Age = 10
Student Records sorted by Name:
Id = 4, Name = aaz, Age = 9
Id = 5, Name = az, Age = 10
Id = 2, Name = ba, Age = 10
Id = 3, Name = bc, Age = 8
Id = 1, Name = bd, Age = 12
- Write a program to sort a set of names stored in an array in alphabetical order.
C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static int myCompare( const void * a, const void * b)
{
return strcmp (*( const char **)a, *( const char **)b);
}
void sort( const char * arr[], int n)
{
qsort (arr, n, sizeof ( const char *), myCompare);
}
int main()
{
const char * arr[];
= { "GeeksforGeeks",
"GeeksQuiz",
"CLanguage" };
int n = sizeof (arr) / sizeof (arr[0]);
int i;
printf ("Given array of names is\n");
for (i = 0; i < n; i++)
printf ("%d: %s \n", i, arr[i]);
sort(arr, n);
printf ("\nSorted array of names is\n");
for (i = 0; i < n; i++)
printf ("%d: %s \n", i, arr[i]);
return 0;
}
|
- Output:
Given array of names is
0: GeeksforGeeks
1: GeeksQuiz
2: CLanguage
Sorted array of names is
0: CLanguage
1: GeeksQuiz
2: GeeksforGeeks
- Write a user define function to compare two strings where they are identical or not.
C
#include <stdio.h>
#include <string.h>
int main()
{
char string1[100], string2[100];
scanf ("%s", string1);
printf ("Enter the first string: %s", string1);
scanf ("%s", string2);
printf ("\nEnter the second string: %s", string2);
printf ("\nAre both strings same: ");
if ( strcmp (string1, string2) == 0) {
printf ("Yes");
}
else {
printf ("No");
}
return 0;
}
|
Output:
Enter the first string: GeeksForGeeks
Enter the second string: GeeksForGeeks
Are both strings same: Yes
7. Attempt any two of the following: (2*5 = 10)
- Define the concept of pointer> Also define the dynamic memory allocation and various functions for dynamic memory allocation, with suitable examples.
Pointers are symbolic representation of addresses. They enable programs to simulate call-by-reference as well as to create and manipulate dynamic data structures. It’s general declaration in C/C++ has the format:
Syntax:
datatype *var_name;
int *ptr; //ptr can point to an address which holds int data
- How to use a pointer?
- Define a pointer variable
- Assigning the address of a variable to a pointer using unary operator (&) which returns the address of that variable.
- Accessing the value stored in the address using unary operator (*) which returns the value of the variable located at the address specified by its operand.
- malloc()
- calloc()
- free()
- realloc()
- malloc() “malloc” or “memory allocation” method is used to dynamically allocate a single large block of memory with the specified size. It returns a pointer of type void which can be cast into a pointer of any form. Syntax:
ptr = (cast-type*) malloc(byte-size)
For Example:
ptr = (int*) malloc(100 * sizeof(int));
Since the size of int is 4 bytes,
this statement will allocate 400 bytes of memory.
And, the pointer ptr holds the address
of the first byte in the allocated memory.
- If the space is insufficient, allocation fails and returns a NULL pointer. Example:
C
#include <stdio.h>
#include <stdlib.h>
int main()
{
int * ptr;
int n, i, sum = 0;
n = 5;
printf ("Enter number of elements: %d\n", n);
ptr = ( int *) malloc (n * sizeof ( int ));
if (ptr == NULL) {
printf ("Memory not allocated.\n");
exit (0);
}
else {
printf ("Memory successfully allocated using malloc .\n");
for (i = 0; i < n; ++i) {
ptr[i] = i + 1;
}
printf ("The elements of the array are: ");
for (i = 0; i < n; ++i) {
printf ("%d, ", ptr[i]);
}
}
return 0;
}
|
Output:
Enter number of elements: 5
Memory successfully allocated using malloc.
The elements of the array are: 1, 2, 3, 4, 5,
- calloc() “calloc” or “contiguous allocation” method is used to dynamically allocate the specified number of blocks of memory of the specified type. It initializes each block with a default value ‘0’. Syntax:
ptr = (cast-type*)calloc(n, element-size);
For Example:
ptr = (float*) calloc(25, sizeof(float));
This statement allocates contiguous space in memory
for 25 elements each with the size of float.
- If the space is insufficient, allocation fails and returns a NULL pointer. Example:
C
#include <stdio.h>
#include <stdlib.h>
int main()
{
int * ptr;
int n, i, sum = 0;
n = 5;
printf ("Enter number of elements: %d\n", n);
ptr = ( int *) calloc (n, sizeof ( int ));
if (ptr == NULL) {
printf ("Memory not allocated.\n");
exit (0);
}
else {
printf ("Memory successfully allocated using calloc .\n");
for (i = 0; i < n; ++i) {
ptr[i] = i + 1;
}
printf ("The elements of the array are: ");
for (i = 0; i < n; ++i) {
printf ("%d, ", ptr[i]);
}
}
return 0;
}
|
Output:
Enter number of elements: 5
Memory successfully allocated using calloc.
The elements of the array are: 1, 2, 3, 4, 5,
- free() “free” method is used to dynamically de-allocate the memory. The memory allocated using functions malloc() and calloc() are not de-allocated on their own. Hence the free() method is used, whenever the dynamic memory allocation takes place. It helps to reduce wastage of memory by freeing it. Syntax:
free(ptr);
- Example:
C
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *ptr, *ptr1;
int n, i, sum = 0;
n = 5;
printf ("Enter number of elements: %d\n", n);
ptr = ( int *) malloc (n * sizeof ( int ));
ptr1 = ( int *) calloc (n, sizeof ( int ));
if (ptr == NULL || ptr1 == NULL) {
printf ("Memory not allocated.\n");
exit (0);
}
else {
printf ("Memory successfully allocated using malloc .\n");
free (ptr);
printf ("Malloc Memory successfully freed.\n");
printf ("\nMemory successfully allocated using calloc .\n");
free (ptr1);
printf ("Calloc Memory successfully freed.\n");
}
return 0;
}
|
Output:
Enter number of elements: 5
Memory successfully allocated using malloc.
Malloc Memory successfully freed.
Memory successfully allocated using calloc.
Calloc Memory successfully freed.
- realloc() “realloc” or “re-allocation” method is used to dynamically change the memory allocation of a previously allocated memory. In other words, if the memory previously allocated with the help of malloc or calloc is insufficient, realloc can be used to dynamically re-allocate memory. Syntax:
ptr = realloc(ptr, newSize);
where ptr is reallocated with new size 'newSize'.
- If the space is insufficient, allocation fails and returns a NULL pointer. Example:
C
#include <stdio.h>
#include <stdlib.h>
int main()
{
int * ptr;
int n, i, sum = 0;
n = 5;
printf ("Enter number of elements: %d\n", n);
ptr = ( int *) calloc (n, sizeof ( int ));
if (ptr == NULL) {
printf ("Memory not allocated.\n");
exit (0);
}
else {
printf ("Memory successfully allocated using calloc .\n");
for (i = 0; i < n; ++i) {
ptr[i] = i + 1;
}
printf ("The elements of the array are: ");
for (i = 0; i < n; ++i) {
printf ("%d, ", ptr[i]);
}
n = 10;
printf ("\n\nEnter the new size of the array: %d\n", n);
ptr = realloc (ptr, n * sizeof ( int ));
printf ("Memory successfully re-allocated using realloc .\n");
for (i = 5; i < n; ++i) {
ptr[i] = i + 1;
}
printf ("The elements of the array are: ");
for (i = 0; i < n; ++i) {
printf ("%d, ", ptr[i]);
}
free (ptr);
}
return 0;
}
|
Output:
Enter number of elements: 5
Memory successfully allocated using calloc.
The elements of the array are: 1, 2, 3, 4, 5,
Enter the new size of the array: 10
Memory successfully re-allocated using realloc.
The elements of the array are: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
- What is string? Also explain different string functions with examples.
Strings in C: Strings are defined as an array of characters. The difference between a character array and a string is the string is terminated with a special character ‘\0’. Some of the most commonly used String functions are:
- strcat: The strcat() function will append a copy of the source string to the end of destination string. The strcat() function takes two arguments: 1) dest 2) src It will append copy of the source string in the destination string. The terminating character at the end of dest is replaced by the first character of src . Return value: The strcat() function returns dest, the pointer to the destination string.
- strchr: In C/C++, strrchr() is a predefined function used for string handling. cstring is the header file required for string functions. This function Returns a pointer to the last occurrence of a character in a string. The character whose last occurrence we want to find in passed as the second argument to the function and the string in which we have to find the character is passed as the first argument to the function. Syntax
char *strrchr(const char *str, int c)
- Here, str is the string and c is the character to be located. It is passed as its int promotion, but it is internally converted back to char.
- strcmp: strcmp() is a built-in library function and is declared in <string.h> header file. This function takes two strings as arguments and compare these two strings lexicographically. Syntax::
int strcmp(const char *leftStr, const char *rightStr );
- In the above prototype, function strcmp takes two strings as parameters and returns an integer value based on the comparison of strings.
- strcmp() compares the two strings lexicographically means it starts comparison character by character starting from the first character until the characters in both strings are equal or a NULL character is encountered.
- If first character in both strings are equal, then this function will check the second character, if this is also equal then it will check the third and so on
- This process will be continued until a character in either string is NULL or the characters are unequal.
- strcpy: strcpy() is a standard library function in C/C++ and is used to copy one string to another. In C it is present in string.h header file and in C++ it is present in cstring header file. Syntax:
char* strcpy(char* dest, const char* src);
- Parameters: This method accepts following parameters:
- dest: Pointer to the destination array where the content is to be copied.
- src: string which will be copied.
- strlen: The strlen() function calculates the length of a given string.The strlen() function is defined in string.h header file. It doesn’t count null character ‘\0’. Syntax:
int strlen(const char *str);
- Parameter:
- str: It represents the string variable whose length we have to find.
- strncat: In C/C++, strncat() is a predefined function used for string handling. string.h is the header file required for string functions. This function appends not more than n characters from the string pointed to by src to the end of the string pointed to by dest plus a terminating Null-character. The initial character of string(src) overwrites the Null-character present at the end of string(dest). Thus, length of the string(dest) becomes strlen(dest)+n. But, if the length of the string(src) is less than n, only the content up to the terminating null-character is copied and length of the string(dest) becomes strlen(src) + strlen(dest). The behavior is undefined if
- the strings overlap.
- the dest array is not large enough to append the contents of src.
- dest: the string where we want to append.
- src: the string from which ‘n’ characters are going to append.
- n: represents maximum number of character to be appended. size_t is an unsigned integral type.
- strncmp: std::strncmp() function lexicographically compares not more than count characters from the two null-terminated strings and returns an integer based on the outcome.
- This function takes two strings and a number num as arguments and compare at most first num bytes of both the strings.
- num should be at most equal to the length of the longest string. If num is defined greater than the string length then comparison is done till the null-character(‘\0’) of either string.
- This function compares the two strings lexicographically. It starts comparison from the first character of each string. If they are equal to each other, it continues and compare the next character of each string and so on.
- This process of comparison stops until a terminating null-character of either string is reached or num characters of both the strings matches.
- strncpy: The strncpy() function is similar to strcpy() function, except that at most n bytes of src are copied. If there is no NULL character among the first n character of src, the string placed in dest will not be NULL-terminated. If the length of src is less than n, strncpy() writes additional NULL character to dest to ensure that a total of n character are written. Syntax:
char *strncpy( char *dest, const char *src, size_t n )
- Parameters: This function accepts two parameters as mentioned above and described below:
- src: The string which will be copied.
- dest: Pointer to the destination array where the content is to be copied.
- n: The first n character copied from src to dest.
- strrchr: The strrchr() function in C/C++ locates the last occurrence of a character in a string. It returns a pointer to the last occurrence in the string. The terminating null character is considered part of the C string. Therefore, it can also be located to retrieve a pointer to the end of a string. It is defined in cstring header file. Syntax :
const char* strrchr( const char* str, int ch )
or
char* strrchr( char* str, int ch )
- Parameter :The function takes two mandatory parameters which are described below:
- str : specifies the pointer to the null terminated string to be searched for.
- ch: specifies the character to be search for.
- Write short note on following (Any two):
- (i) Stack with push and pop operation: Stack is a linear data structure which follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out).
Mainly the following three basic operations are performed in the stack:
- Push: Adds an item in the stack. If the stack is full, then it is said to be an Overflow condition.
- Pop: Removes an item from the stack. The items are popped in the reversed order in which they are pushed. If the stack is empty, then it is said to be an Underflow condition.
- Peek or Top: Returns top element of stack.
- isEmpty: Returns true if stack is empty, else false.
- Balancing of symbols
- Infix to Postfix /Prefix conversion
- Redo-undo features at many places like editors, photoshop.
- Forward and backward feature in web browsers
- Used in many algorithms like Tower of Hanoi, tree traversals, stock span problem, histogram problem.
- Other applications can be Backtracking, Knight tour problem, rat in a maze, N queen problem and sudoku solver
- In Graph Algorithms like Topological Sorting and Strongly Connected Components
- Using array
- Using linked list
- Linked List: Like arrays, Linked List is a linear data structure. Unlike arrays, linked list elements are not stored at contiguous location; the elements are linked using pointers. Why Linked List? Arrays can be used to store linear data of similar types, but arrays have following limitations. 1) The size of the arrays is fixed: So we must know the upper limit on the number of elements in advance. Also, generally, the allocated memory is equal to the upper limit irrespective of the usage. 2) Inserting a new element in an array of elements is expensive, because room has to be created for the new elements and to create room existing elements have to shifted. For example, in a system if we maintain a sorted list of IDs in an array id[]. id[] = [1000, 1010, 1050, 2000, 2040]. And if we want to insert a new ID 1005, then to maintain the sorted order, we have to move all the elements after 1000 (excluding 1000). Deletion is also expensive with arrays until unless some special techniques are used. For example, to delete 1010 in id[], everything after 1010 has to be moved. Advantages over arrays 1) Dynamic size 2) Ease of insertion/deletion Drawbacks: 1) Random access is not allowed. We have to access elements sequentially starting from the first node. So we cannot do binary search with linked lists efficiently with its default implementation. Read about it here. 2) Extra memory space for a pointer is required with each element of the list. 3) Not cache friendly. Since array elements are contiguous locations, there is locality of reference which is not there in case of linked lists. Representation: A linked list is represented by a pointer to the first node of the linked list. The first node is called head. If the linked list is empty, then value of head is NULL. Each node in a list consists of at least two parts: 1) data 2) Pointer (Or Reference) to the next node In C, we can represent a node using structures. Below is an example of a linked list node with an integer data.
C
struct Node {
int data;
struct Node* next;
};
|
- Command line argument: The most important function of C/C++ is main() function. It is mostly defined with a return type of int and without parameters :
int main() { /* ... */ }
- We can also give command-line arguments in C and C++. Command-line arguments are given after the name of the program in command-line shell of Operating Systems. To pass command line arguments, we typically define main() with two arguments : first argument is the number of command line arguments and second is list of command-line arguments.
int main(int argc, char *argv[]) { /* ... */ }
int main(int argc, char **argv) { /* ... */ }
- argc (ARGument Count) is int and stores number of command-line arguments passed by the user including the name of the program. So if we pass a value to a program, value of argc would be 2 (one for argument and one for program name)
- The value of argc should be non negative.
- argv(ARGument Vector) is array of character pointers listing all the arguments.
- If argc is greater than zero, the array elements from argv[0] to argv[argc-1] will contain pointers to strings.
- Argv[0] is the name of the program, After that till argv[argc-1] every element is command -line arguments.
Share your thoughts in the comments
Please Login to comment...