Write a C program to work on statements using functions and loops

R ProgrammingServer Side ProgrammingProgramming

Problem

How to print the long lines into two or more short lines based on specified length in the program using C Language?

Solution

Let’s write a code to read a long line and print into two or more short lines according to the mentioned size in the program.

The built in functions that we take in this program readline() function, is used to store text in array and returns the size of line.

The logic we use to read a short sentence is explained below −

while((charcter=readtext())>0){
   if(charcter>length){
      count=0;
      a=0;
      while(a<charcter){
         if(msg[a]==' ')
            b=a;
         if(count==length){
            msg[b]='\n';
            count=0;
         }
         count++;
         a++;
      }
   }
   printf("%s",msg);
}

The logic we use to read a long sentence is explained below −

for(i=0;i<MAX-1 && (charcter=getchar())!=EOF && charcter!='\n';i++)
msg[i]=charcter;
if(charcter='\n'){
   msg[i]=charcter;
   ++i;
}
msg[i]='\0';
return i;

Program

Following is the C program to work on statements by using the functions and loops −

#include<stdio.h>
#define MAX 100
int readtext(void);
char msg[MAX];
const int length=30;
int main(){
   int a,b,count,charcter;
   printf("enter the statement:\n");
   while((charcter=readtext())>0){
      if(charcter>length){
         count=0;
         a=0;
         while(a<charcter){
            if(msg[a]==' ')
               b=a;
            if(count==length){
               msg[b]='\n';
               count=0;
            }
            count++;
            a++;
         }
      }
      printf("%s",msg);
   }
   return 0;
}
int readtext(void){
   extern char msg[];
   int charcter,i;
   for(i=0;i<MAX-1 && (charcter=getchar())!=EOF && charcter!='\n';i++)
      msg[i]=charcter;
      if(charcter='\n'){
         msg[i]=charcter;
         ++i;
      }
      msg[i]='\0';
   return i;
}

Output

The output is stated below −

enter the statement:
Hi Welcome to TutorialsPoint .It is one of the biggest platform where you can find all types of study materials with a very good and validate content,students can get there solutions in this platform
Hi Welcome to TutorialsPoint
.It is one of the biggest
platform where you can find all
types of study
materials with a very good
and validate content,students
can get there solutions in
this platform
raja
Published on 10-Mar-2021 09:36:53
Advertisements