Write a program that reads an integer N, asks the user to enter N characters, calculate the length of the longest ascending sequence of characters and the position of its first character.

Example of execution:
Enter a positive integer: 11
Enter 11 characters without spaces:
AecDklnpacD
The longest sequence is of 5 characters, it begins at position 4


Difficulty level
Video recording
This exercise is mostly suitable for students
Solution provided by Dr. Rami El Baida using fflush(stdin) and reduced number of variables.



#include<stdio.h>
main()
{
	int n,i,longseq,pos,poslong;
	char c,old;
	printf("Enter a positive integer: ");
	scanf("%d",&n);
	printf("Enter %d characters: ",n);
	fflush(stdin);
	c=getchar();
	longseq=-1;
	pos=1;
	old=c;
	for(i=2;i<=n;i++)
	{
		c=getchar();
		if(c<old)
		{
			if(i-pos>longseq)
			{
				longseq=i-pos;
				poslong=pos;
			}
			pos=i;
		}
		old=c;
	}
	printf("The longest sequence is of %d characters\n",longseq);
	printf("It begins at the position %d\n",poslong);
}







#include<stdio.h>
#include<limits.h>
int main()
{
	int N, i;
	char c ,old;
	
	int size_ls = INT_MIN, position_ls = -1; 
	int current_size, current_position;
	
	do{
	    printf("Enter N: ");
	    scanf("%d\n",&N);   // pay attention here
	}while(N<1);
	
	
	
	printf("Enter %d characters without spaces: ", N);
	scanf("%c",&c);
	current_position=1;
	current_size=1;
	old = c ;
	
	for(i=2;i<=N;i++)
	{
	    scanf("%c",&c);
	    if(c<old)
	    {
	        if(current_size > size_ls)
	        {
	             size_ls = current_size ;
	             position_ls = current_position;
	        }
	        current_position=i;
	        current_size=1;
	    }
	    else
	    {
	        current_size++;
	    }
	    old=c;
	}
	
	if(current_size > size_ls)
	 {
	    size_ls = current_size ;
	    position_ls = current_position;
	 }
	
	printf("The longest sequence is of %d characters, it begins at  position %d.\n",size_ls,position_ls);

	return 0;
}

Back to the list of exercises
Looking for a more challenging exercise, try this one !!
Sorting using the counting sort algorithm