w3resource

C Programming: Length of longest common subsequence of two strings

C String: Exercise-41 with Solution

Write a C programming to calculate the length of longest common subsequence of two given strings. The strings consist of alphabetical characters.

Sample Data:

("abcdkiou", "cabsdf") -> 3
("pqrjad", "qr") -> 2

Sample Solution:

C Code:

#include <stdio.h>
#include <string.h>

#define max(x,y)((x)>(y)?(x):(y))
int result[200][200];
char str1[200], str2[200];
int main(){
	printf("Input the first string: ");
	scanf("%s",str1);
	printf("\nInput the second string: ");
	scanf("%s",str2);
	int n=strlen(str1);
	int m=strlen(str2);
	for(int i=1;i<=n;i++)for(int j=1;j<=m;j++)
	  {
	 	if(str1[i-1]==str2[j-1])
	      result[i][j]=result[i-1][j-1]+1;
		else 
		  result[i][j]=max(result[i-1][j],result[i][j-1]);		
      }
      printf("\nLength of longest common subsequence of said strings: %d\n",result[n][m]);
}

Sample Output:

Input the first string: 
Input the second string: 
Length of longest common subsequence of said strings: 3

Flowchart :

Flowchart: Length of longest common subsequence of two strings.

C Programming Code Editor:

Improve this sample solution and post your code through Disqus.

Previous C Programming Exercise: Replace every lowercase letter with the same uppercase.
Next C Programming Exercise: C Date Time Exercises Home

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Share this Tutorial / Exercise on : Facebook and Twitter

C Programming: Tips of the Day

What's an object file in C?

An object file is the real output from the compilation phase. It's mostly machine code, but has info that allows a linker to see what symbols are in it as well as symbols it requires in order to work. (For reference, "symbols" are basically names of global objects, functions, etc.)

A linker takes all these object files and combines them to form one executable (assuming that it can, i.e.: that there aren't any duplicate or undefined symbols). A lot of compilers will do this for you (read: they run the linker on their own) if you don't tell them to "just compile" using command-line options. (-c is a common "just compile; don't link" option.)

Ref : https://bit.ly/3CbzF8M