C Program to Search an Element in an Array Using Linear Search

  • Write a program for linear search in C.
  • Write a C program to search an element in array using linear search.

Required Knowledge

Algorithm to search an element in an unsorted array using linear search
Let inputArray is an integer array having N elements and K be the number to search.

  • Using a for loop, we will traverse inputArray from index 0 to N-1.
  • For every element inputArray[i], we will compare it with K for equality. If equal we will print the index of in inputArray.

C program to search an element in an array using linear search

C Program to Search an Element in an Array Using Linear Search

/*
* C Program to search any element or number in an array
*/
#include <stdio.h>
#include <conio.h>
  
int main(){
    int inputArray[100], elementCount, counter, num;
      
    printf("Enter Number of Elements in Array\n");
    scanf("%d", &elementCount);
    printf("Enter %d numbers \n", elementCount);
     
    /* Read array elements */
    for(counter = 0; counter < elementCount; counter++){
        scanf("%d", &inputArray[counter]);
    }
     
    printf("Enter a number to serach in Array\n");
    scanf("%d", &num);
     
    /* search num in inputArray from index 0 to elementCount-1 */
    for(counter = 0; counter < elementCount; counter++){
        if(inputArray[counter] == num){
            printf("Number %d found at index %d\n", num, counter);
            break;
        }
    }
     
    if(counter == elementCount){
     printf("Number %d Not Present in Input Array\n", num);
    }
          
    getch();
    return 0;
}

Output

Enter Number of Elements in Array
6
Enter 6 numbers
7 2 9 4 1 6
Enter a number to serach in Array
4
Number 4 found at index 3

C program to print hollow rectangle star pattern

C program to print hollow rectangle star pattern
  • Write a C program print hollow rectangular star pattern of n rows and m columns.

For a hollow rectangular star pattern of 4 rows and 12 columns. Program’s output should be:

Hollow_Rectangle_Star_Pattern

Required Knowledge

Algorithm to print hollow rectangular star pattern using loop

The algorithm of this pattern is similar to rectangular star pattern except here we have to print stars of first and last rows and columns only. At non-boundary position, we will only print a space character.

  • Take the number of rows(N) and columns(M) of rectangle as input from user using scanf function.
  • We will use two for loops to print empty rectangular star pattern.
    • Outer for loop will iterate N times. In each iteration, it will print one row of pattern.
    • Inside inner for loop, we will add a if statement check to find the boundary positions of the pattern and print star (*) accordingly.

Here is the matrix representation of the hollow rectangle star pattern. The row numbers are represented by i whereas column numbers are represented by j.
Hollow_Rectangle_Star_Pattern

C program to print hollow rectangular star pattern

C program to print hollow rectangle star pattern

#include<stdio.h>
 
int main(){
    int rows, cols , i, j;
     
    printf("Enter rows and columns of rectangle\n");
    scanf("%d %d", &rows, &cols);
     
    /* Row iterator for loop */
    for(i = 0; i < rows; i++){
     /* Column iterator for loop */
        for(j = 0; j < cols; j++){
            /* Check if currely position is a boundary position */
            if(i==0 || i==rows-1 || j==0 || j==cols-1)
                printf("*");
            else
                printf(" ");
        }
        printf("\n");
    }
    return 0;
}

Output

Enter rows and columns of rectangle
4 12
************
*          *
*          *
************

C Program to Print Pascal Triangle till N Rows

  • Write a C program to print pascal triangle till N rows by calculating binomial coefficients.
  • Algorithm to print pascal triangle.

Capture
<h4″>Required Knowledge

Pascal Triangle is a regular triangle of binomial coefficients. The counting of rows of the pascal triangle starts with 0 from top to bottom and elements in any particular row are numbered from left to right starting from 0.

Here is the formulae to find the value of nth element of rth row of pascal triangle.

Pascal_triangle

C program to print pascal triangle till N rows

C Program to Print Pascal Triangle till N Rows

#include <stdio.h>  
   
int getFactorial(int n);  
   
