Strings
Strings are used for storing text/characters.
For example, "Hello World" is a string of characters.
Unlike many other programming languages, C does not have a String
type to easily create string variables. Instead, you must use the char type
and create an array of characters to make a string in C:
char greetings[] = "Hello World!";
Note that you have to use double quotes ( "").
To output the string, you can use the printf() function together with the
format specifier %s to tell C that we are now working with strings:
Example
char greetings[] = "Hello World!";
printf("%s", greetings);
Access Strings
Since strings are actually arrays in C, you can access a string by referring to
its index number inside square brackets [].
This example prints the first character (0) in greetings:
Example
char greetings[] = "Hello World!";
printf("%c", greetings[0]);
Modify Strings
To change the value of a specific character in a string, refer to the index
number, and use single quotes:
Example
char greetings[] = "Hello World!";
greetings[0] = 'J';
printf("%s", greetings);
// Outputs Jello World! instead of Hello World!
C Programming Strings
In C programming, a string is a sequence of characters terminated with a
null character \0 . For example:
char c[] = "c string";
When the compiler encounters a sequence of characters enclosed in the
double quotation marks, it appends a null character \0 at the end by
default.
Memory Diagram
Here's how you can declare strings:
char s[5];
String Declaration in C
How to initialize strings?
You can initialize strings in a number of ways.
String Initialization in C
Assigning Values to Strings
Arrays and strings are second-class citizens in C; they do not support the
assignment operator once it is declared. For example,
char c[100];
c = "C programming"; // Error! array type is not assignable.
Note: Use the strcpy() function to copy the string instead.
Read String from the user
You can use the scanf() function to read a string.
The scanf() function reads the sequence of characters until it
encounters whitespace (space, newline, tab, etc.).
Example 1: scanf() to read a string
#include <stdio.h>
int main()
{
char name[20];
printf("Enter name: ");
scanf("%s", name);
printf("Your name is %s.", name);
return 0;
}
Enter name: Dennis Ritchie
Your name is Dennis.
Even though Dennis Ritchie was entered in the above program,
only "Dennis" was stored in the name string. It's because there was a space
after Dennis .
Also notice that we have used the code name instead of &name with scanf() .
scanf("%s", name);
This is because name is a char array, and we know that array names decay
to pointers in C.
Thus, the name in scanf() already points to the address of the first element
in the string, which is why we don't need to use & .
How to read a line of text?
You can use the fgets() function to read a line of string. And, you can
use puts() to display the string.
Example 2: fgets() and puts()
#include <stdio.h>
int main()
{
char name[30];
printf("Enter name: ");
fgets(name, sizeof(name), stdin); // read string
printf("Name: ");
puts(name); // display string
return 0;
}
Output
Enter name: Tom Hanks
Name: Tom Hanks
Here, we have used fgets() function to read a string from the user.
fgets(name, sizeof(name), stdlin); // read string
The sizeof(name) results to 30. Hence, we can take a maximum of 30
characters as input which is the size of the name string.
To print the string, we have used puts(name); .
Note: The gets() function can also be to take input from the user.
However, it is removed from the C standard.
It's because gets() allows you to input any length of characters. Hence,
there might be a buffer overflow.
Passing Strings to Functions
Strings can be passed to a function in a similar way as arrays. Learn more
about passing arrays to a function.
Example 3: Passing string to a Function
#include <stdio.h>
void displayString(char str[]);
int main()
{
char str[50];
printf("Enter string: ");
fgets(str, sizeof(str), stdin);
displayString(str); // Passing string to a function.
return 0;
}
void displayString(char str[])
{
printf("String Output: ");
puts(str);
}
Commonly Used String Functions
strlen() - calculates the length of a string
strcpy() - copies a string to another
strcmp() - compares two strings
strcat() - concatenates two strings
C Functions
A function is a block of code that performs a specific task.
Suppose, you need to create a program to create a circle and color it. You
can create two functions to solve this problem:
create a circle function
create a color function
Dividing a complex problem into smaller chunks makes our program easy
to understand and reuse.
Types of function
There are two types of function in C programming:
Standard library functions
User-defined functions
Standard library functions
The standard library functions are built-in functions in C programming.
These functions are defined in header files. For example,
The printf() is a standard library function to send formatted output
to the screen (display output on the screen). This function is defined
in the stdio.h header file.
Hence, to use the printf() function, we need to include
the stdio.h header file using #include <stdio.h> .
The sqrt() function calculates the square root of a number. The
function is defined in the math.h header file.
User-defined function
You can also create functions as per your need. Such functions created by
the user are known as user-defined functions.
How user-defined function works?
#include <stdio.h>
void functionName()
... .. ...
... .. ...
int main()
... .. ...
... .. ...
functionName();
... .. ...
... .. ...
}
The execution of a C program begins from the main() function.
When the compiler encounters functionName(); , control of the program
jumps to
void functionName()
And, the compiler starts executing the codes inside functionName() .
The control of the program jumps back to the main() function once
code inside the function definition is executed.
Note, function names are identifiers and should be unique.
This is just an overview of user-defined functions. Visit these pages to learn
more on:
User-defined Function in C programming
Types of user-defined Functions
Advantages of user-defined function
1. The program will be easier to understand, maintain and debug.
2. Reusable codes that can be used in other programs
3. A large program can be divided into smaller modules. Hence, a large
project can be divided among many programmers.
Types of User-defined
Functions in C Programming
These 4 programs below check whether the integer entered by the user is
a prime number or not.
The output of all these programs below is the same, and we have created a
user-defined function in each example. However, the approach we have
taken in each example is different.
Example 1: No Argument Passed and No
Return Value
#include <stdio.h>
void checkPrimeNumber();
int main() {
checkPrimeNumber(); // argument is not passed
return 0;
}
// return type is void meaning doesn't return any value
void checkPrimeNumber() {
int n, i, flag = 0;
printf("Enter a positive integer: ");
scanf("%d",&n);
// 0 and 1 are not prime numbers
if (n == 0 || n == 1)
flag = 1;
for(i = 2; i <= n/2; ++i) {
if(n%i == 0) {
flag = 1;
break;
}
}
if (flag == 1)
printf("%d is not a prime number.", n);
else
printf("%d is a prime number.", n);
}
Run Code
The checkPrimeNumber() function takes input from the user, checks whether
it is a prime number or not, and displays it on the screen.
The empty parentheses in checkPrimeNumber(); inside the main() function
indicates that no argument is passed to the function.
The return type of the function is void . Hence, no value is returned from the
function.
Example 2: No Arguments Passed But Returns
a Value
#include <stdio.h>
int getInteger();
int main() {
int n, i, flag = 0;
// no argument is passed
n = getInteger();
// 0 and 1 are not prime numbers
if (n == 0 || n == 1)
flag = 1;
for(i = 2; i <= n/2; ++i) {
if(n%i == 0){
flag = 1;
break;
}
}
if (flag == 1)
printf("%d is not a prime number.", n);
else
printf("%d is a prime number.", n);
return 0;
}
// returns integer entered by the user
int getInteger() {
int n;
printf("Enter a positive integer: ");
scanf("%d",&n);
return n;
}
Run Code
The empty parentheses in the n = getInteger(); statement indicates that
no argument is passed to the function. And, the value returned from the
function is assigned to n .
Here, the getInteger() function takes input from the user and returns it.
The code to check whether a number is prime or not is inside
the main() function.
Example 3: Argument Passed But No Return
Value
#include <stdio.h>
void checkPrimeAndDisplay(int n);
int main() {
int n;
printf("Enter a positive integer: ");
scanf("%d",&n);
// n is passed to the function
checkPrimeAndDisplay(n);
return 0;
}
// return type is void meaning doesn't return any value
void checkPrimeAndDisplay(int n) {
int i, flag = 0;
// 0 and 1 are not prime numbers
if (n == 0 || n == 1)
flag = 1;
for(i = 2; i <= n/2; ++i) {
if(n%i == 0){
flag = 1;
break;
}
}
if(flag == 1)
printf("%d is not a prime number.",n);
else
printf("%d is a prime number.", n);
}
Run Code
The integer value entered by the user is passed to
the checkPrimeAndDisplay() function.
Here, the checkPrimeAndDisplay() function checks whether the argument
passed is a prime number or not and displays the appropriate message.
Example 4: Argument Passed and Returns a
Value
#include <stdio.h>
int checkPrimeNumber(int n);
int main() {
int n, flag;
printf("Enter a positive integer: ");
scanf("%d",&n);
// n is passed to the checkPrimeNumber() function
// the returned value is assigned to the flag variable
flag = checkPrimeNumber(n);
if(flag == 1)
printf("%d is not a prime number",n);
else
printf("%d is a prime number",n);
return 0;
}
// int is returned from the function
int checkPrimeNumber(int n) {
// 0 and 1 are not prime numbers
if (n == 0 || n == 1)
return 1;
int i;
for(i=2; i <= n/2; ++i) {
if(n%i == 0)
return 1;
}
return 0;
}
Run Code
The input from the user is passed to the checkPrimeNumber() function.
The checkPrimeNumber() function checks whether the passed argument is
prime or not.
If the passed argument is a prime number, the function returns 0. If the
passed argument is a non-prime number, the function returns 1. The return
value is assigned to the flag variable.
Depending on whether flag is 0 or 1, an appropriate message is printed
from the main() function.
#include <stdio.h>
void ap_capital(void);
void ts_capital(void);
void main() {
ap_capital();
ts_capital();
void ap_capital(void) {
printf("Amaravathi\n");
void ts_capital(void) {
printf("Hyderabad\n");
#include <stdio.h>
int sum(int, int);
int sub(int, int);
int mul(int, int);
int div(int, int);
void main() {
int a, b;
printf("Enter two values : ");
scanf("%d%d", &a, &b);
printf("Addition of two values = %d\n", sum(a, b));
printf("Subtraction of two values = %d\n", sub(a, b));
printf("multiplication of two values = %d\n", mul(a, b));
printf("division of two values = %d\n", div(a, b));
}
sum(int x,int y ) { // Correct the code
return(x+y) ; // Correct the code
sub(int x,int y ) { // Correct the code
return(x-y) ; // Correct the code
mul(int x,int y ) { // Correct the code
return(x*y) ; // Correct the code
div(int x,int y ) { // Correct the code
return(x/y) ; // Correct the code
#include <stdio.h>
float sum(float a,float b) {
return(a+b);
float sub(float x,float y ) {
return(x-y);
float mul(float x,float y ) {
return(x*y);
}
float div(float x,float y ) {
return(x/y);
void main() {
float a, b;
printf("Enter two values : ");
scanf("%f%f", &a, &b);
printf("Addition of two values = %f\n", sum(a, b));
printf("Subtraction of two values = %f\n", sub(a, b));
printf("multiplication of two values = %f\n", mul(a, b));
printf("division of two values = %f\n", div(a, b));
}
An argument is an expression which is passed to a function by its
caller in order for the function to perform its task. It is an
expression in the comma-separated list bound by the parentheses
in a function call expression.
A function may be called by the portion of the program with some
arguments and these arguments are known as actual
arguments (or) original arguments.
Actual arguments are local to the particular function. These
variables are placed in the function declaration and function
call. These arguments are defined in the calling function.
The parameters are variables defined in the function to receive the
arguments.
Formal parameters are those parameters which are present in
the function definition.
Formal parameters are available only with in the specified
function. Formal parameters belong to the called function.
Formal parameters are also the local variables to the function.
So, the formal parameters are occupied memory when the
function execution starts and they are destroyed when the
function execution completed.
Let us consider the below example:
#include <stdio.h>
int add(int, int);
void main() {
int a = 10, b = 20;
printf("Sum of two numbers = %d\n", add(a, b)); // variables a, b
are called actual arguments
}
int add(int x, int y) { // variables x, y are called formal parameters
return(x + y);
}
In the above code whenever the function call add(a, b) is made, the
execution control is transferred to the function definition of add().
The values of actual arguments a and b are copied in to the formal
arguments x and y respectively.
The formal parameters x and y are available only with in the
function definition of add(). After completion of execution of add(),
the control is transferred back to the main().
#include <stdio.h>
int sum(int);
void main() {
int number; // number is called actual argument
printf("Enter an integer value : ");
scanf("%d", &number);
printf("Sum of %d natural numbers = %d\n", number, sum(number));
int sum(int value) { // value is called formal argument
return(value*(value+1)/2);// write the code to find sum of n natrual numbers
// return the result
Local variables are declared and used inside a function (or) in
a block of statements.
Local variables are created at the time of function call and
destroyed when the function execution is completed.
Local variables are accessible only with in the particular
function where those variables are declared.
Global variables are declared outside of all the function blocks and
these variables can be used in all functions.
Global variables are created at the time of program beginning
and reside until the end of the entire program.
Global variables are accessible in the entire program.
If a local and global variable have the same name, then local
variable has the highest precedence to access with in the
function.
Let us consider an example:
#include <stdio.h>
void change();
int x = 20; // Global Variable x
void main() {
int x = 10; // Local Variable x
change();
printf("%d", x); // The value 10 is printed
}
void change() {
printf("%d", x); // The value 20 is printed
}
In the above code the global and local variables have the same
variable name x, but they are different.
In main() function the local variable x is only accessed, so it prints
the value 10.
In change() function the variable x is not declared locally so it
access global variable x, so it prints 20.
The user can write any number of function definitions within the
own header file. The own header files can also end with an
extension .h.
Programmers can include their own header files by
using #include as #include "own header file name".
For example, if you want to include your own header file sum. h it
can be written as #include "sum.h" The main advantage of creating
own header files is the function defined within the header file can
be directly used in any program just by including the header file.
i.e., re-usage of code is done by writing the code only once in the
header file.
Remember that when including files in the C program, check it
once if there is only one main() function is defined, because
multiple definitions of main() creates ambiguity where to start the
program execution.
Headerdemo.h
int sum(int a, int b) {
return (a+b);
// return the sum of a and b
Headerdemo.c
#include <stdio.h>
#include "HeaderDemo.h"
// include header file here
void main() {
int a, b;
printf("Enter two numbers : ");
scanf("%d%d", &a, &b);
printf("The sum of given two numbers = %d\n", sum(a, b));