How to concatenate two strings in C++

This C program is used to concatenate strings by using strcat() function.

Program to Concatenate Strings using strcat()

Program:

#include <stdio.h> #include <string.h> int main() { char a[100], b[100]; printf("Enter the first string\n"); gets(a); printf("Enter the second string\n"); gets(b); strcat(a,b); printf("String obtained on concatenation is %s\n",a); return 0; }

Program Output:

How to concatenate two strings in C++

Explanation:

This program is used to concatenate two given strings as a single set of strings using the function strcat(). So first of all, you have to include the stdio header file using the "include" preceding # which tells that the header file needs to be process before compilation, hence named preprocessor directive. Also, you have to include the string.h header file. The string.h header classifies one variable type, one macro, and various functions to manipulate arrays of characters within your program.

Then you have to define the main() function and it has been declared as an int as it is going to return an integer type value at the end of the program. The inside the main() function, you have to take two character arrays name as a[] and b[] having 100 consecutive memory location. You have to use the printf() function for displaying the message - "Enter the first string" to the screen. The statement gets(a); will fetch a set of characters the form of a string and store them in the array a[]. Similarly another printf for displaying the second message - "Enter the second string" and so the second string will also get fetched from the keyboard using gets() and stored in character array b[]. Then comes the use of strcat() which is abbreviated as string concatenation, and is having syntax as: char *strcat(dest, src), where 'dest' defines the destination array (here in this program 'a'), which should contain a string and should be larger for containing the concatenated resulting string.

'src' also contains a string (here in this program 'b') for appending and should not overlap the dest string. And lastly the return 0; statement is used to return an integer type value back to main().

How to concatenate two strings in C++
report this ad


Page 2

In this example C program, a user-defined function swaps the values of two variables. It uses a temporary variable to replace the values of variables from each other and print the output to the screen.

Example:

#include <stdio.h> void swap (int *n1, int *n2) { int temp; temp = *n2; *n2 = *n1; *n1 = temp; } void main () { /* Declaration of variables used within this program. */ int num1, num2; /* Take input from the user and save it to the first variable. */ printf("Enter first number:\n"); scanf ("%d", &num1); /* Take input from the user and save it to the second variable. */ printf("Enter second number:\n"); scanf ("%d", &num2); /* Printing the use input before swapping. */ printf("\nBefore Swapping\n"); printf("First number: %d\n", num1); printf("Second number: %d\n\n", num2); /* Swapping the variables. */ swap (&num1, &num2); /* Printing the variables after the swapping. */ printf("\nAfter Swapping\n"); printf("First number: %d\n", num1); printf("Second number: %d\n\n", num2); }

Program Output:

Enter first number: 10 Enter second number: 5 Before Swapping First number: 10 Second number: 5 After Swapping First number: 5 Second number: 10
How to concatenate two strings in C++
report this ad


Page 3

C exit() function is a standard library function defined in the <stdlib.h> header file used to terminate C program execution immediately with an error code.

Syntax:

void exit(int status)

Parameters:
Value Description
EXIT_SUCCESS or 0 Successful
EXIT_FAILURE Unsuccessful

Use of the exit() Function in C with Example

Sometimes some situations arise during the execution of a C program where we need to end the further execution process according to the situation. For example, if a C program opens a file and that file doesn't open for some reason, it's a possible error; Here, there is no point in executing this program further. It must end with an error message by calling the exit() function. Let's see the code snippet of a practical use example to understand the exit function in C:

Example C Program:
#include <stdio.h> #include <stdlib.h> void main() { FILE *fpointer = fopen("NotFoundFile.txt","r"); if (fpointer == NULL) { fprintf(stderr, "File not found, failed to open it.\n"); exit(EXIT_FAILURE); } /* If the file is found the code execution will continue. */ fclose(fpointer); printf("Success\n"); }

Program Output:

File not found, failed to open it.
How to concatenate two strings in C++
report this ad


Page 4

In this C programming example, a C program is demonstrated that performs the task of finding and printing the average number of characters per line of text entered by the user.