int main() {  
    int row, rows, i, value;
   
    printf("Enter Number of Rows of Pascal Triangle\n");  
    scanf("%d", &rows);  
   
    for(row = 0; row < rows; row++) {  
        /* Print Spaces for every row */  
        for(i = row; i <= rows; i++)  
            printf("  ");  
   
        for(i = 0; i <= row; i++) {  
            value = getFactorial(row)/(getFactorial(i)*getFactorial(row-i));  
            printf("%4d", value);  
        }  
   
        printf("\n");  
    }  
   
    return 0;  
}  
   
/*
 * Function to calculate factorial of a number 
 */
int getFactorial(int N){
    if(N < 0){
        printf("Invalid Input: factorial not defined for \
negative numbers\n");
        return 0;
    }
    int nFactorial = 1, counter;
    /*  N! = N*(N-1)*(N-2)*(N-3)*.....*3*2*1  */
    for(counter = 1; counter <= N; counter++){
        nFactorial = nFactorial * counter;
    }    
    return nFactorial;
}

Output

Enter Number of Rows of Pascal Triangle
5
      1
     1 1
    1 2 1
   1 3 3 1
  1 4 6 4 1

C Program to Print Triangle and Pyramid patterns of Star(*) Character Using Loop

C Program to Print Triangle and Pyramid patterns of Star(*) Character Using Loop

This Program first takes the numbers of rows in pattern and then prints the corresponding pattern using nested for loops. This kind of problems are useful for beginners to understands the fundamentals of loops and spaces. Here, we will discuss about four variations of patterns using ‘*’ character, right triangle, inverted right triangle, pyramid and inverted pyramid.

C program to print triangle pattern using * and loop

In this program, we first take the number of rows in the pattern as input from user using scanf function. Then we use two for loops to print triangle pattern. Outer for loop prints one horizontal row of pattern in one iteration whereas inner for loop prints n stars for nth row in one iteration.

C Program to Print Triangle and Pyramid patterns of Star(*) Character Using Loop

/*
* C program to print triangle pyramid pattern using *
*/
#include<stdio.h>
#include<conio.h>
 
int main() {
    int i,j,rows;
    printf("Enter the number of rows\n");
    scanf("%d", &rows);
     
    for(i = 1; i <= rows; i++) {
    /* Prints one row of triangle */
        for(j = 1; j <= i; ++j) {
           printf("* ");
        }
        printf("\n");
    }
    getch();
    return 0;
}

Program Output

Enter the number of rows
6
*
* *
* * *
* * * *
* * * * *
* * * * * *

C program to print inverted triangle pattern using * and loop

This c program is similar to above program, the only difference is the pattern is inverted. For ith row we are printing (rows – i + 1) starts.

For Example

Let, total number of rows in pattern is 6 then.
Number of starts in 3th row = 6 – 3 + 1 = 4

C program to print inverted triangle pattern using * and loop

/*
* C program to print inverted half pyramid pattern using *
*/
#include<stdio.h>
#include<conio.h>
 
int main() {
    int i,j,rows;
    printf("Enter the number of rows\n");
    scanf("%d", &rows);
     
    for(i = rows; i > 0; i--) {
    /* Prints one row of triangle */
        for(j = i; j > 0; j--) {
           printf("* ");
        }
        printf("\n");
    }
    getch();
    return 0;
}

Program Output

Enter the number of rows
6
* * * * * *
* * * * *
* * * *
* * * 
* *
*

C program to print pyramid pattern using * and loop

In this program, we are printing a pyramid pattern in which ith row contains (2*i – 1) space separated stars. We first take the number of rows in the pattern as input from user using scanf function. One iteration of outer for loop will print a row of pyramid. Inner for loop prints the initial spaces for every line and nested while loop prints (2*r – 1) space separated stars for rth row of pyramid.

C program to print pyramid pattern using * and loop

/*
* C Program to print full pyramid pattern using *
*/
#include<stdio.h>
#include<conio.h>
int main() {
    int row, space, rows, star=0;
    printf("Enter the number of rows in pyramid\n");
    scanf("%d",&rows);
 
    for(row = 1;row <= rows; row++) {
     /* Printing spaces */
        for(space = 1; space <= rows-row; space++) {
           printf("  ");
        }
        /* Printing stars */
        while(star != (2*row - 1)) {
            printf("* ");
            star++;;
        }
        star=0;
        printf("\n");
    }
    getch();
    return 0;
}

