how to loop and print 3 char's at a time out of a sequnce of characters

I'm trying to create a for loop that loops through a string of chars imputed by the user and i want it to cout<< the arrayor string of chars three characters at a time.
like if i had "aaaaagggggtttttt" i want it to print "aaa" "aag" "ggg" etc. how do I do this?
I tried Googling it but I cant find an example
here's my code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#include<iostream>
#include<fstream>
#include <string>
using namespace std;
int main()//declaring 1st sub-function
{
//declaration of DNA & RNA Array	
char DNA[50];
char RNA[50];
//User prompt
cout<<"Enter DNA Sequence"<<endl; 
int len=0;//declaration and initialization of length counter
cin>>DNA;//user input to DNA Array
for(int i=0; i<=sizeof(DNA); i++){//for loop (initialized; Range; increment)
	//the following if statements are the actual transcription 
	if (DNA[i] == 'A')
	{cout<<"U";
	 RNA[i]='U';
	 len++;
	 }
		if (DNA[i] == 'G')
		{cout<<"C";
		RNA[i]='C';
		len++;
		}
			if (DNA[i] == 'C')
			{cout<<"G";
			RNA[i]='G';
			len++;
			}
	
				if (DNA[i] == 'T')
				{cout<<"A";
				RNA[i]='A';
				len++;
				}
				
         }
	cout<<endl;
	for(int i=0; i<len; i++){//this for loop uses the len variable to count & store value & amount of characters	
	cout<<RNA[i];//printing the next available character stored in the RNA array.
	}

	system("PAUSE");
		return 0;
}



this part of the code this loop i want it to cout<< 3 characters at a time
1
2
for(int i=0; i<len; i++){//this for loop uses the len variable to count & store value & amount of characters	
	cout<<RNA[i];//printing the next available character stored in the RNA array. 

you can do like this,
1
2
for(......,i += 3)
cout<<RNA[i] <<RNA[i + 1] <<RNA[i + 2];
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
#include <stdlib.h>
using namespace std;

void printNextTriplet(const char *strand, int startIndex)
{
    for (int i = 0; strand[startIndex] && i<3; ++i, ++startIndex)
        cout << strand[startIndex];
}

//example how to use
int main()
{
    char rna[] = "aaaaagggggtttttt";
    int index = 0;

    while (index < (int)strlen(rna))
    {
        printNextTriplet(rna, index);
        cout << endl;
        index += 3;
    }
    
    return 0;
}


output:
aaa
aag
ggg
gtt
ttt
t
Last edited on
thanks fellas!!!
Topic archived. No new replies allowed.