Dynamic array and foreach loop

Binarydepth via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Aug 8 08:52:19 PDT 2015


I'm writing a program that rotates numbers then asks the user if 
a new set of numbers should be rotated. I'm having trouble using 
a Foreach loop to fill a dynamic array with the elements to be 
rotated.

Here's my code, I add a TAB when a loop is inside a loop and and 
do that too to the statements inside and to IF's also.

import std.stdio;

/*Input : Quantity of elements, elements y positions to be 
rotated*/
/*Output : Elements rotated as requested*/
void main()        {
int liEle, liCount, liRot, liAcc;
int[] liaOrig, liaFinal;
immutable kArr=50;
/*Variables : Quantity of elements to be used, Counter variable 
for loops,
Array for original sequence, Array for final sequence, Variable 
for positions to rotate and
Action counter variable.

*/
char lcRot;//Variable for options

do	{//Complete program. Also runs when an other sequence is to be 
used

         do	{//Validation loop for the array. Must be positive


		 write ("How many elements need to be used? ");
		 readf(" %d", &liEle);
		        if(liEle<2)
			        write("Must be a number greater than 1\n");
	}while(liEle<2 || liEle>kArr);
	liaOrig.length = liEle;
	liaFinal.length = liEle;
	foreach(num; liaOrig[0..$])	{//Data input loop

		write("Input the element : ", num+1, " ");
		readf(" %d", &liaOrig[num]);
	}

	do	{
	        do	{
		        write("How many positions do you wish to rotate ? ");
		        readf(" %d", &liRot);
		        if(liRot<1)
		        	write("Input a positive number\n");
         	}while(liRot<1);//Keep asking if a negatice number


			liRot%=liEle;// Reduce rotations for minimal executino

		for(liCount=liEle-1, liAcc=liRot-1; liAcc>=0; liCount--, 
liAcc--)	{//Revrse loop for rotation
			liaFinal[liAcc]=liaOrig[liCount];
		}
		for(liCount=0; liRot<liEle; liCount++, liRot++) 
{//Complementary loop for missed elements
			liaFinal[liRot]=liaOrig[liCount];
		}
		write("The original patter is : ");//Output the original 
sequence
		for(liCount=0; liCount<liEle; liCount++)	{
			write(liaOrig[liCount], " ");
		}
		write("\n");//New line for next loop output
		write("The final is : ");//Final sequence output
		for(liCount=0; liCount<liEle; liCount++)	{//loop for Final 
sequence output
			write(liaFinal[liCount], " ");
		}
		write("\nDo you want to rotate again ? y/n ");//Option to 
rotate again
		readf(" %c", &lcRot);
		if(lcRot == 'y' || lcRot == 'Y')	{
			for(liCount=0; liCount<liEle; liCount++)//Keep the Final 
sequence
				liaOrig[liCount]=liaFinal[liCount];
		}
		else	{
			write("Do you want to make an adicional  sequence ? a/A 
");//Option to make a new sequence
			readf(" %c", &lcRot);
		}
	        }while(lcRot == 'y' || lcRot == 'Y');
}while(lcRot == 'A' || lcRot == 'a');//Loop for restarting the 
program
write("End of program\n");//Nothing else to do
}



More information about the Digitalmars-d-learn mailing list