Program Output

Enter the number of rows in pyramid
5 
       *
      * * *
    * * * * *
  * * * * * * *
* * * * * * * * *

C program to print inverted pyramid pattern using * and loop

C program to print inverted pyramid pattern using and loop

/*
* C Program to print full pyramid pattern using *
*/
#include<stdio.h>
#include<conio.h>
int main() {
    int row, space, rows, star=0;
    printf("Enter the number of rows in reverse pyramid\n");
    scanf("%d",&rows);
 
    for(row = rows;row >= 1; row--) {
     /* Printing spaces */
        for(space = 0; space <= rows-row; space++) {
           printf("  ");
        }
        /* Printing stars */
        star = 0;
        while(star != (2*row - 1)) {
            printf("* ");
            star++;
        }
        printf("\n");
    }
    getch();
    return 0;
}

Program Output

Enter the number of rows in reverse pyramid
5 
* * * * * * * * *
  * * * * * * *
    * * * * *
      * * *
        *

C Program to Find Sum of All Upper Triangular Matrix Elements

  • Write a C program to find the sum of all elements in upper triangular matrix.
  • C program to add all elements of upper triangular matrix

Required Knowledge

The main diagonal of a square matrix divides it into two sections, one above the diagonal and the other one is below the diagonal. We have to find the sum of all elements in upper triangular matrix.
A matrix element matrix[i][j] is part of upper triangular matrix if i < j.

C Program to find sum of upper triangular elements of matrix

C Program to Find Sum of All Upper Triangular Matrix Elements

#include <stdio.h>
#include <conio.h>
  
int main(){
    int rows, cols, size, row, col, sum=0;
    int inputMatrix[50][50];
     
    printf("Enter size square matrix\n");
    scanf("%d", &size);
    rows = cols = size;
      
    printf("Enter Matrix of size %dX%d\n", rows, cols);
    /*  Input matrix*/
    for(row = 0; row < rows; row++){
        for(col = 0; col < cols; col++){
            scanf("%d", &inputMatrix[row][col]);
        }
    }
    /* 
     *  Find sum of Upper Triangular Elements 
     */
    for(row = 0; row < rows; row++){
        for(col = 0; col < cols; col++){
            if(row < col){
                /* Upper triangular matrix element*/
                sum += inputMatrix[row][col];
            }
        }
    }
 
    printf("Sum of Upper triangular Matrix Elements\n%d", sum);
     
    getch();
    return 0;
}

Output

Enter size square matrix
3
Enter Matrix of size 3X3
1 2 3
4 5 6
7 8 9
Sum of Upper triangular Matrix Elements
11

C Program to Print All Prime Numbers between 1 to N

C Program to Print All Prime Numbers between 1 to N
  • Write a C program to print all prime numbers between 1 to N using for loop.
  • Wap in C to print prime numbers between 1 to 100.

Required Knowledge

A Prime number is a natural number greater than 1 that is only divisible by either 1 or itself. All numbers other than prime numbers are known as composite numbers. There are infinitely many prime numbers, here is the list of first few prime numbers
2 3 5 7 11 13 17 19 23 29 31 37….

Algorithm to check whether a number is prime number or not

  • Let, N be a positive number.
  • For every number i, between 2 to N/2(2<= i <= N/2) check whether i divides N completely(check If i is a factor of N).
  • if (N % i == 0), then N cannot be a Prime number.
  • If none of the number between 2 to N/2 divides N completely then N is a prime number.

C program to print all prime numbers between 1 to N using for loop

C Program to Print All Prime Numbers between 1 to N

#include<stdio.h>
#include<conio.h>
  
int main(){
  
    int N, i, j, isPrime, n;
     
    printf("To print all prime numbers between 1 to N\n");
    printf("Enter the value of N\n");
    scanf("%d",&N);
  
    /* For every number between 2 to N, check 
    whether it is prime number or not */
    printf("Prime numbers between %d to %d\n", 1, N);
     
    for(i = 2; i <= N; i++){
        isPrime = 0;
        /* Check whether i is prime or not */
        for(j = 2; j <= i/2; j++){
             /* Check If any number between 2 to i/2 divides I 
              completely If yes the i cannot be prime number */
             if(i % j == 0){
                 isPrime = 1;
                 break;
             }
        }
          
        if(isPrime==0 && N!= 1)
            printf("%d ",i);
    }
   getch();
   return 0;
}

