Why is it important to initialize the loop control variable for WHILE loops?

1 Answer

Answer :

Uninitialised variables take on whatever value happens to resideat the memory address to which the variable was allocated at thepoint of instantiation. It is a "garbage value" because we cannotpredict what the initial value will actually be at runtime. Allvariables must be initialised before they are used (read); if weuse an uninitialised variable our program has undefinedbehaviour.Ideally, initialisation should always occur at the point ofinstantiation. However, there can be valid reasons for delayinginitialisation. For instance, when we read data from a disk fileinto a memory buffer, it doesn't make any sense to waste timeinitialising the buffer with values we're about to overwrite:void read_file (std::ifstream& file) {char buffer[1024]; // uninitialised!while (file.good()) {size_t index=0;while (file.good() && index<1024) {file >> buffer[index++]; // fill the buffer one characterat a time}if (!file.good()) {if (file.eof()) --index; // index is off-by-one, so adjustelse throw std::exception ("Unknown error in read_file()");}// use the buffer...}}In the above example, index is used as a loop control variablein the inner loop and ultimately tells us how many characters wereread into the buffer (such that index<=1024 upon exiting theinner loop). If EOF was reached, index will be off by one becausewe attempted to read one more character than actually exists, so wedecrement accordingly. We could handle other read errors here but,for the sake of brevity, we throw an exception and let the callerdeal with it. Assuming no read errors occurred, we can safely usethe buffer (all indices less than index are valid). If the filecontains more than 1024 characters, the next iteration of the outerloop will overwrite the buffer, so there's no need to flush it.Now, consider what happens if we (accidently) fail to initialiseindex with the value 0:void read_file (std::ifstream& file) {char buffer[1024]; // uninitialised!while (file.good()) {size_t index; // WARNING: uninitialisedwhile (file.good() && index<1024) {file >> buffer[index++]; // fill the buffer one characterat a time}if (!file.good()) {if (file.eof()) --index; // index is off-by-one, so adjustelse throw std::exception ("Unknown error in read_file()");}// use the buffer...}}This code has undefined behaviour. Hope for a compilerwarning!If we suppose that the code compiles without warning (or weunwisely choose to ignore such warnings), there are severalpossible outcomes. Note that it is reasonable to assume that indexwill always be allocated the same address so, regardless of theinitial value, it will hold whatever value was generated upon theprevious iteration of the inner loop.1. If index happens to hold the (correct) value zero, then theinner loop will read up to 1024 characters. However, any subsequentiteration will incur undefined behaviour because index would thenbe 1024 which is beyond the valid range of buffer.2. If index happens to hold a value greater than zero but lessthan 1024, all characters before buffer[index] will remainuninitialised. Upon exiting the inner loop, there is no way todetermine where writing began and index will tell us we've readmore characters than were actually read. Any subsequent iterationwill incur undefined behaviour because index would then be 1024which is beyond the valid range of buffer.3. If index happens to hold a value greater than or equal to1024, the inner loop will never execute (nothing will be read fromthe file), thus file.good() can never become false and the outerloop becomes an infinite loop. Any attempt to read buffer[index] orany value beyond buffer[1023] incurs undefined behaviour.

Related questions

Description : What is an auto-associative network? a) a neural network that contains no loops b) a neural network that contains feedback c) a neural network that has only one loop d) a single layer feed-forward neural network with pre-processing

Last Answer : b) a neural network that contains feedback

Description : What basic requirement of a closed-loop system (not present in open-loops) enables present load position to be sensed?

Last Answer : Feedback.

Description : An auto-associative network is: a) a neural network that contains no loops b) a neural network that contains feedback c) a neural network that has only one loop d) a single layer feed-forward neural network with pre-processing

Last Answer : b) a neural network that contains feedback

Description : Loop unrolling is a code optimization technique: (A) that avoids tests at every iteration of the loop (B) that improves performance by decreasing the number of instructions in a basic block. ... loops with outer loops (D) that reorders operations to allow multiple computations to happen in parallel.

Last Answer : (A) that avoids tests at every iteration of the loop

Description : In .............., the bodies of the two loops are merged together to form a single loop provided that they do not make any references to each other. (A) Loop unrolling (B) Strength reduction (C) Loop concatenation (D) Loop jamming

Last Answer : (D) Loop jamming

Description : With respect to a loop in the transportation table, which one of the following is not correct? (1) Every loop has an odd no. of cells and at least 5. (2) Closed loops may or may not b square in ... starting cell, must be occupied cells. (4) Every loop has an even no. of cells and at least four.

Last Answer : Every loop has an odd no. of cells and at least 5.

Description : Cascade control is (A) The continuous adjustment of the set point index of an automatic control loop by a primary (master) controller (B) Used when changes in process conditions cause serious upsets in the controlled variable (C) Useful to control flow from temperature (D) All 'a', 'b' & 'c'

Last Answer : (D) All 'a', 'b' & 'c'

