Welcome to PhoneASK, where you can ask questions and receive answers from other members of the community.

Same variable used in 2 nested loops can have different values?

asked 一月 10 at 20:03 by Andy Lowry

First of all I want to say hi to you all!

I'm a self-taught, beginner programmer, started with C, and started to really enjoy this.

Today I've stumbled upon something very interesting and intriguing at the same time in one of my test programs:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define NUMBERS 6
#define BALLS 6

int main()
int x, y, z, numbers[BALLS];

for (x = 0; x < BALLS; x++)
    numbers[x] = -1;


puts("\t\tTHE AMAZING LOTTERY\n\n");
printf("Have you ever won at a lottery?\n");
printf("You can try your luck now! %c\n\n" , 2);
printf("Quick, write down 6 numbers and then press \"Enter\"");

for (y = 0; y < BALLS; y++)

/* This is the intriguing part*/

printf("%d\n", y);

    z = rand() % NUMBERS+1;

    for (y = 0; y < BALLS; y++)
        if (z == numbers[y])
            goto label;
        else if (numbers[y] != -1)
            numbers[y] = z;
printf("\n\nToday's numbers are %c\a ", 16);
for (x = 0; x < BALLS; x++)
    printf("%d, ", numbers[x]);

printf("\n\n\nWell...\n\t..tough luck buddy..");
printf("\n\n\n\tMaybe next time.. %c" , 15);

return 0;

Tried in 3 different compilers, c4droid, code::blocks, and an online compiler. Same intriguing result. Why does the same variable (y), declared only once but used in 2 nested loops, can hold different values without causing any problems?

I don't think this is a recommended practice, but... how come it works?

Your answer

1 Answers

answered 一月 11 at 16:53 by KURN

your code is a bit complicate. it is not supposed to work like what you say unless you define the loop variables inside like "for (int y = 0; ...)" write a simple code and test it:

int i = 0;
for (i = 0; i < 5; i++) {
        printf("in first loop with i = %d\n",i);
    for (i = 0; i < 2; i++) {
        printf("in second loop with i = %d\n",i);

Related Questions

I have this code to get a list of all apps on system: PackageManager pm = getPackageManager(); Intent mainIntent = new Intent(Intent.ACTION_MAIN); List<ResolveInfo> installedApps = pm.queryInt
I'm trying to create a deck of cards (based on the SET game) that has 81 unique cards. I'm trying to accomplish this by using three generalized for loops. Now, I have three arrays of Strings with the
As the title Can I have multiple values in a single variable? First, I have got this form: <form name=myform> <input type=text name=mytext> <input type=button onClick=clickBu
Is --foo++; a valid statement in C? (Will it compile/run) And is there any practical application for this? Sorry for changing the question in an edit but I found something out. According to my C++ co
Specifically I'm trying to do this? How would I accomplish it? class Test { private int var1; public Test(int var1) { var1 = var1; //set the member variable to what was passed in } } I'm sure there's
In a loop, I malloc a certain amount of memory, use it to store some string. When the loop occurs, I will have to malloc another amount of memory, to the same variable I have used. The amount of memor
DISCLAIMER: All of this information is completely fake on the report for testing purposes. I have a report which contains a text box that is getting back a lot of data from a query. The issue is that
I am actually reading a rails book that is written for rails 2.3.5. I want to test Rails 3 beta as well. Is it possible to have such a setup in my Mac OS leopard? I have tried with gem list -d rails.
Defined an ndarray a with dtype as object and filled it with a dictionary a = np.ndarray(shape=(2,3,4), dtype=object) a.fill({'position':(0,0,0)}) This is the value of a array([[[{'position': (0, 0,
I need to create N nested loops to print all combinations of a binary sequence of length N. Im not sure how to do this. Any help would be greatly appreciated. Thanks.
I really don't know how to find out the result of nested loops. For example in the following pseudo-code, I can't sort out what will be given at the end of execution. I'll be so glad if anyone gives m
I know that every for loop is a O(log₂n), but I am not sure what 3 of them together would make? O(3⋅log₂n)? Thank you guys. for (int i = n; i > 0; i = i / 2) { for (int j = n; j > 0; j = j / 2)
I am trying to output all the possible unique integer combinations from 1 to max for a set number of integers. So for 3 integers and a max of 4 I would get: 123 124 134 234 I am doing this with nested
I have a need to create a list of combinations of numbers. The numbers are quite small so I can use byte rather than int. However it requires many nested loops in order to get every possible combinati
I've got some XML that I'm trying to parse. Example: <TVAMain> <ProgramDescription> <ProgramLocationTable> <Schedule value1=1234> <ScheduleEvent> <Program value2=12
I'd like to parallelize a for loop within another for loop. I can simply use the instruction #pragma omp parallel for directly in the inner loop, but I fear that creating a new set of threads each t
I am using R and I have a data frame containing info about the applications made by individuals for a grant. Individuals can apply for a grant as many times as they like. I want to derive a new variab
Why does i remain the same even after a new instance of the class is created? class Test(object): i = 0 def add(self): Test.i += 1 Running this code t = Test() print t.i t.add() t2 = Test() print t2.
I'm having an issue with slugs in child pages. Imagine I have a page called Something in the main tree with the slug something, and another page named Anything with the slug anything. This sec
#include <iostream> using namespace std; int main () { int firstvalue = 5, secondvalue = 15; int * p1, * p2; p1 = &firstvalue; // p1 = address of firstvalue p2 = &secondvalue; // p2 = ad
QUERY SELECT * FROM `products` WHERE ( `category` = 'a' AND `category` = 'b' ) MySQL products --- id sku category ------------------------- 1 34343 a 2 32523 d 3 23234 b 4 23433 b 5 23442 c I want t
This is more a question of semantics than anything else. I'd like to check if a variable is either one of two values. The easiest way of doing this would be: if var == foo || var == bar # or if va
If I want to take an action if php if a variable isn't 0,1, or 2, how would I do that? my if statement isn't working. Thanks!
I've got a function that I want to reference and use across different scripts. Is there any way to do this? I don't want to be re-writing the same function for different scripts. Thanks.
I know that for loops can be avoided almost all the time in R if you understand the language properly, but I'm struggling to find out the clever way of doing this for (i in 1:100){ AllData[[i]]$Div =
I just started learning how to program in c #, so don't shoot me if I have dumb questions or questions to which the answer is probably very logical. I have the next assignment: Use a for loop to wri
How can I calculate worst case running time of this loop? for(int i=1 ; i * i < n ; i*=2) { //do something }
I'm trying to create a sudoku game, for those that do not know what it is. You have a 9x9 box that needs to be filled with numbers from 1-9, every number must be unique in its row and column, and also
I'm trying to open file-a and set each line as a regex. The number of times this regex occurs in file-b needs to be counted. I'm doing this by pushing each match of the regex in file-b into an array @
I have a large datframe (about 3 million rows) which contain an ID, a year and three dates each: lookupdate, date1 and date2. The data.frame is sorted by ID and date1. I want to search through the who
Using Excel 2010 and trying to work on some semi-complicated conditional formatting. The spreadsheet is a roster system (don't ask why...the bosses insist it's the best). I have 1 column which denote
So the object of the script I'm making is to compare files from two while read lists that have file path names in them... while read compareFile <&3; do if [[ ! $server =~ [^[:space:]] ]] ; the
I have a XML file like this: <Document> <Tests> <Test> <Name>A</Name> <Value>1</Value> </Test> <Test> <Name>A</Name> <Value>2<
Why do different versions of Silverlight assemblies have the same version number? Location: ...\Silverlight\v3.0\System.Core.dll Name: System.Core, Version=, Culture=neutral, PublicKeyToken=7ce
This question already has an answer here: SQL Query: How to get items from one col paired with another but not visa versa 3 answers I have some data that looks like this: A | B 97 |556 257|803
I am using many variables with the same type in all functions of the same module: def func1(double x): cdef double a,b,c a = x b = x**2 c = x**3 return a+b+c def func2(double x): cdef double a,b,c a =
I remember years ago hearing that it is more efficient to have loops decrementing instead of incrementing especially when programming microprocessors. Is this true, and if so, what are the reasons?
Can I use a loop in Python to generate 10 different variables instead of computing the value of each variable separately? I can imagine doing this in C/C++ wherein I could use an index value to iterat
I have two dictionaries. dict1 and dict2. dict 2 is always of the same length but dict1 varies in length. Both dictionaries are as follows: dict2 = {name:martin,sex:male,age:97,address:
How can I put the default values for main function arguments like the user defined function?
function ratioDetect () { var contWidth = $('.thumbnail-container').width() var contHeight = $('.thumbnail-container').height() var imgWidth = $('.thumbnail-container img').width() var imgHeight = $('
I have followed many of the excellent pieces of advise on this site about selecting the MAX from a group of rows. I have a history file and I only want the top date and comments for each project numb
I'm working on an AngularJS app. When I console.log an object (the attrs parameter of directive linking function) the browser show unconsistent results for the parameter editable (see image). In Chr
I have a cookie I am setting when a user clicks a button on a form with the following OnClick handler... <input type=button OnClick= alert(document.cookie); var d; d = new Date(); d.setDate(d.
I have 2 tables, Products, and Genre.. In the products table its all the info on the product including two genres, (genre_id and genre_id2), only the first one is required, so the second could have nu
I have a variable number of user-defined lists, each containing words. For example, there may be three lists like the following: list1 = [THE, A] list2 = [ELEPHANT, APPLE, CAR] list3 = [WAL
I know a break statement jumps out of a loop, but does it jump out of nested loops or just the one its currently in? Thanks.
Basically, I am trying to check if 6 of my values are the same. I tried stringing them: if val1 == val2 == val3 == val4 == val5 == val6 #... end But this errors out. Is this possible using another me
Why there is a match here: scala> \bdog\b.r res65: scala.util.matching.Regex = \bdog\b scala> res65.findFirstIn( The dog plays in the yard) res66: Option[String] = Some(dog) But not her
I have 2 table in access,Employee and Dept. In Employee table there is empname column and deptcode column, while in Dept table there is deptcode column and deptname column. I want to do a query which