Output

To print all prime numbers between 1 to N
Enter the value of N
50
Prime numbers between 1 to 50
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47

Operators in C Programming

Operators in C Programming
  • C programming language supports various operators to perform various operations like logical, mathematical, relational, arithmetic, bitwise operators etc. In this tutorial we will learn about various C operators in brief with sample programs.

An operator in C is a symbol used to perform logical and mathematical operations in a C program.

A statement containing operators and variables is called an Expression. C operators connects constants and variables to form expressions.
For Example

In 2 x (length + breadth);

  • x and + are operators
  • 2 is a constant
  • length and breadth are variables
  • “2x(length + breadth)” is an expression, performing one logical task

C programming language is rich in built in operators. Here is the list of operators supported by C language.

  • Arithmetic Operators
  • Assignment Operators
  • Bitwise Operators
  • Logical Operators
  • Relational Operators
  • Conditional Operator

Special Operators in C

Below are some special operators supported by C language.

Operators Description Example
* It represents a pointer to a variable. int *ptr; ptr is a pointer to variable of data type int.
& Returns address of the variable. &Val will give address of Val variable.
Sizeof() Returns the size of a variable or data type. It is not a function. Sizeof(int); Returns the size of integer data type.

Address of Operator(&)
The & is a unary operator in C which returns the memory address of the passed operand. This is also known as “address of” operator.

A pointer contains the memory address of some object.

Value of Operator(*)
The * is a unary operator which returns the value of object pointer by a pointer variable. It is known as value of operator.

It is also used for declaring pointer variable.

For Example
int A = 100;
int *ptr = &A;
In the first statement, we first declare an integer variable and initialize it with value 100. In second statement, we are declaring a pointer to a variable of type int and initializing it with address of A.

Sizeof Operator
The sizeof is a compile time operator not a standard library function. The sizeof is a unary operator which returns the size of passed variable or data type in bytes.

As we know, that size of basic data types in C is system dependent, So we can use sizeof operator to dynamically determine the size of variable at run time.

C program to show use of Sizeof, & and * Operator

Operators in C Programming

#include<stdio.h>
#include<conio.h>
 
int main()
{
    int A = 10;
    /* Use of & and * Operator */
    int *ptr = &A;
    printf("Value of A is %d\n", *ptr);
     
    /* Use of Sizeof Operator to dynamically determine
       the size of data types and variables */
    printf("Size of variable A is %d\n", sizeof(A));
    printf("Size of an Integer variable is %d\n", sizeof(int));
    printf("Size of long int variable is %d\n", sizeof(long int));
    printf("Size of char variable is %d\n", sizeof(char));
    printf("Size of float variable is %d\n", sizeof(float));
     
    getch();
    return(0);
}

Output

Value of A is 10
Size of variable A is 4
Size of an Integer variable is 4
Size of long int variable is 4
Size of char variable is 1
Size of float variable is 4

Operator Precedence

An expression in C may contains more than one variables and operators. Not every operator in C is of same precedence, some operators are of higher priority than others; for example increment operator(++) is of higher precedence than addition operator(+). Operator precedence defines the sequence of evaluation for operators of an expression, to resolve and ambiguity.
For Example
X = 1 + 2 * 3;

Without any Operator precedence, above expression can be evaluated in two different ways producing two different values for X.

Performing addition before multiplication
X = 3 * 3 = 9

Performing multiplication before addition
X = 1 + 6 = 7

To resolve this confusion, we assign different precedence to different operator. As the precedence of multiplication is more than addition, Correct value of X is 7.

The associativity specifies the operators direction to be evaluated, it may be left to right or right to left.

Below table lists the operators in decreasing order of their precedence.

Operator Associativity
() [] -> . Left to right
! ~ — ++ (type)* & sizeof() Right to left
/ * % Left to right
– + Left to right
<< >> Left to right
< <= > >= Left to right
== != Left to right
& Left to right
^ Left to right
| Left to right
&& Left to right
|| Left to right
?: Right to left
= += -= *= /= %=>>= <<= &= ^= |= Right to left
, Left to right