Description : Basic C programming question about while loops.

Last Answer : The logic falls out of the loop and continues on…

Description : Python : Efficient way to initialize a very large array -Web-Development

Last Answer : answer:

Description : How to initialize all the key's values in a Python dictionary -Web-Development

Last Answer : answer:

Description : Write a program to initialize large number of strings?

Last Answer : Strings are used as a constant and it helps in creation of the procedure and for the initialization process. - Find the strings and assign it to the variable string. Then create a special string type that will help in ... for i := 1 to cstlen do s[i] := c[i] { place string } end;

Description : Write a C++ program to declare a class student with members as roll no, name and department. Declare a parameterized constructor with default value for department as ‘CO’ to initialize members of object. Initialize and display data for two students.

Last Answer : write a C plus plus program to declare a class which accept and display student information such as roll number division and percentage use get data and put data with required parameters

Description : Write a C++ program to declare a class addition with data members as x and y. Initialize values of x and y with constructor. Calculate addition and display it using function ‘display’.

Last Answer : #include<iostream.h> #include<conio.h> class addition { int x,y; public: addition(int,int); void display(); }; addition::addition (int x1,int y1) { x=x1; y=y1; } void addition: ... y); } void main() { addition a(3,4); a.display(); getch(); }

Description : Give a method to create, declare and initialize structure also develop a program to demonstrate nested structure.

Last Answer : Declaration of structure:- struct structure_name { data_type member 1; data_type member 2; . . . data_type member n; } structure variable 1, structure variable 2,..., structure variable n ... .collegeid); printf("\n College name=%s",s.c.collegename); getch(); }

Description : Define a class circle having data members pi and radius. Initialize and display values of data members also calculate area of circle and display it.

Last Answer : class abc {  float pi,radius; abc(float p, float r) { pi=p; radius=r; } void area() { float ar=pi*radius*radius; System.out.println("Area="+ar); } void display() { System.out.println("Pi="+pi ... void main(String args[]) { abc a=new abc(3.14f,5.0f); a.display(); a.area(); } }

Description : Write a program to declare class student having data members name and percentage. Write constructor to initialize these data members. Accept and display this data for one object.

Last Answer : #include<iostream.h> #include<conio.h> #include<string.h> class student { char name[20]; float per; public: student(char n[],float p) { strcpy(name,n); per=p; } ... { student S("Sachin",78.00); clrscr(); S.putdata(); getch(); }

Description : Write a program in C++ to declare a class measure having data members as add 1, add 2, add 3. Initialize the values of two data members using constructor and display their addition using function.

Last Answer : #include<iostream.h> #include<conio.h> class measure { public: int add1,add2,add3; measure(int a,int b) { add1=a; add2=b; } void cal() { add3=add1+add2; } void display() ... ;>a>>b; measure m1(a, b); m1.cal(); m1.display(); getch(); }

Description : Message passing is a principle to initialize an action by means of a  A) method B) object C) class D) attributes

Last Answer : Message passing is a principle to initialize an action by means of a method

Description : The fluid reaching the distal convoluted tubule from the ascending limb of Henle's loop is (a) isotonic in respect of plasma (b) hypotonic in respect of plasma (c) hypertonic in respect of plasma (d) variable

Last Answer : Ans:(a)

Description : If you needed to execute some code repeatedly based on a certain condition, which of the following would you use: a) Compiler b) Loop c) Variable d) None of These

Last Answer : b) Loop

Description : Types of loop control statements are. a. For loop b. While loop c. Do-while loop d. All of these

Last Answer : d. All of these

Description : Where can I find free dubstep loops for commercial use?

Last Answer : You should check with Jerv and Bookish1. They’re our resident dubstep experts : )

Description : Does anyone know of a good website that has archived radar loops 48-72 hours in length?

Last Answer : Forecasting would be A LOT easier if you could see the radar patterns over the last couple days. The weather forecast that says, High in the mid 80 with a 30% chance of showers doesn't cut it ... yesterday over Tennessee moving east towards North Carolina so I know if it's going to hit us or not.

Description : Boxed cereals (like Froot Loops) have pesticides laced into the plastic bags to keep bugs out. What chemicals are used?

Last Answer : Interesting. I’d never heard this before. Do you have a link to a source that I could check out? Very disturbing if true.

Description : Do you enjoy self referential or self-denying loops?

Last Answer : Pulling the rug out from under me will cause me to slit my own throat!

Description : In a how-much-can-you-stuff-down-your-gullet eating contest, would you choose to overindluge in Froot Loops or Cheerios?

Last Answer : Cheerios. I would kick major ass.

Description : How come Pops and Fruit Loops cereals use different bags than most cereals?

Last Answer : AH i always wondered this! i personally dont like that packaging that pops uses. its weird to touch. like syrofoam EW. but to answer WHY they use it, i have no idea

Description : I get a lag when I try to record vocals into Fruity Loops, Audacity, etc. What am I doing wrong?

