Q1 Explain the history of language?
= C Programming history:-
In 1960, ALGOL was developed by the international group.
In 1966, Martin Richards developed BCPL (Basic Combined Programming Language before developing C.
Later, Ken Thomson further developed BCPL by developing the first letter of BCPL i.e. he developed the B
language.
Ken Thomson developed BASIC type of UNIX Operating System, while the B language was in motion.
After all this, by further developing the B language, Dennis Ritchie developed the C language in the Bell
laboratory.
After developing the C language, Dennis Ritchie and Ken Thompson together developed the UNIX
Operating System.
In 1978, Kerni Ghan and Ritchie both did further improvement in C language and they brought the C
programming language in front of the whole world.
In 1989, ANSI C developed by the ANSI Committee.
In 1999, The new version of C was developed, In which have new features like Data Types-
char,float,int,double was used.
Today‟s we are using the new version of C is C11, which is developed by Standard Commit
Q2 ) Explain structure of C program?
Documentation section
The documentation section consists of a set of comment lines giving the name of the program, the author
and other details, which the programmer would like to use later.
Link section
The link section provides instructions to the compiler to link functions from the system library such as
using the #include directive.
Definition section
The definition section defines all symbolic constants such using the #define directive.
Global declaration section
There are some variables that are used in more than one function. Such variables are called global
variables and are declared in the global declaration section that is outside of all the functions. This section
also declares all the user-defined functions.
main () function section
Every C program must have one main function section. This section contains two parts; declaration part
and executable part
Declaration part
The declaration part declares all the variables used in the executable part.
Executable part
There is at least one statement in the executable part. These two parts must appear between the opening
and closing braces. The program execution begins at the opening brace and ends at the closing brace. The
closing brace of the main function is the logical end of the program. All statements in the declaration and
executable part end with a semicolon.
Q 3 Explain character set in C language.
There are four type of character set in C programming.
Alphabets
Digit
Special Character
White space
Alphabets
Alphabets has a two case.
Upper case A-Z
Lower case a a-z.
Digit
C programming support 10 digit which are used to construct numerical value.
Digit 0-9.
Special character
C programming supports set of special symbols that include symbols to perform mathematical operation,
check condition and other special symbol.
Special character %,&,*,etc..
White space
In computer programming, white space is a character that represent vertical space in typography.
White space \b,\v,\? and so on.
Q4 Explain the feature of c language
1) Simple
C is a simple language in the sense that it provides a structured approach (to break the problem into
parts), the rich set of library functions, data types, etc.
2) Machine Independent or Portable
Unlike assembly language, c programs can be executed on different machines with some machine
specific changes. Therefore, C is a machine independent language.
3) Mid-level programming language
Although, C is intended to do low-level programming. It is used to develop system applications such
as kernel, driver, etc. It also supports the features of a high-level language. That is why it is known
as mid-level language.
4) Structured programming language
C is a structured programming language in the sense that we can break the program into parts using
functions. So, it is easy to understand and modify. Functions also provide code reusability.
5) Rich Library
C provides a lot of inbuilt functions that make the development fast.
6) Memory Management
It supports the feature of dynamic memory allocation. In C language, we can free the allocated
memory at any time by calling the free() function.
7) Speed
The compilation and execution time of C language is fast since there are lesser inbuilt functions and hence
the lesser overhead
Q5 Explain the types of error
Errors are the problems or the faults that occur in the program, which makes the behavior of the program
abnormal, and experienced developers can also make these faults. Programming errors are also known as
the bugs or faults, and the process of removing these bugs is known as debugging.
These errors are detected either during the time of compilation or execution. Thus, the errors must be
removed from the program for the successful execution of the program.
There are mainly five types of errors exist in C program
o Syntax error
o Run-time error
o Linker error
o Logical error
o Semantic error
1. Syntax Errors
These are also referred to as compile-time errors. These errors have occurred when the rule of C writing
techniques or syntaxes has been broken. These types of errors are typically flagged by the compiler prior
to compilation.
Example 1: In the below program we are getting an error because of a missing semicolon at the end of
the output statement (printf()) called syntax error.
2. Runtime Errors
This type of error occurs while the program is running. Because this is not a compilation error, the
compilation will be completed successfully. These errors occur due to segmentation fault when a number
is divided by division operator or modulo division operator.
Example: Let us consider an array of length 5 i.e. array[5], but during runtime, if we try to access 10
elements i.e array[10] then we get segmentation fault errors called runtime errors. Giving only an array
length of 5
3. Logical Errors
Even if the syntax and other factors are correct, we may not get the desired results due to logical issues.
These are referred to as logical errors. We sometimes put a semicolon after a loop, which is syntactically
correct but results in one blank loop. In that case, it will display the desired output.
Example: In the below example, the for loop iterates 5 times but the output will be displayed only one
time due to the semicolon at the end of for loop. This kind of error is called a logical error.
4. Linker Errors
When the program is successfully compiled and attempting to link the different object files with the main
object file, errors will occur. When this error occurs, the executable is not generated. This could be due to
incorrect function prototyping, an incorrect header file, or other factors. If main() is written as Main(), a
linked error will be generated.
Example: Below is the C program to show the linker er
5. Semantic Errors
When a sentence is syntactically correct but has no meaning, semantic errors occur. This is similar to
grammatical errors. If an expression is entered on the left side of the assignment operator, a semantic
error may occur.
Example: Below is the C program to show semantic error.
Q 6 Explain formatted and unformatted input and output functions
In C programming, input and output operations can be categorized into two main types: formatted and
unformatted.
1. Formatted Input/Output:
printf(): This function is used for formatted output. It allows you to display information on
the console in a formatted way. You specify the format using format specifiers like %d for
integers, %f for floats, %s for strings, etc.
scanf(): This function is used for formatted input. It allows you to read data from the
console in a specific format. You need to specify the format using format specifiers.
2. Unformatted Input/Output:
puts(): This function is used for unformatted output. It is mainly used for printing strings to
the console.
gets(): This function is used for unformatted input. It reads a line of text from the console.
Unformatted I/O is less structured and doesn't have the same level of control over the display or reading
of data as formatted I/O. It's generally safer to use formatted I/O functions like printf and scanf to
prevent buffer overflow issues associated with unformatted I/O functions like gets.
Note: The use of gets() is discouraged due to the risk of buffer overflow. Instead, you should use safer
alternatives like fgets() for reading strings.
Q7 What is variable? Explain the different types of data types in C programming.
OR Explain data type in C
A variable is a name of the memory location. It is used to store data. Its value can be changed, and it
can be reused many times.
Data Types in C
A data type specifies the type of data that a variable can store such as integer, floating, character, etc.
There are the following data types in C language.
Types Data Types
Basic Data Type int, char, float, double
Derived Data Type array, pointer, structure, union
Enumeration Data Type enum
Void Data Type void
Basic Data Types
The basic data types are integer-based and floating-point based. C language supports both signed and
unsigned literals.
Int:
Integers are entire numbers without any fractional or decimal parts, and the int data type is used to
represent them.
It is frequently applied to variables that include values, such as counts, indices, or other numerical
numbers. The int data type may represent both positive and negative numbers because it is signed
by default.
An int takes up 4 bytes of memory on most devices, allowing it to store values between around -2 billion
and +2 billion.
Char:
Individual characters are represented by the char data type. Typically used to hold ASCII or UTF-8
encoding scheme characters, such as letters, numbers, symbols, or commas. There are 256
characters that can be represented by a single char, which takes up one byte of memory. Characters
such as 'A', 'b', '5', or '$' are enclosed in single quotes.
Float:
To represent integers, use the floating data type. Floating numbers can be used to represent fractional
units or numbers with decimal places.
The float type is usually used for variables that require very good precision but may not be very precise.
It can store values with an accuracy of about 6 decimal places and a range of about 3.4 x 1038 in 4
bytes of memory.
Double:
Use two data types to represent two floating integers. When additional precision is needed, such as in
scientific calculations or financial applications, it provides greater accuracy compared to float.
Double type, which uses 8 bytes of memory and has an accuracy of about 15 decimal places, yields
larger values. C treats floating point numbers as doubles by default if no explicit type is supplied.
Derived Data Type
Beyond the fundamental data types, C also supports derived data types, including arrays, pointers,
structures, and unions. These data types give programmers the ability to handle heterogeneous data,
directly modify memory, and build complicated data structures.
Array:
An array, a derived data type, lets you store a sequence of fixed-size elements of the same type. It
provides a mechanism for joining multiple targets of the same data under the same name.
Pointer:
A pointer is a derived data type that keeps track of another data type's memory address. When
a pointer is declared, the data type it refers to is stated first, and then the variable name is preceded
by an asterisk (*).
Structure:
A structure is a derived data type that enables the creation of composite data types by allowing the
grouping of many data types under a single name.
Q8 Explain the use printf( ) & scanf( ) function with example.
printf() and scanf() in C
The printf() function is used to display output and the scanf() function is used to take input from users.
The printf() and scanf() functions are commonly used functions in C Language. These functions are inbuilt
library functions in header files of C programm
printf() Function
In C Programming language, the printf() function is used for output.
printf() function can take any number of arguments. First argument must be enclosed within the double
quotes “hello” and every other argument should be separated by comma ( , ) within the double quotes.
Important points about printf():
printf() function is defined in stdio.h header file. By using this function, we can print the data or
user-defined message on monitor (also called the console).
printf() can print a different kind of data format on the output string.
To print on a new line on the screen, we use “\n” in printf() statement.
C language is case sensitive programming language. For example, printf() and scanf() in lowercase letters
treated are different from Printf() and Scanf(). All characters in printf() and scanf() builtin functions must
be in lower case.
Syntax
printf("format specifier",argument_list);
The format string for output can be %d (integer), %c (character), %s (string), %f (float) %lf (double)
and %x (hexadecimal) variable.
scanf() Function
The scanf() function is used to read input data from the console.
The scanf() function is builtin function available in the C library. scanf() function can read character,
string, numeric & other data from keyboard in C language.
scanf() reads formatted data from user and assign them in the variables provided the additional
arguments. Additional arguments must point to variables that have the same datatype as of user input
data format.
Syntax
scanf("format specifier",argument_list);
Q9 What is constant? Explain how to declare a symbolic constant with example?
A constant in C is a value that doesn't change as the program runs. Integers, floating-point
numbers, characters, and strings are just a few of the several types of constants that may be
employed.
Symbolic Constants in C
Identifiers are used to represent fixed values in programs using symbolic constants in the C programming
language. These parameters are frequently used to increase the readability, maintainability,
and modifiability of code, which may be numerical or not. The C language's "#define" command is used to
declare symbolic constants.
Syntax:
Syntax for defining a symbolic constant in C:
1. #define MAX_V 100
In this example, the symbolic constant "MAX_V" is specified to have a value of 100. It indicates that
the number 100 will be substituted for "MAX_V" wherever it appears in the code at compilation time.
Q 10 What is variable? Write rules to declare variable in C?
Variable
It is the name for memory location that may be used to store a data value.
A variable may take different values at different times during execution.
A variable name may be chosen by the programmer in a meaningful way, so as to reflect its
function (or) nature in the program.
For example, sum, avg, total etc.
Rules for naming variable
The rules for naming a variable are explained below −
They must begin with a letter.
Maximum length of variable is 31 characters in ANSI standard. But, first eight characters are
significant by many compilers.
Upper and lowercase characters are different. For example: total, TOTAL, Total are 3 different
variables.
The variable is not to be a keyword.
White space is not allowed.
Q 11 ) What is keyword? List all supported by C language?
Or What is keyword ? Explain any six keywords in C language
Keywords are predefined or reserved words that have special meanings to the compiler. These are part of
the syntax and cannot be used as identifiers in the program. A list of keywords in C or reserved words in
the C programming language are mentioned below:
auto break case char const continue default do
double else enum extern float for goto if
int long register return short signed sizeof static
struct switch typedef union unsigned void volatile while
auto
auto is the default storage class variable that is declared inside a function or a block. auto variables can
only be accessed within the function/block they are declared. By default, auto variables have garbage
values assigned to them. Automatic variables are also called local variables as they are local to a
function.
auto int num;
break and continue
The break statement is used to terminate the innermost loop. It generally terminates a loop or a switch
statement. The switch statement skips to the next iteration of the loop. Below is the C program to
demonstrate break and continue in
switch, case, and default
The switch statement in C is used as an alternate to the if-else ladder statement. For a single variable i.e,
switch variable it allows us to execute multiple operations for different possible values of a single variable
. charchar keyword in C is used to declare a character variable in the C programming language.
const
The const keyword defines a variable who‟s value cannot be changed.
do
The do statement is used to declare a do-while loop. A do-while loop is a loop that executes once, and
then checks it‟s condition to see if it should continue through the loop. After the first iteration, it will
continue to execute the code while the condition is true.
Q12 Describe scope of variable.
The scope of a variable in C is the block or the region in the program where a variable is declared,
defined, and used. Outside this region, we cannot access the variable and it is treated as an undeclared
identifier.
The scope is the area under which a variable is visible.
The scope of an identifier is the part of the program where the identifier may directly be accessible.
We can only refer to a variable in its scope.
In C, all identifiers are lexically(or statically) scoped.
Types of Scope Rules in C
C scope rules can be covered under the following two categories
1. Global Scope
2. Local Scope
Let‟s discuss each scope rule with examples.
1. Global Scope in C
The global scope refers to the region outside any block or function.
The variables declared in the global scope are called global variables.
Global variables are visible in every part of the program.
Global is also called File Scope as the scope of an identifier starts at the beginning of the file and
ends at the end of the file.
Local Scope in C
The local scope refers to the region inside a block or a function. It is the space enclosed between the { }
braces.
The variables declared within the local scope are called local variables.
Local variables are visible in the block they are declared in and other blocks nested inside that block.
Local scope is also called Block scope.
Local variables have internal linkage.
Q13 What is conditional operator? Explain with example.
The conditional operator is also known as a ternary operator. The conditional statements are the
decision-making statements which depends upon the output of the expression. It is represented by two
symbols, i.e., '?' and ':'.
As conditional operator works on three operands, so it is also known as the ternary operator.
The behavior of the conditional operator is similar to the 'if-else' statement as 'if-else' statement is also a
decision-making statement.
Syntax of a conditional operator
1. Expression1? expression2: expression3;
o In the above syntax, the expression1 is a Boolean condition that can be either true or false value.
o If the expression1 results into a true value, then the expression2 will execute.
o The expression2 is said to be true only when it returns a non-zero value.
o If the expression1 returns false value then the expression3 will execute.
o The expression3 is said to be false only when it returns zero value.
Let's understand the ternary or conditional operator through an example.
#include <stdio.h>
int main()
{
int age; // variable declaration
printf("Enter your age");
scanf("%d",&age); // taking user input for age variable
(age>=18)? (printf("eligible for voting")) : (printf("not eligible for voting")); // conditional operator
return 0;
}
Q14 What is an operator? Explain the arithmetic, relational, logical operators in C language.
Operators are the special symbols in the C programming language, which is used to perform various
mathematical and logical operations on the given operands to return the appropriate results.
Arithmetic Operators
The following table shows all the arithmetic operators supported by the C language. Assume
variable A holds 10 and variable B holds 20 then −
Operator Description Example
+ Adds two operands. A + B = 30
− Subtracts second operand from the first. A − B = -10
* Multiplies both operands. A * B = 200
/ Divides numerator by de-numerator. B/A=2
% Modulus Operator and remainder of after an integer division. B%A=0
++ Increment operator increases the integer value by one. A++ = 11
-- Decrement operator decreases the integer value by one. A-- = 9
Relational Operators
The following table shows all the relational operators supported by C. Assume variable A holds 10 and
variable B holds 20 then −
Operator Description Example
== Checks if the values of two operands are equal or not. If yes, then the (A == B)
condition becomes true.
!= Checks if the values of two operands are equal or not. If the values are not (A != B
equal, then the condition becomes true.
> Checks if the value of left operand is greater than the value of right (A > B
operand. If yes, then the condition becomes true.
< Checks if the value of left operand is less than the value of right operand. If (A < B)
yes, then the condition becomes true.
>= Checks if the value of left operand is greater than or equal to the value of (A >= B)
right operand. If yes, then the condition becomes true.
<= Checks if the value of left operand is less than or equal to the value of right (A <= B
operand. If yes, then the condition becomes true.
Logical Operators
Following table shows all the logical operators supported by C language. Assume variable A holds 1 and
variable B holds 0, then −
Operator Description Example
&& Called Logical AND operator. If both the operands are non-zero, then (A && B)
the condition becomes true. is false.
|| Called Logical OR Operator. If any of the two operands is non-zero, (A || B)
then the condition becomes true. is true.
! Called Logical NOT Operator. It is used to reverse the logical state of !(A &&
its operand. If a condition is true, then Logical NOT operator will B) is
make it false. true.
Q What do you mean by type casting? Explain implicit and explicit type casting with example?
In computer science, type casting is the process of assigning a value of one data type to another
type. There are two types of type casting:
Implicit casting
Automatically converts a smaller type to a larger type size. For example, in C#, implicit casting converts a
char to an int, long, float, or double.
Explicit casting
Manually converts a larger type to a smaller size type. For example, in C, explicit casting uses the casting
operator (new_data_type) to convert values between different data types.
Implicit type casting is also known as widening conversion. Explicit type casting is used when there is a
possibility of data loss.
Here are some examples of implicit and explicit type casting:
Implicit casting: In C#, implicit casting converts a char to an int, long, float, or double.
Explicit casting: In C, explicit casting uses the casting operator (new_data_type) to convert values
between different data types. For example, in C, a float variable can be converted into an int
(integer) data type.
In programming, implicit is often used to refer to something that's done for you by other code behind the
scenes. Explicit is the manual approach to accomplishing the change you wish to have by writing out the
instructions to be done explicitly.
Q Explain the working of switch statement with syntax? Or Explain the working of switch
statement with syntax and suitable example
We can define various statements in the multiple cases for the different values of a single variable.
The syntax of switch statement in c language is given below:
switch(expression){
case value1:
//code to be executed;
break; //optional
case value2:
//code to be executed;
break; //optional
......
default:
code to be executed if all cases are not matched;
}
The expression used in a switch statement must have an integral or enumerated type, or be of a
class type in which the class has a single conversion function to an integral or enumerated type.
You can have any number of case statements within a switch. Each case is followed by the value to
be compared to and a colon.
The constant-expression for a case must be the same data type as the variable in the switch,
and it must be a constant or a literal.
When the variable being switched on is equal to a case, the statements following that case will
execute until a break statement is reached.
When a break statement is reached, the switch terminates, and the flow of control jumps to the
next line following the switch statement.
Not every case needs to contain a break. If no break appears, the flow of control will fall
through to subsequent cases until a break is reached.
A switch statement can have an optional default case, which must appear at the end of the
switch. The default case can be used for performing a task when none of the cases is true.
No break is needed in the default case.
Example
#include <stdio.h>
int main() {
int num = 8;
switch (num) {
case 7:
printf("Value is 7");
break;
case 8:
printf("Value is 8");
break;
case 9:
printf("Value is 9");
break;
default:
printf("Out of range");
break;
}
return 0;
}
Q Explain for loop with syntax and example.
The for loop in C language is used to iterate the statements or a part of the program several times. It is
frequently used to traverse the data structures like the array and linked list.
Syntax of for loop in C
The syntax of for loop in c language is given below:
for(Expression 1; Expression 2; Expression 3){
//code to be executed
}
Flowchart of for loop in C
for loop Examples
Let's see the simple program of for loop that prints table of 1.
#include<stdio.h>
int main(){
int i=0;
for(i=1;i<=10;i++){
printf("%d \n",i);
}
return 0;
}
Q Give difference between while and do-while loop OR State difference between while and do-
while loop? Write a program to display factorial of given number.
Here is an important difference between While and Do While Loop:
While Do While
It checks the condition first and then executes This loop will execute the statement(s) at
statement(s) least once, then the condition is checked.
While loop allows initialization of counter variables before Do while loop allows initialization of counter
starting the body of a loop. variables before and after starting the body
of a loop.
It is an entry controlled loop. It is an exit controlled loop.
We do not need to add a semicolon at the end of a while We need to add a semicolon at the end of
condition. the while condition.
In case of a single statement, we do need to add Brackets are always needed.
brackets.
In this loop, the condition is mentioned at the starting of The loop condition is specified after the
the loop. block is executed.
Statement(s) can be executed zero times if the condition Statement is executed at least once.
is false.
Generally while loop is written as: Generally do while loop is written as:
while (condition) { do{
Statements; // loop body Statements; //loop body
} } while (condition);
Example
#include<stdio.h>
int main()
{
int i,fact=1,number;
printf("Enter a number: ");
scanf("%d",&number);
for(i=1;i<=number;i++){
fact=fact*i;
}
printf("Factorial of %d is: %d",number,fact);
return 0;
}
Q Explain if-else control statement with proper syntax and example?
The if-else statement is a decision-making statement that is used to decide whether the part of the code
will be executed or not based on the specified condition (test expression). If the given condition is
true, then the code inside the if block is executed, otherwise the code inside the else block is executed.
Syntax of if-else
if (condition) {
}
else {
}
Example
#include <stdio.h>
int main()
{
if (5 < 10)
{
printf("5 is less than 10.");
}
Else
{
printf("5 is greater that 10.");
}
return 0;
}
if-else Statement works?
Working of the if-else statement in C is explained below:
When the program control first comes to the if-else block, the test condition is checked.
If the test condition is true:
The if block is executed.
If the test condition is false:
The else block is executed
After that, the program control continues to the statements below the if-else state
Q Explain nested for loop with suitable example? Also mention the rule of nested
for loop.
Nesting of loops is the feature in C that allows the looping of statements inside another loop. Let's observe
an example of nesting loops in C.
Any number of loops can be defined inside another loop, i.e., there is no restriction for defining any
number of loops. The nesting level can be defined at n times. You can define any type of loop inside
another loop; for example, you can define 'while' loop inside a 'for' loop.
Syntax of Nested loop
Outer_loop
{
Inner_loop
{
// inner loop statements.
}
// outer loop statements.
}
for (initialization; condition; update)
{
for(initialization; condition; update)
{
// inner loop statements.
}
// outer loop statements.
}
Example of nested for loop
1. #include <stdio.h>
int main()
{
int n;// variable declaration
printf("Enter the value of n :");
// Displaying the n tables.
for(int i=1;i<=n;i++) // outer loop
{
for(int j=1;j<=10;j++) // inner loop
{
printf("%d\t",(i*j)); // printing the value.
}
printf("\n");
}
Explain while loop with example
A while loop in C programming repeatedly executes a target statement as long as a given condition is
true.
Syntax
The syntax of a while loop in C programming language is −
while(condition) {
statement(s);
}
Here, statement(s) may be a single statement or a block of statements. The condition may be any
expression, and true is any nonzero value. The loop iterates while the condition is true.
When the condition becomes false, the program control passes to the line immediately following the loop.
Flow Diagram
Here, the key point to note is that a while loop might not execute at all. When the condition is tested and
the result is false, the loop body will be skipped and the first statement after the while loop will be
executed.
Example
#include <stdio.h>
int main ()
{
/* local variable definition */
int a = 10;
/* while loop execution */
while( a < 20 ) {
printf("value of a: %d\n", a);
a++;
}
return 0;
}
Q Write short note on array in C language with example? Or Define array? How a single
dimension and two dimension arrays are declared and initialized?
An array is defined as the collection of similar type of data items stored at contiguous memory locations.
Arrays are the derived data type in C programming language which can store the primitive type of data
such as int, char, double, float, etc. It also has the capability to store the collection of derived data types,
such as pointers, structure, etc. The array is the simplest data structure where each data element can be
randomly accessed by using its index number.
C array is beneficial if you have to store similar elements. For example, if we want to store the marks of a
student in 6 subjects, then we don't need to define different variables for the marks in the different
subject. Instead of that, we can define an array which can store the marks in each subject at the
contiguous memory locations.
Initialization of C Array
The simplest way to initialize an array is by using the index of each element. We can initialize each
element of the array by using the index. Consider the following example.
1. marks[0]=80;//initialization of array
2. marks[1]=60;
3. marks[2]=70;
4. marks[3]=85;
5. marks[4]=75;
include<stdio.h>
int main(){
int i=0;
int marks[5];//declaration of array
marks[0]=80;//initialization of array
marks[1]=60;
marks[2]=70;
marks[3]=85;
marks[4]=75;
//traversal of array
for(i=0;i<5;i++)
{
printf("%d \n",marks[i]);
}//end of for loop
return 0;
}
Initialization of 2D Array in C
In the 1D array, we don't need to specify the size of the array if the declaration and initialization are being
done simultaneously. However, this will not work with 2D arrays. We will have to define at least the
second dimension of the array. The two-dimensional array can be declared and defined in the following
way.
1. int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
Q Define String. List and explain any four String function in C.
String Functions in C
Some of the commonly used string functions in C are as follows:
1. strcat() Function
The strcat() function in C is used for string concatenation. It will append a copy of the source string to the
end of the destination string.
Syntax
char* strcat(char* dest, const char* src);
The terminating character at the end of dest is replaced by the first character of src.
Parameters
dest: Destination string
src: Source string
strncat()
This function is used for string handling. 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.
yntax of strncat()
char* strncat(char* dest, const char* src, size_t n);
where n represents the maximum number of characters to be appended. size_t is an unsigned integral
type.
2. strlen() Function
The strlen() function calculates the length of a given string. It doesn‟t count the null character „\0‟.
Syntax
int strlen(const char *str);
Parameters
str: It represents the string variable whose length we have to find.
Return Value
strlen() function in C returns the length of the string.
Example
C
// C program to demonstrate the strlen() function
#include <stdio.h>
#include <string.h>
int main()
{
// Declare and initialize a character array 'str' with
// the string "GeeksforGeeks"
char str[] = "GeeksforGeeks";
// Calculate the length of the string using the strlen()
// function and store it in the variable 'length'
size_t length = strlen(str);
// Print the length of the string
printf("String: %s\n", str);
printf("Length: %zu\n", length);
return 0;
}
Output
String: GeeksforGeeks
Length: 13
3. strcmp() Function
The strcmp() is a built-in library function in C. This function takes two strings as arguments and compares
these two strings lexicographically.
Syntax
int strcmp(const char *str1, const char *str2);
Parameters
str1: This is the first string to be compared.
str2: This is the second string to be compared.
Return Value
If str1 is less than str2, the return value is less than 0.
If str1 is greater than str2, the return value is greater than 0.
If str1 is equal to str2, the return value is 0.
Example
C
// C program to demonstrate the strcmp() function
#include <stdio.h>
#include <string.h>
int main()
{
// Define a string 'str1' and initialize it with "Geeks"
char str1[] = "Geeks";
// Define a string 'str2' and initialize it with "For"
char str2[] = "For";
// Define a string 'str3' and initialize it with "Geeks"
char str3[] = "Geeks";
// Compare 'str1' and 'str2' using strcmp() function and
// store the result in 'result1'
int result1 = strcmp(str1, str2);
// Compare 'str2' and 'str3' using strcmp() function and
// store the result in 'result2'
int result2 = strcmp(str2, str3);
// Compare 'str1' and 'str1' using strcmp() function and
// store the result in 'result3'
int result3 = strcmp(str1, str1);
// Print the result of the comparison between 'str1' and
// 'str2'
printf("Comparison of str1 and str2: %d\n", result1);
// Print the result of the comparison between 'str2' and
// 'str3'
printf("Comparison of str2 and str3: %d\n", result2);
// Print the result of the comparison between 'str1' and
// 'str1'
printf("Comparison of str1 and str1: %d\n", result3);
return 0;
}
Output
Comparison of str1 and str2: 1
Comparison of str2 and str3: -1
Comparison of str1 and str1: 0
There is a function strncmp() similar to strcmp().
strncmp()
This function lexicographically compares the first n characters from the two null-terminated strings and
returns an integer based on the outcome.
Syntax
int strncmp(const char* str1, const char* str2, size_t num);
Where num is the number of characters to compare.
4. strcpy
The strcpy() is a standard library function in C and is used to copy one string to another. In C, it is present
in <string.h> header file.
Syntax
char* strcpy(char* dest, const char* src);
Parameters
dest: Pointer to the destination array where the content is to be copied.
src: string which will be copied.
Return Value
strcpy() function returns a pointer pointing to the output string.
Example
C
// C program to illustrate the use of strcpy()
#include <stdio.h>
#include <string.h>
int main()
{
// defining strings
char source[] = "GeeksforGeeks";
char dest[20];
// Copying the source string to dest
strcpy(dest, source);
// printing result
printf("Source: %s\n", source);
printf("Destination: %s\n", dest);
return 0;
}
Output
Source: GeeksforGeeks
Destination: GeeksforGeeks
strncpy()
The function strncpy() 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 an additional NULL character to dest to
ensure that a total of n characters are written.
Syntax
char* strncpy( char* dest, const char* src, size_t n );
Where n is the first n characters to be copied from src to dest.
5. strchr()
The strchr() function in C is a predefined function used for string handling. This function is used to find the
first occurrence of a character in a string.
Syntax
char *strchr(const char *str, int c);
Parameters
str: specifies the pointer to the null-terminated string to be searched in.
ch: specifies the character to be searched for.
Here, str is the string and ch is the character to be located. It is passed as its int promotion, but it is
internally converted back to char.
Return Value
It returns a pointer to the first occurrence of the character in the string.
Example
C++
#include <stdio.h>
#include <string.h>
int main()
{
char str[] = "GeeksforGeeks";
char ch = 'e';
// Search for the character 'e' in the string
// Use the strchr function to find the first occurrence
// of 'e' in the string
char* result = strchr(str, ch);
// Character 'e' is found, calculate the index by
// subtracting the result pointer from the str pointer
if (result != NULL) {
printf("The character '%c' is found at index %ld\n",
ch, result - str);
}
else {
printf("The character '%c' is not found in the "
"string\n",
ch);
}
return 0;
}