Program to print X characters up to X in C++

In this tutorial we will learn how to print X characters up to X in a word.

The program accepts a word and an integer X.

The program finds the length of the word and checks it’s divisibility with X .

If the divisibility is satisfied the program splits the X characters up to X.

How to find the length of the string?

The length of the string can be found using the function strlen().



The strlen() function can be used only when the header file #include<string.h> is included.

How to get the input values?

char str[1000];
cin>>str;
int X;
cin>>X;

In the above code,

The word and the integer X are obtained.

The length of the string is calculated and if it is divisible by X , it starts spliting the word into X characters

INPUT 1:
Enter the Word to be split:

codespeedy

Enter the value of X:

2

C++ code to print X characters up to X :

#include<iostream.h>
#include<string.h>
using namespace std;
int main(){
   char str[1000];
   int X,count=0;
   cout<<"Enter the Word to be split:"<<"\t";
   cin>>str;
   cout<<"\nEnter the value of X :"<<"\t";
   cin>>X;
   int len=strlen(str);
     if(len%X==0){
        cout<<"X characters up to X:"<<"\n";  
      for(int i=0;i<len;i++){
           if(count<X){
             cout<<str[i];
             count++;
           }
           else if(count==X){
             cout<<"\n";
             cout<<str[i];
             count++;
             count=1;
           }
        }
     }
     else{
          cout<<"The word cannot be split into "<<X<<" equal parts.";
     }
 }

In the above code,

The variable str[1000] and X are obtained. strlen() function calculates the length of the string and stores it in the variable len.

The count variable is initialized with 0 and incremented on each character.

If the count value is less than X the characters are printed.

The count if reaches the value X, it is reset to 1 and therefore it reaches the next line.

If the length of the string is not divisible by X then the program prints that the word cannot be split into X equal parts.

OUTPUT 1:

X characters up to X:
co
de
sp
ee
dy

INPUT 2:

Enter the Word to be split:
program
Enter the value of X:
4

OUTPUT 2:

The word cannot be split into 4 equal parts.

The program prints X characters up to X.

We hope this tutorial helped you to understand how to print X characters up to X using C++.

You may also read:

Leave a Reply

Your email address will not be published. Required fields are marked *