Last Answer : You’d probably be better off running the mic through a mixer (or something with dual outs) and sending out one signal to the computer and then other signal for you to listen to, as there will generally be some lag as the computer processes the signal.

Description : Any apps like Fruity Loops?

Last Answer : There’s a cereal app?

Description : Loops of Henle present in

Last Answer : Loops of Henle present in A. Cortex B. Medulla C. Pelvis D. Ureter

Description : What name is given to the loops of DNA in the cytoplasm of bacteria?

Last Answer : Need answer

Description : Three ways musicians can manipulate music with technology is by adding audio effects, creating loops, or?

Last Answer : constructing beats.

Description : How many types of storage loops exists in magnetic bubble memory A) 8 B) 4 C) 16 D) 2

Last Answer : Answer : D

Description : Structured programming codes includes ? sequencing alteration iteration multiple exit from loops only A, B and C

Last Answer : only A, B and C

Description : Figure shows human urinary system with structures labelled A to D. Select option which correctly identifies them and gives their characteristic and/ or functions. (a) C - Medulla - inner zone of ... B - Pelvis - broad funnel shaped space inner to hilum, directly connected to loops of Henle

Last Answer : (c) A - Adrenal gland - located at the anterior part of kidney. Secrete catecholamines which stimulate glycogen breakdown.

Description : A subset of a network that includes all the routers but contains no loops is called ________ a. spanning tree b. spider structure c. spider tree d. special tree

Last Answer : a. spanning tree

Description : The subset of a network that includes all the routers but contains no loops is called ________ A. spanning tree B. spider structure C. spider tree D. special tree

Last Answer : A. spanning tree

Description : One subset of a network that includes all the routers but contains no loops is called ________ A. spanning tree B. spider structure C. spider tree D. special tree

Last Answer : A. spanning tree

Description : Name the two current loops in a transistor.

Last Answer : The base current loop and the collector current loop

Description : A typical liquid-cooling system is composed of what loops?

Last Answer : Primary and secondary.

Description : What are the horizontal loops formed in knitting known as? a. Warps b. Wefts c. Courses d. Wales

Last Answer : c. Courses

Description : Receptors perform the following function/functions: A. Ligand recognition B. Signal transduction C. Both ligand recognition and signal transduction D. Disposal of agonists and antagonists

Last Answer : D. Disposal of agonists and antagonists

Description : The following receptor type has 7 helical membrane spanning amino acid segments with 3 extracellular and 3 intracellular loops: A. Tyrosine protein kinase receptor B. Gene expression regulating receptor C. Intrinsic ion channel containing receptor D. G protein coupled receptor

Last Answer : D. G protein coupled receptor

Description : Consider a Hamiltonian Graph (G) with no loops and parallel edges. Which of the following is true with respect to this Graph (G) ? (a) deg(v) ≥ n/2 for each vertex of G (b) |E(G)| ≥ 1/2 (n-1)(n-2)+2 edges (c) deg(v) + deg( ... edge (A) (a) and (b) (B) (b) and (c) (C) (a) and (c) (D) (a), (b) and (c)

Last Answer : (D) (a), (b) and (c)

Description : Consider an undirected graph G where self-loops are not allowed. The vertex set of G is {(i, j) | 1 ≤ i ≤ 12, 1 ≤ j ≤ 12}. There is an edge between (a, b) and (c, d) if |a – c| ≤ 1 or |b–d| ≤ 1. The number of edges in this graph is (A) 726 (B) 796 (C) 506 (D) 616

Last Answer : (D) 616

Description : Nodes, Branches, and Loops

Last Answer : Nodes, Branches, and Loops

Description : In a graph, the number of independent loops is 6 and the number of independent cut sets is 5, The total number of branches in the graph is A) 9 B) 12 C) 10 D) 11

Last Answer : In a graph, the number of independent loops is 6 and the number of independent cut sets is 5, The total number of branches in the graph is 11

Description : The number of independent loops for a network with n nodes and b branches is

Last Answer : The number of independent loops for a network with n nodes and b branches is b-n+1

Description : Kirchhoff's current law is applicable to 1. Closed loops in a circuit 2. Junction in a circuit 3. Magnetic circuits Which of the above is/are correct ?  (a) 1 only (b) 2 only (c) 3 only (d) 1, 2 and 3

Last Answer : Kirchhoff's current law is applicable to 1. Closed loops in a circuit 2. Junction in a circuit 3. Magnetic circuits Which of the above is/are correct ?  (a) 1 only (b) 2 only (c) 3 only (d) 1, 2 and 3

Description : Write the code given below using ‘for’ loop instead of ‘while’ loop : -Technology

Last Answer : The given code using ‘for’ loop instead of ‘while’ loop :int ifor (i = 1 ; i < = 5 ; i + +){if (1 * i = = 4)jTextFieldl. setText ( “ “ + i) ;}