Example C Program:
#include <stdio.h> int line(void); /* Define function prototype. */ void main() { /* Variable Declaration and Initialization. */ int n, c = 0, sum = 0; float avg; printf("Enter some text per line below:\n"); /* Reading the text by line and updating the cumulative counters. */ while ((n = line()) > 0) { sum += n; ++c; } avg = (float) sum / c; printf("\nAverage number of characters per line : %5.2f", avg); } /* Function Definition - User Defined Function */ int line(void) /* Reading a line of text and counting the number of characters. */ { char l[80]; int c = 0; while ((l[c] = getchar()) != '\n') ++c; return (c); }

Program Output:

Enter some text per line below: Welcome to W3schools. Here you will have an excellent learning experience. Average number of characters per line : 36.50
How to concatenate two strings in C++
report this ad


Page 5

This C program code will insert an element into an array, and it does not mean increasing size of the array.

For example consider an array n[10] having four elements: n[0] = 1, n[1] = 2, n[2] = 3 and n[3] = 4 And suppose you want to insert a new value 60 at first position of array. i.e. n[0] = 60, so we have to move elements one step below so after insertion

n[1] = 1 which was n[0] initially, n[2] = 2, n[3] = 3 and n[4] = 4.

Program:

#include <stdio.h> int main() { int array[50], position, c, n, value; printf("Enter number of elements in the array\n"); scanf("%d", &n); printf("Enter %d elements\n", n); for (c = 0; c < n; c++) scanf("%d", &array[c]); printf("Please enter the location where you want to insert an new element\n"); scanf("%d", &position); printf("Please enter the value\n"); scanf("%d", &value); for (c = n - 1; c >= position - 1; c--) array[c+1] = array[c]; array[position-1] = value; printf("Resultant array is\n"); for (c = 0; c <= n; c++) printf("%d\n", array[c]); return 0; }

Program Output:

How to concatenate two strings in C++
How to concatenate two strings in C++
report this ad


Page 6

C program to merge two arrays into one array, Arrays are assumed to be sorted in ascending order.
Enter the two short sorted arrays and combine them to obtain a large array.

Program:

#include <stdio.h> void merge(int [], int, int [], int, int []); int main() { int a[100], b[100], m, n, c, sorted[200]; printf("Input number of elements in first array\n"); scanf("%d", &m); printf("Input %d integers\n", m); for (c = 0; c < m; c++) { scanf("%d", &a[c]); } printf("Input number of elements in second array\n"); scanf("%d", &n); printf("Input %d integers\n", n); for (c = 0; c < n; c++) { scanf("%d", &b[c]); } merge(a, m, b, n, sorted); printf("Sorted array:\n"); for (c = 0; c < m + n; c++) { printf("%d\n", sorted[c]); } return 0; } void merge(int a[], int m, int b[], int n, int sorted[]) { int i, j, k; j = k = 0; for (i = 0; i < m + n;) { if (j < m && k < n) { if (a[j] < b[k]) { sorted[i] = a[j]; j++; } else { sorted[i] = b[k]; k++; } i++; } else if (j == m) { for (; i < m + n;) { sorted[i] = b[k]; k++; i++; } } else { for (; i < m + n;) { sorted[i] = a[j]; j++; i++; } } } }

Program Output:

How to concatenate two strings in C++

If arrays are not sorted so you can sort them first and then use the above merge function, another method is to merge them and then sort the array. Two small arrays sorting will take less time than sorting a large array. Merging two sorted arrays is used in merge sort algorithm.

How to concatenate two strings in C++
report this ad


Page 7

This C program will show you how to sort a string in alphabetical order.

Program:

#include <stdio.h> #include <stdlib.h> #include <string.h> void sort_string(char*); int main() { char string[100]; printf("Enter some text\n"); gets(string); sort_string(string); printf("%s\n", string); return 0; } void sort_string(char *s) { int c, d = 0, length; char *pointer, *result, ch; length = strlen(s); result = (char*)malloc(length+1); pointer = s; for ( ch = 'a' ; ch <= 'z' ; ch++ ) { for ( c = 0 ; c < length ; c++ ) { if ( *pointer == ch ) { *(result+d) = *pointer; d++; } pointer++; } pointer = s; } *(result+d) = '\0'; strcpy(s, result); free(result); }

Program Output:

How to concatenate two strings in C++

Explanation:

This program will demonstrate you how to sort a string in the alphabet. So first of all, you have to include the stdio header file using the "include" preceding # which tells that the header file needs to be process before compilation, hence named preprocessor directive. Also, you have to include the string.h header file. The string.h header classifies one variable type, one macro, and various functions to manipulate arrays of characters within your program.

Then you have to define the main() function and it has been declared as an int as it is going to return an integer type value at the end of the program. Then inside main() you have to declare a character array name 'string' of size 100. Then you have to use printf() to display a message - "Enter some text". Then the gets() function will fetch the input string from the user.

Then the user-defined function sort_string() is called which is having 'string' as a parameter. Then the next printf() display the value of the string. Now inside the user-defined function, the definition will contain 3 integer type variables - c, d, length, and initialize d as 0. Then a pointer type character variable *pointer,  *result and a character variable 'ch'. The strlen() will count the length of the string and store the value in the form of integer to the variable length. result = (char*)malloc(length+1); statement will allocate memory for the variable 'result' and the value of 's' gets stored in 'pointer'.

How to concatenate two strings in C++
report this ad


Page 8

This program find maximum or largest element present in an array. It also prints the location or index at which maximum element occurs in array.

Program:

#include <stdio.h> int main() { int array[100], maximum, size, c, location = 1; printf("Enter the number of elements in array\n"); scanf("%d", &size); printf("Enter %d integers\n", size); for (c = 0; c < size; c++) scanf("%d", &array[c]); maximum = array[0]; for (c = 1; c < size; c++) { if (array[c] > maximum) { maximum = array[c]; location = c+1; } } printf("Maximum element is present at location %d and it's value is %d.\n", location, maximum); return 0; }

Program Output:

How to concatenate two strings in C++

Same C program code using pointers

Example:

#include <stdio.h> int main() { long array[100], *maximum, size, c, location = 1; printf("Enter the number of elements in array\n"); scanf("%ld", &size); printf("Enter %ld integers\n", size); for ( c = 0 ; c < size ; c++ ) scanf("%ld", &array[c]); maximum = array; *maximum = *array; for (c = 1; c < size; c++) { if (*(array+c) > *maximum) { *maximum = *(array+c); location = c+1; } } printf("Maximum element found at location %ld and it's value is %ld.\n", location, *maximum); return 0; }

The complexity of above code is O(n) as the time used depends on the size of input array or in other words time to find maximum increases linearly as array size grows.

How to concatenate two strings in C++
report this ad


Page 9

In C programming strcat() function is used to Concatenate strings but in this program we have concatenate string without using this function.

Program to Concatenate Strings without using strcat()

Program:

#include<stdio.h> void main(void) { char str1[25],str2[25]; int i=0,j=0; printf("\nEnter First String:"); gets(str1); printf("\nEnter Second String:"); gets(str2); while(str1[i]!='\0') i++; while(str2[j]!='\0') { str1[i]=str2[j]; j++; i++; } str1[i]='\0'; printf("\nConcatenated String is %s",str1); }

Explanation:

This program is used to concatenate strings without using strcat() function. So first of all, you have to include the stdio header file using the "include" preceding # which tells that the header file needs to be process before compilation, hence named preprocessor directive.

Then you have to define the main() function and it has been declared nothing so by default it is integer heche returns an integer. The inside the main() function, you have to declare two character array name str1 and str2 having size 25 for both. Then you have o declare two integer variables j and j and initialized them with value 0. Then the printf() is used to display a message "Enter First String:". Followed by printf() you have to use the gets() to take the 1st string from the user. Similarly, another printf() is used to display the message "Enter Second String:" and using gets() takes the value of str2 from the user.

Now a while loop is implemented which checks whether str1[i] does not equal to '\0' or not, and increments the value of i by 1. Another while is used after this which checks whether str2[i] not equals to '\0', if the condition becomes true, the loop will get executed and where it is given the value of str2[j] gets initialized to str1[i]; Then increments the value of i and j by 1. And finally, initializes the str1[i] as '\0' i.e. null character terminator. At last printf() is used to display the value of the concatenated string.

How to concatenate two strings in C++
report this ad


Page 10

This C program is used to compare two strings without using strcmp function.

Program:

#include<stdio.h> #include<string.h> int cmpstr(char s1[10], char s2[10]); int main() { char arr1[10] = "Nodalo"; char arr2[10] = "nodalo"; printf(" %d", cmpstr(arr1, arr2)); //cmpstr() is equivalent of strcmp() return 0; }/ /s1, s2 are strings to be compared int cmpstr(char s1[10], char s2[10]) { //strlen function returns the length of argument string passed int i = strlen(s1); int k = strlen(s2); int bigger; if (i < k) { bigger = k; } else if (i > k) { bigger = i; } else { bigger = i; } //loops 'bigger' times for (i = 0; i < bigger; i++) { //if ascii values of characters s1[i], s2[i] are equal do nothing if (s1[i] == s2[i]) { } //else return the ascii difference else { return (s1[i] - s2[i]); } } //return 0 when both strings are same //This statement is executed only when both strings are equal return (0); }

Program Output:

-32

Explanation:

cmpstr() is a function that illustrates C standard function strcmp(). Strings to be compared are sent as arguments to cmpstr().

Each character in string1 is compared to its corresponding character in string2. Once the loop encounters a differing character in the strings, it would return the ASCII difference of the different characters and exit.

How to concatenate two strings in C++
report this ad


Page 11

C program to find smallest element present in an array. It also prints the location or index at which minimum element occurs in array.

Program:

#include <stdio.h> int main() { int array[100], minimum, size, c, location = 1; printf("Enter the number of elements in array\n"); scanf("%d",&size); printf("Enter %d integers\n", size); for ( c = 0 ; c < size ; c++ ) scanf("%d", &array[c]); minimum = array[0]; for ( c = 1 ; c < size ; c++ ) { if ( array[c] < minimum ) { minimum = array[c]; location = c+1; } } printf("Minimum element is present at location %d and it's value is %d.\n", location, minimum); return 0; }

Program Output:

How to concatenate two strings in C++

Same C program using pointers

Program:

#include <stdio.h> int main() { int array[100], *minimum, size, c, location = 1; printf("Enter the number of elements in array\n"); scanf("%d",&size); printf("Enter %d integers\n", size); for ( c = 0 ; c < size ; c++ ) scanf("%d", &array[c]); minimum = array; *minimum = *array; for ( c = 1 ; c < size ; c++ ) { if ( *(array+c) < *minimum ) { *minimum = *(array+c); location = c+1; } } printf("Minimum element found at location %d and it's value is %d.\n", location, *minimum); return 0; }

The algorithm first assumes the first element as a minimum, and then compare it with other elements if an element it is smaller than the new minimum and the entire array is scanned until the process is repeated.

How to concatenate two strings in C++
report this ad


Page 12

This program reverses the array elements.

For example if a is an array of integers with three elements such that

a[0] = 1

a[1] = 2

a[2] = 3

Then on reversing the array will be

a[0] = 3

a[1] = 2

a[0] = 1

Given below is the c code to reverse an array.

Example:

#include <stdio.h> int main() { int n, c, d, a[100], b[100]; printf("Enter the number of elements in array\n"); scanf("%d", &n); printf("Enter the array elements\n"); for (c = 0; c < n ; c++) scanf("%d", &a[c]); /* * Copying elements into array b starting from end of array a */ for (c = n - 1, d = 0; c >= 0; c--, d++) b[d] = a[c]; /* * Copying reversed array into original. * Here we are modifying original array, this is optional. */ for (c = 0; c < n; c++) a[c] = b[c]; printf("Reverse array is\n"); for (c = 0; c < n; c++) printf("%d\n", a[c]); return 0; }

Reverse array by swapping (without using additional memory)

Example:

#include <stdio.h> int main() { int array[100], n, c, t, end; scanf("%d", &n); end = n - 1; for (c = 0; c < n; c++) { scanf("%d", &array[c]); } for (c = 0; c < n/2; c++) { t = array[c]; array[c] = array[end]; array[end] = t; end--; } printf("Reversed array elements are:\n"); for (c = 0; c < n; c++) { printf("%d\n", array[c]); } return 0; }

C program to reverse an array using pointers

Example:

#include <stdio.h> #include <stdlib.h> void reverse_array(int*, int); int main() { int n, c, *pointer; scanf("%d",&n); pointer = (int*)malloc(sizeof(int)*n); if( pointer == NULL ) exit(EXIT_FAILURE); for ( c = 0 ; c < n ; c++ ) scanf("%d",(pointer+c)); reverse_array(pointer, n); printf("Original array on reversal is\n"); for ( c = 0 ; c < n ; c++ ) printf("%d\n",*(pointer+c)); free(pointer); return 0; } void reverse_array(int *pointer, int n) { int *s, c, d; s = (int*)malloc(sizeof(int)*n); if( s == NULL ) exit(EXIT_FAILURE); for ( c = n - 1, d = 0 ; c >= 0 ; c--, d++ ) *(s+d) = *(pointer+c); for ( c = 0 ; c < n ; c++ ) *(pointer+c) = *(s+c); free(s); }

Array passed to function and a new array is created, contents of passed array (in reverse order) are copied into it and finally contents of new array are copied into array passed to function.

How to concatenate two strings in C++
report this ad


Page 13

Palindrome is a string, which when read in both forward and backward way is same.

Example:

radar, madam, pop, lol, etc.

Palindrome String Check Program in C

Example:

#include <stdio.h> #include <string.h> int main(){ char string1[20]; int i, length; int flag = 0; printf("Enter a string:"); scanf("%s", string1); length = strlen(string1); for(i=0;i < length ;i++){ if(string1[i] != string1[length-i-1]){ flag = 1; break; } } if (flag) { printf("%s is not a palindrome", string1); } else { printf("%s is a palindrome", string1); } return 0; }

Program Output:

How to concatenate two strings in C++

Explanation:

To check if a string is a palindrome or not, a string needs to be compared with the reverse of itself.

Consider a palindrome string: radar,

---------------------------
index: 0 1 2 3 4

value: r a d a r
---------------------------

How to concatenate two strings in C++

To compare it with the reverse of itself, the following logic is used:

  1. 0th character in the char array, string1 is same as 4th character in the same string.
  2. 1st character is same as 3rd character.
  3. 2nd character is same as 2nd character.
  4. . . . .
  5. ith character is same as 'length-i-1'th character.
  6. If any one of the above condition fails, flag is set to true(1), which implies that the string is not a palindrome.
  7. By default, the value of flag is false(0). Hence, if all the conditions are satisfied, the string is a palindrome.
How to concatenate two strings in C++
report this ad


Page 14

#include<stdio.h> int main() { int number; printf("Please enter an integer: \n"); scanf("%d", &number); printf("You enter the integer %d\n", number); return 0; }


Page 15

/* insertion sort ascending order */ #include <stdio.h> int main() { int n, array[1000], c, d, t; printf("Enter number of elements\n"); scanf("%d", &n); printf("Enter %d integers\n", n); for (c = 0; c < n; c++) { scanf("%d", &array[c]); } for (c = 1 ; c <= n - 1; c++) { d = c; while ( d > 0 && array[d] < array[d-1]) { t = array[d]; array[d] = array[d-1]; array[d-1] = t; d--; } } printf("Sorted list in ascending order:\n"); for (c = 0; c <= n - 1; c++) { printf("%d\n", array[c]); } return 0; }


Page 16

#include <stdio.h> int main() { int array[100], position, c, n; printf("Enter number of elements in array\n"); scanf("%d", &n); printf("Enter %d elements\n", n); for ( c = 0 ; c < n ; c++ ) scanf("%d", &array[c]); printf("Enter the location where you wish to delete element\n"); scanf("%d", &position); if ( position >= n+1 ) printf("Deletion not possible.\n"); else { for ( c = position - 1 ; c < n - 1 ; c++ ) array[c] = array[c+1]; printf("Resultant array is\n"); for( c = 0 ; c < n - 1 ; c++ ) printf("%d\n", array[c]); } return 0; }


Page 17

C program to perform basic arithmetic operations of two numbers. Numbers are assumed to be integers and will be entered by the user.

#include <stdio.h> int main() { int first, second, add, subtract, multiply; float divide; printf("Enter two integers\n"); scanf("%d%d", &first, &second); add = first + second; subtract = first - second; multiply = first * second; divide = first / (float)second; //typecasting printf("Sum = %d\n",add); printf("Difference = %d\n",subtract); printf("Multiplication = %d\n",multiply); printf("Division = %.2f\n",divide); return 0; }