Points to Remember

  • If two operators of same priority appear at a same level, more priority is given to the operator appearing first.
    For Example :
    X = A*B + C/D;
    In above expression, * and / both have the same priority but * will be evaluated first as it appears first.
  • In any expression containing parentheses, innermost parentheses is given more priority then the outer one and so on.
    For Example :
    X = 2 * (3 + 4);
    X = 2 * 7;      /* + gets evaluated first because of parentheses */
    X = 14;

Header Files in C Programming

Header Files in C Programming

A header file in C programming language is a file with .h extension which contains a set of common function declarations and macro definitions which can be shared across multiple program files. C language provides a set of in build header files which contains commonly used utility functions and macros.

For Example:

  • stdio.h header file contains standard Input and Output functions.
  • string.h header file contains string handling functions.

Types of Header Files in C

  • User defined header files.
  • In-built header files.

#inclide Preprocessor Directives is used to include both system header files and user defined header files in C Program.

Syntax to Include Header File in C Program

#include <Header_file_name>

Above mentioned #include syntax is used to include in-built system header files. It searches given header file in a standard list of directories where all in-built header files are stored. To include in-built header file we use triangular bracket.

#include "Header_file_name"

Above mentioned #include syntax is used to include user-defined system header files. It searches given user defined header file in a current directories where current c program exists. To include user-defined header file we use double quotes.

For Example:

#include <math.h>          // Standard Header File
#include "myHeaderFile.h"    // User Defined Header File

Including a header file in a c program is equivalent to copying the content of the header file in your program. Above statement tells the preprocessor to replace this line with content of math.h header file.

Create Your Own Header File in C

Steps to create your own header file

  1. Open a text editor and type a function definition, like we define a new function in C program.
    int getSquare(int num){
       return num*num;
    }
  2. Save this file with .h extension. Lets assume we saved this file as myMath.h.
  3. Copy myMath.h header file to the same directory where other inbuilt header files are stored.
  4. Compile this file.
  5. To Include your new header file in a c program used #include preprocessor directive.
    #include "myMath.h"
  6. Now you can directly call any function define inside myMath.h header file.

Header Files in C Programming

#include <stdio.h>
#include "myMath.c" 
 
int main(){
    int number;
     
    printf("Enter an Integer\n");
    scanf("%d", number);
    printf("Square of %d is %d\n", number, getSquare(number));
     
    return 0;
}

Conditionally Including a Header File in C Program
Sometimes, we may want to include some header file or select one out of many header if some condition is true. This is useful, when we have system dependent functions and macros defined in separate header files.

#if Condition_One
   # include "headerFile_One.h"
#elif Condition_Two
   # include "headerFile_Two.h"
#elif Condition_Three
   # include "headerFile_Three.h"
  .
  .
#endif

Preprocessor Directives in C Programming

The C Preprocessor is not part of the compiler but it extends the power of C programming language. All preprocessor directives begin with a # symbol.

The preprocessor step comes before compilation of source code and it instruct the compiler to do required pre-processing before actual compilation.

Points to Remember about Preprocessor Directives

  • Preprocessor directives are processed before compilation of source code.
  • All preprocessor directives begin with a # symbol.
  • Preprocessor directives do not ends with semicolon.

C-PreProcessor

Types of Preprocessor Directives

  • Macro Substitution
  • Conditional Compilation
  • File Inclusive

Below is the list of Preprocessor Directives

Directive Description
#include It includes header file inside a C Program.
#define It is substitution macro. It substitute a constant with an expression.
#if It include a block of code depending upon the result of conditional expression.
#else It is complement of #if
#elif #else and #if in one statement. It is similar to else if ladder.
#endif It flags the end of conditional directives like #if, #elif etc.
#undef Undefines a preprocessor macro.
#ifdef Returns true If constant is defined earlier using #define.
#ifndef Returns true If constant is not defined earlier using #define.
#pragma Issues special commands to the compiler.
#error Prints error message on stderr.

#include Preprocessor Directives

#inclide Preprocessor Directives is used to include header file inside C Program. It checks for header file in current directory, If path is not mentioned. To include user defined header file we use double quote instead of using triangular bracket.
For Example

