473,549 Members | 2,731 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Output location in an array

I made the program below. It outputs the smallest number in the array. What
I would like to know is how do I output the array location. I am at a loss.

For example, since the smallest number in the array is 2, the output should
be 2 for the number and 1 for the location. If anyone could help or point
me in the right direction that would be great. Thanks.
-------------------
#include <iostream>
using namespace std;

int main()
{

int array[3];

array[0] = 5;
array[1] = 2;
array[2] = 10;

int k = 0;
for (int i = 0; i < 3; i++)
if (array[i] < array[i+1])
k = i;

cout << k;
return 0;
}
Jul 22 '05 #1
8 2097
Gactimus wrote:
I made the program below. It outputs the smallest number in the array. It does not What
I would like to know is how do I output the array location. I am at a loss.
You need to fix your program then it should be clear for you.
For example, since the smallest number in the array is 2, the output should
be 2 for the number and 1 for the location. If anyone could help or point
me in the right direction that would be great. Thanks.
I think right direction is to think before you program, sorry.
[skip]

--
Regards,
Slava

Jul 22 '05 #2

"Gactimus" <ga******@xrs.n et> wrote in message
news:1100028264 .AejCN2DZfRBBcL rMtYpPQw@bubban ews...
I made the program below. It outputs the smallest number in the array. What
I would like to know is how do I output the array location. I am at a
loss.

For example, since the smallest number in the array is 2, the output
should
be 2 for the number and 1 for the location. If anyone could help or point
me in the right direction that would be great. Thanks.
-------------------
#include <iostream>
using namespace std;

int main()
{

int array[3];

array[0] = 5;
array[1] = 2;
array[2] = 10;

int k = 0;
for (int i = 0; i < 3; i++)
if (array[i] < array[i+1])
k = i;

cout << k;
return 0;
}


That's likely to crash! The if statement compares against array[i+1], and
when i equals 2, it will try to access array[3], which is illegal (undefined
behavior).

Let's look at what your code actualy does. You say it reports the smallest
number, but it doesn't. The variable k gets the value of i, which is the
index ("location", in your terms), not the value from the array. To get the
value, you need to set some variable equal to array[i]. You can do that in
a second variable, named min, for instance. In that case, the if statement
needs {} brackets, with two assignments inside it: one to assign i to k, and
one to assign array[i] to min.

Now that you have a min variable, use that to compare the current array
value against it, instead of comparing it against array[i+1]. For example,
your if statement could be "if (array[i] < min)".

Of course, you need to have a starting value for min. One convenient
starting value would be array[0], especially since you're already defaulting
k to 0.

Once you do that, your can optimize the loop a little, by startng at 1
isntead of 0 (since you already have k set to 0 and min set to array[0]).
So your for loop goes "for (int i = 1; i < 3; ++i)".