When we divide two integers in C language we get integer result for example 5/2 evaluates to 2. As a general rule integer/integer = integer and float/integer = float or integer/float = float. So we convert denominator to float in our program, you may also write float in numerator. This is known as explicit conversion typecasting.

How to concatenate two strings in C++
report this ad


Page 18

This C program reverse the number entered by the user, and then prints the reversed number on the screen.

For example if user enter 423 as input then 324 is printed as output. We use modulus(%) operator in program to obtain the digits of a number. To invert number look at it and write it from opposite direction or the output of code is a number obtained by writing original number from right to left. To reverse or invert large numbers use long data type or long long data type if your compiler supports it, if you still have large numbers then use strings or other data structure.

Example:

#include<stdio.h> int main() { int n, reverse = 0; printf("Enter a number to reverse\n"); scanf("%d",&n); while (n != 0) { reverse = reverse * 10; reverse = reverse + n%10; n = n/10; } printf("Reverse of entered number is = %d\n", reverse); return 0; }

Program Output:

How to concatenate two strings in C++
How to concatenate two strings in C++
report this ad


Page 19

This program performs addition of two numbers using pointers.

In this program I have used two integer variables x, y and two pointer variables p and q.

Firstly I have assign the addresses of x and y to p and q respectively and then assign the sum of x and y to variable sum. & is address of operator and * is value at address operator.

Example:

#include <stdio.h> int main() { int first, second, *p, *q, sum; printf("Enter two integers to add\n"); scanf("%d%d", &first, &second); p = &first; q = &second; sum = *p + *q; printf("Sum of entered numbers = %d\n",sum); return 0; }

Program Output:

How to concatenate two strings in C++
How to concatenate two strings in C++
report this ad


Page 20

This C example program performs simple mathematical calculations to find the area and perimeter of a circle. The perimeter of a circle is equal to 2*PI*Radious, and its area equals to PI*Radius2. Here PI refers to the value of pi(π).

Example C Program:
#include <stdio.h> #define PI 3.14f /* Define the value of pie */ void main() { /* Variable Declaration. */ float radius, perimeter, area; /* Taking input of the radious of the circle from the user */ printf("Enter radius of the Circle:\n"); scanf("%f", & radius); /* Calculating perimeter of the circle */ perimeter = 2 * PI * radius; printf("Perimeter of the circle: %0.4f\n", perimeter); /* Calculating area of the circle */ area = PI * radius * radius; printf("Area of circle: %0.4f\n", area); }

Program Output:

Enter radius of the Circle: 20 Perimeter of the circle: 125.6000 Area of circle: 1256.0000
How to concatenate two strings in C++
report this ad


Page 21

This C example program performs simple mathematical calculations to find the area and perimeter of a square. The perimeter of a square is equal to 4 times the length of any of its sides, and its area is equal to multiplied by the length of any side.

Example C Program:
#include <stdio.h> void main() { /* Variable Declaration. */ float side, perimeter, area; /* Taking user input */ printf("Enter the length of the side of the square:\n"); scanf("%f", & side); /* Calculate Perimeter of the square */ perimeter = 4 * side; printf("Perimeter of the Square : %0.4f\n", perimeter); /* Calculate Area of the square */ area = side * side; printf("Area of the square : %0.4f\n", area); }

Program Output:

Enter the length of the side of the square: 10 Perimeter of the Square : 40.0000 Area of the square : 100.0000
How to concatenate two strings in C++
report this ad


Page 22

This C program checks the number given by the user whether it is a palindrome or not. It reverses the number using a while loop and matches the reversed number with the user input using the decision statement.

What Is Palindrome Number

A palindrome number is a sequence of numbers that can be read alike from the front and back in the same sequence.

Example C Program:
#include <stdio.h> void main() { /* Variable Declaration and Initialization. */ int input, reverse = 0, rem, temp; /* taking user input */ printf("Please enter an integer number:"); scanf("%d", & input); temp = input; /* Reverse the number using while loop */ while (temp != 0) { rem = temp % 10; reverse = reverse * 10 + rem; temp /= 10; } /* Check the reversed number with the user input */ if (reverse == input) printf("%d is a palindrome number.", input); else printf("%d is not a palindrome number.", input); }

Program Output:

Please enter an integer number:: 1331 1331 is a palindrome number
How to concatenate two strings in C++
report this ad