#include           // Standard Header File
#include "myHeaderFile.h"    // User Defined Header File

First line tells the preprocessor to replace this line with content of string.h header file.
Second line tells the preprocessor to get myHeaderFile.h from the current directory and add the content of myHeaderFile.h file.

#define Preprocessor Directives

It is simple substitution macro. It substitute all occurrences of the constant and replace them with a expression.

#define identifier value
  • #define : It is preprocessor directive used for text substitution.
  • identifier : It is an identifier used in program which will be replaced by value.
  • value : This is the value to be substituted for identifier.

For Example

#define PIE 3.141
#define ZERO 0

C Program to show use of #define Preprocessor Directives

Preprocessor Directives in C Programming

#include <stdio.h>
#include <conio.h>
 
#define PI 3.141
 
int main(){
    int radius;
    float circumference;
    printf("Enter the radius of circle\n");
    scanf("%d", &radius);
     
    circumference = 2*PI*radius;
     
    printf("Circumference of Circle = %f", circumference);
     
    getch();
    return 0;
}

Output

Enter the radius of circle
5
Circumference of Circle = 31.410000

#define macro substitution with arguments

#define Preprocessing directive can be used to write macro definitions with parameters.

  • Whenever a macro identifier is encountered, the arguments are substituted by the actual arguments from the c program.
  • No data type defined for macro arguments. You can pass any numeric like int, float etc.
  • Argument macro is not case sensitive.

For Example

#define circumference(r) (2*3.141*(r))

C Program to show Macro Substitution with Arguments

C Program to show Macro Substitution with Arguments

#include <stdio.h>
#include <conio.h>
 
#define circumference(r) (2*3.141*(r))
 
int main(){
    int radius;
    float c;
    printf("Enter the radius of circle\n");
    scanf("%d", &radius);
     
    c = circumference(radius);
     
    printf("Circumference of Circle = %f", c);
     
    getch();
    return 0;
}

Output

Enter the radius of circle
5
Circumference of Circle = 31.410000

#if, #else and #endif Conditional Compilation Preprocessor Directives
The Conditional Compilation Directives allow us to include a block of code based on the result of conditional expression.

#if Condition_Expression
statements;
#else
statements;
#endif

It is similar to if else condition but before compilation.
Condition_Expression must be only constant expression.

C program to show Conditional Compilation using #if, #else and #endif

C program to show Conditional Compilation using

#include <stdio.h>
#include <conio.h>
 
#define COUNT 5
 
void main(){
   #if(COUNT > 1)
       printf("Enter %d numbers\n", COUNT);
   #else
       printf("Enter a number\n");
   #endif
 
   getch();
   return 0;
}

Output

Enter 5 numbers

Predefined Macros in C Language

C Programming language defines a number of macros. Below is the list of some commonly used macros.

Macro Description
NULL Value of a null pointer constant.
EXIT_SUCCESS Value for the exit function to return in case of successful completion of program.
EXIT_FAILURE Value for the exit function to return in case of program termination due to failure.
RAND_MAX Maximum value returned by the rand function.
__FILE__ Contains the current filename as a string.
__LINE__ Contains the current line number as a integer constant.
__DATE__ Contains current date in “MMM DD YYYY” format.
__TIME__ Contains current time in “HH:MM:SS” format.

C Program to print value of Predefined Macros

C Program to print value of Predefined Macros

#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
 
int main(){
   printf("NULL : %d\n", NULL );
   printf("EXIT_SUCCESS : %d\n", EXIT_SUCCESS );
   printf("EXIT_FAILURE : %d\n", EXIT_FAILURE );
   printf("RAND_MAX : %d\n", RAND_MAX );
   printf("File Name : %s\n", __FILE__ );
   printf("DATE : %s\n", __DATE__ );
   printf("Line : %d\n", __LINE__ );
 
   getch();
   return 0;
}

Output

NULL : 0
EXIT_SUCCESS : 0
EXIT_FAILURE : 1
RAND_MAX : 32767
File Name : PreProcessorMacro.c
DATE : Jan 27 2015
Line : 12

C Program to Swap Two Strings

C Program to Swap Two Strings

Write a program in c to swap the content of two strings

  • Write a C program to swap two strings using strcpy.
  • C Program to swap two strings without using extra memory

