
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
C Program to Work on Statements Using Functions and Loops
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]='
'; 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!='
';i++) msg[i]=charcter; if(charcter='
'){ 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:
"); while((charcter=readtext())>0){ if(charcter>length){ count=0; a=0; while(a<charcter){ if(msg[a]==' ') b=a; if(count==length){ msg[b]='
'; 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!='
';i++) msg[i]=charcter; if(charcter='
'){ 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
Advertisements