(Get into the practice of using ++i instead of i++. It's not important
here, but may be in later work, and it's a good habit to develop.)

So what's that look like now?

int k = 0;
int min = array[0];
for (int i = 1; i < 3; ++i)
{
if (array[i] < min)
{
k = i;
min = array[i];
}
}
cout << "min is " << min << " at index " << k << "\n";

(You probably should also get in the habit of using constant variables for
things like the array size, instead of explicit constants like "3" in the
for loop. That way, you can change the array size in just one place and
have al code that refers to the array size changed at once.)

-Howard


Jul 22 '05 #3
Vyacheslav Kononenko <vy********@NOk ononenkoSPAM.ne t> wrote in
news:H0******** *********@menck en.net.nih.gov:
Gactimus wrote:
I made the program below. It outputs the smallest number in the array.


It does not


You're right. It seemed like it worked the first time but when I changed the
numbers around I realized it was wrong.
Jul 22 '05 #4
Howard wrote:
"Gactimus" <ga******@xrs.n et> wrote in message
news:1100028264 .AejCN2DZfRBBcL rMtYpPQw@bubban ews...
I made the program below. It outputs the smallest number in the array. What
I would like to know is how do I output the array location. I am at a
loss.

For example, since the smallest number in the array is 2, the output
should
be 2 for the number and 1 for the location. If anyone could help or point
me in the right direction that would be great. Thanks.
-------------------
#include <iostream>
using namespace std;

int main()
{

int array[3];

array[0] = 5;
array[1] = 2;
array[2] = 10;

int k = 0;
for (int i = 0; i < 3; i++)
if (array[i] < array[i+1])
k = i;

cout << k;
return 0;
}

That's likely to crash! The if statement compares against array[i+1], and
when i equals 2, it will try to access array[3], which is illegal (undefined
behavior).

Let's look at what your code actualy does. You say it reports the smallest
number, but it doesn't. The variable k gets the value of i, which is the
index ("location", in your terms), not the value from the array. To get the
value, you need to set some variable equal to array[i]. You can do that in
a second variable, named min, for instance. In that case, the if statement
needs {} brackets, with two assignments inside it: one to assign i to k, and
one to assign array[i] to min.

Now that you have a min variable, use that to compare the current array
value against it, instead of comparing it against array[i+1]. For example,
your if statement could be "if (array[i] < min)".

Of course, you need to have a starting value for min. One convenient
starting value would be array[0], especially since you're already defaulting
k to 0.

Once you do that, your can optimize the loop a little, by startng at 1
isntead of 0 (since you already have k set to 0 and min set to array[0]).
So your for loop goes "for (int i = 1; i < 3; ++i)".

(Get into the practice of using ++i instead of i++. It's not important
here, but may be in later work, and it's a good habit to develop.)

So what's that look like now?

int k = 0;
int min = array[0];
for (int i = 1; i < 3; ++i)
{
if (array[i] < min)
{
k = i;
min = array[i];
}
}
cout << "min is " << min << " at index " << k << "\n";

(You probably should also get in the habit of using constant variables for
things like the array size, instead of explicit constants like "3" in the
for loop. That way, you can change the array size in just one place and
have al code that refers to the array size changed at once.)

-Howard

Do you really think that to post the full answer here will help him
learn programming? Especially with an extra variable that is completly
unnecessary:

int k = 0;
for (int i = 1; i < 3; ++i)
if (array[i] < array[k])
k = i;

cout << "min is " << array[k] << " at index " << k << "\n";
--
Regards,
Slava

Jul 22 '05 #5
>int k = 0;
int min = array[0];
for (int i = 1; i < 3; ++i)
{
if (array[i] < min)
{
k = i;
min = array[i];
}
}
cout << "min is " << min << " at index " << k << "\n";


Is variable min necessary?

It seems that keep tracking of the index would be sufficient. At any given
time the minimum value thus far could be retrieved from the array.

Just curious.
Jul 22 '05 #6
DaKoadMunky wrote:
int k = 0;
int min = array[0];
for (int i = 1; i < 3; ++i)
{
if (array[i] < min)
{
k = i;
min = array[i];
}
}
cout << "min is " << min << " at index " << k << "\n";

Is variable min necessary?

It seems that keep tracking of the index would be sufficient. At any given
time the minimum value thus far could be retrieved from the array.

Just curious.


I was curious too :)

It was possible that this could be an optimisation (although it would be
a micro-optimisation). However g++ seems to produce virtually identical
code if it is there or not.

Chris
Jul 22 '05 #7

"Vyacheslav Kononenko" <vy********@NOk ononenkoSPAM.ne t> wrote in message
news:9s******** *********@menck en.net.nih.gov. ..

Do you really think that to post the full answer here will help him learn
programming? Especially with an extra variable that is completly
unnecessary:

int k = 0;
for (int i = 1; i < 3; ++i)
if (array[i] < array[k])
k = i;

cout << "min is " << array[k] << " at index " << k << "\n";


You're correct, the extra variable isn't needed here. It doesn't make it
wrong or even bad form, though. He might want that information later. It's
simply old habit that I keep important information in an identifiable
variable instead of requiring a "lookup" to get it later. Call it
"pre-emptive optimization". :-)

As for posting the whole answer, yes, I *do* think it helped, in this case.
He tried something, and it was wrong. By the time I'd explained the
problems and potential solutions, in prose, I was afraid he'd just be even
more confused if it wasn't put back together as real code. I walked him
through each step of the corrections, and guided him to the final result.
So, yes, I think it was very helpful.

-Howard
Jul 22 '05 #8
Gactimus wrote:
"Howard" <al*****@hotmai l.com> wrote in
news:WL******** ************@bg tnsc04-news.ops.worldn et.att.net:

"Vyacheslav Kononenko" <vy********@NOk ononenkoSPAM.ne t> wrote in message
news:9s****** ***********@men cken.net.nih.go v...

Do you really think that to post the full answer here will help him
learn programming? Especially with an extra variable that is completly
unnecessar y:

int k = 0;
for (int i = 1; i < 3; ++i)
if (array[i] < array[k])
k = i;

cout << "min is " << array[k] << " at index " << k << "\n";
You're correct, the extra variable isn't needed here. It doesn't make
it wrong or even bad form, though. He might want that information
later. It's simply old habit that I keep important information in an
identifiabl e variable instead of requiring a "lookup" to get it later.
Call it "pre-emptive optimization". :-)