Given two strings, we have to swap the content of strings. For example, If firstString = “Apple” and secondString = “Banana” then after swapping firstString = “Banana” and secondString = “Apple”. We can either use strcpy to swap two strings using a temporary string or define user defined function to swap two strings.

C program to swap strings using strcpy function

In this program, we first take two string as input from user using gets function. We use a temporary character array tempString to temporarily store a string while swapping content. This program call strcpy function three times.

Algorithm to swap two strings using strcpy

This algorithm of swapping string is similar to the algorithm of swapping integers using a temporary variable. Let firstString and secondString are two input strings and tempString is a temporary string whose size is equal to or more than the size of firstString.

  • Copy firstString’s content into tempString using strcpy.
  • Copy secondString’s content into firstString using strcpy.
  • Copy tempString’s content into secondString.

C Program to Swap Two Strings

/*
* C Program to swap two strings
*/
#include <stdio.h>
#include <conio.h>
#include <string.h>
 
int main(){
    char firstString[100], secondString[100], tempString[100];
     
    printf("Enter first String \n");
    gets(firstString);
    printf("Enter second String \n");
    gets(secondString);
    /* Swap strings using a temporary array */
    /* Copy firstString into tempString */   
    strcpy(tempString, firstString);
    /* Copy secondString into firstString */
    strcpy(firstString, secondString);
    /* Copy tempString back to secondString*/
    strcpy(secondString, tempString);
    printf("After Swapping\n");
    printf("First String: %s\nSecond String: %s", firstString, secondString);
 
    getch();
    return 0;
}

Program Output

Enter first String
Apple
Enter second String
Banana
After Swapping
First String: Banana
Second String: Apple

C Program to swap two strings without using extra memory

In this program, we don’t use any temporary character array for swapping. We swap the characters of both input strings one by one from index 0 till end of the smaller string and then copy remaining characters of the bigger string.

C Program to swap two strings without using extra memory

/*
* C Program to swap two strings using function
*/
#include <stdio.h>
#include <conio.h>
 
void swapStrings(char *firstString, char *secondString);
int main(){
    char firstString[100], secondString[100];
    printf("Enter first String \n");
    gets(firstString);
    printf("Enter second String \n");
    gets(secondString);
     
    swapStrings(firstString, secondString);
    printf("After Swapping\n");
    printf("First String: %s\nSecond String: %s", firstString, secondString);
 
    getch();
    return 0;
}
 
/*
 * Swaps two passed strings 
 */
void swapStrings(char *firstString, char *secondString){
    if(firstString == NULL || secondString == NULL)
        return;
    /* Initialize it to first character index of both string */
    int firstStringIndex = 0, secondStringIndex = 0;
    char temp;
    /* Starting from index 0, keep on swapping characters 
     using a temporay char variable temp*/
    while(firstString[firstStringIndex] != '\0' && secondString[secondStringIndex] != '\0') {
        temp = firstString[firstStringIndex];
        firstString[firstStringIndex] = secondString[secondStringIndex];
        secondString[secondStringIndex] = temp;
        firstStringIndex++;
        secondStringIndex++;
    }
    if(firstString[firstStringIndex] == '\0'){
        /* If firstString ends before secondString, copy the remaining 
          characters of secondString into firstString */
        firstString[firstStringIndex++] = secondString[secondStringIndex];
        secondString[secondStringIndex++] = '\0';
        while(secondString[secondStringIndex] != '\0'){
            firstString[firstStringIndex++] = secondString[secondStringIndex++];
        }
        firstString[firstStringIndex] = '\0';
    } else {
        /* If secondString ends before firstString, copy the remaining 
          characters of firstString into secondString */
        secondString[secondStringIndex++] = firstString[firstStringIndex];
        firstString[firstStringIndex++] = '\0';
        while(firstString[firstStringIndex] != '\0'){
            secondString[secondStringIndex++] = firstString[firstStringIndex++];
        }
        secondString[secondStringIndex] = '\0';
    }
}
</conio.h></stdio.h>

Program Output

Enter first String
TechCrashCourse
Enter second String
CProgramming
After Swapping
First String: CProgramming
Second String: TechCrashCourse