How to resolve the algorithm Loops/Nested step by step in the Stata programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Loops/Nested step by step in the Stata programming language

Table of Contents

Problem Statement

Show a nested loop which searches a two-dimensional array filled with random numbers uniformly distributed over

[ 1 , … , 20 ]

{\displaystyle [1,\ldots ,20]}

. The loops iterate rows and columns of the array printing the elements until the value

20

{\displaystyle 20}

is met. Specifically, this task also shows how to break out of nested loops.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Loops/Nested step by step in the Stata programming language

Source code in the stata programming language

matrix a=J(20,20,0)
forv i=1/20 {
	forv j=1/20 {
		matrix a[`i',`j']=runiformint(1,20)
	}
}


local q 0
forv i=1/20 {
	forv j=1/20 {
		display "check `i',`j'"
		if el("a",`i',`j')==20 {
			display "found at `i',`j'"
			local q 1
			continue, break
		}
	}
	
	if `q' continue, break
}
if !`q' {
	display "not found"
}


local q 0
local i=1
while !`q' & `i'<=20 {
	local j=1
	while !`q' & `j'<=20 {
		display "check `i',`j'"
		if el("a",`i',`j')==20 {
			display "found at `i',`j'"
			local q 1
		}
		local ++j
	}
	local ++i
}
if !`q' {
	display "not found"
}


capture {
	forv i=1/20 {
		forv j=1/20 {
			display "check `i',`j'"
			if el("a",`i',`j')==20 {
				display "found at `i',`j'"
				exit -1
			}
		}
	}
}
if _rc==-1 {
	// value was found
}
else if _rc==0 {
	display "not found"
}
else exit _rc


function findval1(a,x,i0,j0) {
	n=rows(a)
	p=cols(a)
	for (i=1; i<=n; i++) {
		for (j=1; j<=p; j++) {
			if (a[i,j]==x) {
				i0=i
				j0=j
				return(1)
			}
		}
	}
	return(0)
}

function findval2(a,x,i0,j0) {
	n=rows(a)
	p=cols(a)
	q=0
	for (i=1; i<=n; i++) {
		for (j=1; j<=p; j++) {
			if (a[i,j]==x) {
				i0=i
				j0=j
				q=1
				goto END
			}
		}
	}
END:
	return(q)
}

function findval3(a,x,i0,j0) {
	n=rows(a)
	p=cols(a)
	q=0
	for (i=1; i<=n; i++) {
		for (j=1; j<=p; j++) {
			if (a[i,j]==x) {
				i0=i
				j0=j
				q=1
				break
			}
		}
		if (q) {
			break
		}
	}
	return(q)
}


a=st_matrix("a")
findval1(a,20,i=.,j=.)
findval2(a,20,i=.,j=.)
findval3(a,20,i=.,j=.)

  

You may also check:How to resolve the algorithm Emirp primes step by step in the 11l programming language
You may also check:How to resolve the algorithm Pancake numbers step by step in the ooRexx programming language
You may also check:How to resolve the algorithm Show ASCII table step by step in the Factor programming language
You may also check:How to resolve the algorithm Hello world/Graphical step by step in the Racket programming language
You may also check:How to resolve the algorithm Hello world/Standard error step by step in the AArch64 Assembly programming language