As for posting the whole answer, yes, I *do* think it helped, in this
case. He tried something, and it was wrong. By the time I'd explained
the problems and potential solutions, in prose, I was afraid he'd just
be even more confused if it wasn't put back together as real code. I
walked him through each step of the corrections, and guided him to the
final result. So, yes, I think it was very helpful.

Okay, I appreciate all your help so far but I still haven't finished the
program. The goal of the program is to to pass an array to a function, get
two values of which I explained earlier, put those values in a structure
and then return the single structure item with the two imbedded values.
After working on it for the last few hours, I have gotten the program down
to one error but I am stuck. Any help would be great.

Here is my code:

-------------------
#include <iostream>
using namespace std;

struct minimum
{
int lowest;
int index;
};

const minimum array[] = {5,9,6,3,2,10};
minimum function(int array[]);
void output(minimum t);
int main()
{
minimum pass = function(array) ;
output(pass);

return 0;
}

minimum function(int array[])


you should pass size of the array as a second parameter otherway your
function is rather useless(unless your task is define a function that
finds minimum and index of array THAT HAS 7 elements):
minimum function(int array[], int size)

and call will be then
minimum pass = function(array, sizeof(array)/sizeof(array[0])); {
minimum total;
int k = 0;
int min = array[0];
It is not a mistake but you already have "total" why not to use it
instead of "k" and "min"?
for (int i = 1; i < 7; ++i) for(int i = 1; i < size; ++i) {
if (array[i] < min)
{
k = i;
min = array[i];
}
}
total.index = k;
total.lowest = min; you will not need this two statements if you use total before.
return total;
}

void output(minimum t)
{
cout << "The number closest to Zero is " << t.lowest << ".\n";
cout << "The index of the number is " << t.index << ".\n";
}

--
Regards,
Slava

Jul 22 '05 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
5751
by: bunnyman | last post by:
I have a for each loop in javascript, of which I need to output to an ASP array. unfortunantly not too familiar with javascript.. the loop is for items ordered in a shopping cart. they are displayed as rows of a table. all i need to do is get the same data into an ASP array to use on the next page, specificaly the +theitem+ and +thenumber+...
3
2030
by: Blankdraw | last post by:
I'm getting NO errors and 2 warnings with this code. I thought I was ready to write the output-formatting segment, but may be way off the mark now. The warnings say that "OPEN() and READ() are undeclared - assuming an external is returning integer values." This is not the source of the problem. Step-Thru causes the system to demand the...
5
2158
by: Tom Lam lemontea | last post by:
Hi all, This is my very first post here, I've seriously tried some programming on C, and shown below is my very first program(So you can expect it to be very messy) that I wrote after I've learned the basics. However, the output function I wrote seems to repeat unneedingly for 2 times. My trial on solving it myself have failed. Anyone willing...
4
1436
by: nichas | last post by:
the code is ... int main(void){ static int a={1,2,3,4,5}; static int *p={a,a+1,a+2,a+3,a+4}; int i; for(i=0;i<5;i++){ printf("%u\n",a+i);} printf("\n%u\t%u\t%d",p,*p,*(*p)); return 0; } Now in this code the output which iam getting is :::
6
2094
by: Ben | last post by:
Hi We have a Dataset that has been populated from the output parameter of a Stored Procedure (@Output). I understand that I can extract a single item when the dataset is populated by a table using this code: CType(objDataSet.Tables("MyTable").Rows(0).Item("MyField"), String)
11
1639
by: chutsu | last post by:
Hi Ok...I got a problem in reading a file containning information, and trying to send it to a function... the file containing information has format: Gas 10000 Home Gas Meter Electricity 3000 Home Electricity Meter Flight 8000 Holiday Abroad Flight 1000 Long Weekend Car 1250 Own Car (10000 miles) Car 500 Holiday...
3
9561
by: super.raddish | last post by:
Greetings, I am relatively new to, what I would call, advanced XSLT/XPath and I am after some advice from those in the know. I am attempting to figure out a mechanism within XSLT to compare the difference between two source documents and output node-sets which are "different" (changed or new) to new XML files using xsl:result-document To...
3
1393
by: Aarti | last post by:
Hi, Can some one please explain why the output of this program is 15 #include <iostream> using namespace std; class A {
17
1780
by: Nikhil Bokare | last post by:
#include<stdio.h> int main() { int a; printf("%d %d %d %d",a,*a,**a,&a); } I tried the above code and got the same value for a, *a , **a and &a. Can anyone please tell me the reason behind such a behavior?
0
7518
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7446
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
6040
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5368
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
5087
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3498
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
1
1935
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1057
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
757
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.