473,574 Members | 2,687 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Simple Program using Arrays

I am a newbie to C++ and I need help with a simple program I am trying
to write. My program is designed to print all of the odd integers
contained in an array and output the sum of the odd integers. My code
is listed below, but the problem is that my output of sum is wrong.
For example, I am using 1347830 for my integers and the program outputs
373 and after adding 373 you should get 13 for the total, but that
doesn't happen. Any help you can provide is appreciated! Thanks!
------------------------------------------------------------*---
#include <iostream.h>
#include <iomanip.h>

void main()
{
char numbers[20];
int sum = 0;

cout << "Barcode: ";
cin.get(numbers , 20);

for(int i = 1; i < numbers[i]; i+=2)
{
cout << numbers[i];
sum += numbers[i];
}
cout << endl;
cout << sum;
cout << endl;
}

Jul 23 '05 #1
6 4951
ho************@ hotmail.com wrote:
I am a newbie to C++ and I need help with a simple program I am trying
to write. My program is designed to print all of the odd integers
contained in an array and output the sum of the odd integers. My code
is listed below, but the problem is that my output of sum is wrong.
For example, I am using 1347830 for my integers and the program outputs
373 and after adding 373 you should get 13 for the total, but that
doesn't happen. Any help you can provide is appreciated! Thanks!
------------------------------------------------------------*---
#include <iostream.h>
#include <iomanip.h>

void main()
{
char numbers[20];
int sum = 0;

cout << "Barcode: ";
cin.get(numbers , 20);

for(int i = 1; i < numbers[i]; i+=2)
{
cout << numbers[i];
sum += numbers[i];
}


I think you should write i < 20 instead of i < numbers[i]. More
precisely i < (number of elements you actually put in the array...)

Bye

Andrea
Jul 23 '05 #2
ho************@ hotmail.com wrote:
I am a newbie to C++ and I need help with a simple program I am trying
to write. My program is designed to print all of the odd integers
contained in an array and output the sum of the odd integers. My code
is listed below, but the problem is that my output of sum is wrong.
For example, I am using 1347830 for my integers and the program outputs
373 and after adding 373 you should get 13 for the total, but that
doesn't happen. Any help you can provide is appreciated! Thanks!
------------------------------------------------------------*---
#include <iostream.h>
#include <iomanip.h>

void main()
{
char numbers[20];
int sum = 0;

cout << "Barcode: ";
cin.get(numbers , 20);

for(int i = 1; i < numbers[i]; i+=2)
{
cout << numbers[i];
sum += numbers[i];
}
cout << endl;
cout << sum;
cout << endl;
}


Note that arrays in C/C++ start at index 0. That means, the first odd
number would be at [0], the next at [2] and so on.
Jul 23 '05 #3

<ho************ @hotmail.com> wrote in message
news:11******** **************@ l41g2000cwc.goo glegroups.com.. .
I am a newbie to C++ and I need help with a simple program I am trying
to write. My program is designed to print all of the odd integers
contained in an array
Question: why did you define your array as containing
type 'char' values, and not type 'int'? Besides the
other major problems I point out below, this issue
alone will give you wrong results (explained below).
and output the sum of the odd integers. My code
is listed below, but the problem is that my output of sum is wrong.
For example, I am using 1347830
I'll have to assume that you mean the sequence of integers
1,3,4,7,8,3,0
for my integers and the program outputs 373
You should separate your values so we don't confuse
3,7,3 with the integer 373
and after adding 373
There's another odd integer in your sequence: 1
you should get 13 for the total,
My brain computes 14. :-)
but that
doesn't happen. Any help you can provide is appreciated! Thanks!


#include <iostream.h>

#include <iostream>
#include <ostream>

#include <iomanip.h>

#include <iomanip>
/* but you're not using anything from this
header anyway, you don't need it */

using namespace std;

void main()

int main()

/* main() returns type 'int'. ALWAYS */

{
char numbers[20];
int sum = 0;

cout << "Barcode: ";
cin.get(numbers , 20);

Better would be:

cin.get(numbers , sizeof numbers);

Even better would be to use a std::string (declared by <string>)
instead of an array:

std::string numbers;
std::getline(ci n, numbers);
/* (you can address the characters of a std::string using
the same syntax as for an array of characters) */

for(int i = 1; i < numbers[i]; i+=2)

All three expressions in your 'for' are wrong:

1. Arrays in C++ are indexed beginning with zero, not one.

2. Why are you comparing your counter against an array element?
(also note that comparing against any which have not been
assigned a value produces undefined behavior -- which
will happen if the user enters less than 19 characters
-- this problem could have been avoided had you initialized
your array when you created it.)

3. Why are you skipping every other element in your array?
This simply accesses the elements whose indices are odd
numbers. How can you check every element for 'oddness'
if you don't examine all of them?
{
cout << numbers[i];
sum += numbers[i];
}

Your loop simply accumulates the sum of all the elements
whose indices are odd numbers. It doesn't check the values
themselves for 'oddness' at all. And again, if any of
your array elements haven't been given values, trying
to access them gives undefined behavior. Again, initializing
your array would have prevented this problem. You need to
determine the actual number of characters which were
input, and use that as your limit value in your loop
(see function 'strlen()', declared by <cstring> or
string.h, or if using 'std::string', see its member
function 'size()')

The promised 'explanation' mentioned above:
Once you get all the rest of these problems sorted out,
note that when you assign an input character to a
type 'char' object, what gets stored is the encoded value
for that character as defined by the character set your
computer uses (e.g. ASCII). On on ASCII system, character
'5', has a numeric value of 53, not 5.

The possible solutions are:
1:
Define your array as having elements of type 'int', and
request each value with a separate input (these can still
be supplied by the user on one line, but must be separated
by whitespace). (This will let you use values other than
0 - 9). You'll need to check for and reject bad input (i.e.
containing non-digit characters).

2:
Keep your array as having 'char' objects (or use a std::string),
and translate the digit characters to their corresponding
numeric values. This can be done portably by subtracting
the value '0' (the character literal, not the integer literal 0)
from each. Again, you'll need to also check each character to
ensure it's a digit.
cout << endl;
cout << sum;
cout << endl;
}

If you don't understand some or all of what I wrote above, feel
free to ask specific questions.

HTH,
-Mike

Jul 23 '05 #4
Based on what I'm seeing here, I'm guessing you've been skipping out until
now. Am I right? And midterms are just around the bend. Sheesh.

<ho************ @hotmail.com> wrote in message
news:11******** **************@ l41g2000cwc.goo glegroups.com.. .
I am a newbie to C++ and I need help with a simple program I am trying
to write. My program is designed to print all of the odd integers
contained in an array and output the sum of the odd integers. My code
is listed below, but the problem is that my output of sum is wrong.
For example, I am using 1347830 for my integers and the program outputs
373 and after adding 373 you should get 13 for the total, but that
doesn't happen. Any help you can provide is appreciated! Thanks!
------------------------------------------------------------*---
#include <iostream.h>
#include <iomanip.h>

void main()
{
char numbers[20];
int sum = 0;

cout << "Barcode: ";
cin.get(numbers , 20);

for(int i = 1; i < numbers[i]; i+=2)
{
cout << numbers[i];
sum += numbers[i];
}
cout << endl;
cout << sum;
cout << endl;
}
Jul 23 '05 #5
<ho************ @hotmail.com> wrote:

I am a newbie to C++ and I need help with a simple program I am trying
to write. My program is designed to print all of the odd integers
contained in an array and output the sum of the odd integers. My code
is listed below, but the problem is that my output of sum is wrong.
For example, I am using 1347830 for my integers and the program outputs
373 and after adding 373 you should get 13 for the total, but that
doesn't happen. Any help you can provide is appreciated! Thanks!
------------------------------------------------------------*---
#include <iostream.h>
#include <iomanip.h>

void main()
{
char numbers[20];
int sum = 0;

cout << "Barcode: ";
cin.get(numbers , 20);

for(int i = 1; i < numbers[i]; i+=2)
{
cout << numbers[i];
sum += numbers[i];
}
cout << endl;
cout << sum;
cout << endl;
}

Are you sure you understand what is to be done? I think you are supposed to
find the odd *digits*. You are only examining half the digits, IOW you are
looking at odd *locations*. (the i+= 2 code) Look at all the locations and
determine if the digit is odd or even. Use the modulo operator(%) to make
your decision.

Look up the words digit and integer in a dictionary; they are not the same
thing.

I admit there is a certain amount of guesswork in my answer. Because, in
the C world, an array of char does not contain any integers. There is a
messy bit about the distinction between things and the representation of
those things. And I am *postulating* what seems to me a reasonable
assignment in a course on C.
Jul 23 '05 #6
"osmium" <r1********@com cast.net> wrote in message
news:36******** *****@individua l.net...
<ho************ @hotmail.com> wrote:

I am a newbie to C++ and I need help with a simple program I am trying
to write. My program is designed to print all of the odd integers
contained in an array and output the sum of the odd integers. My code
is listed below, but the problem is that my output of sum is wrong.
For example, I am using 1347830 for my integers and the program outputs
373 and after adding 373 you should get 13 for the total, but that
doesn't happen. Any help you can provide is appreciated! Thanks!
------------------------------------------------------------*---
#include <iostream.h>
#include <iomanip.h>

void main()
{
char numbers[20];
int sum = 0;

cout << "Barcode: ";
cin.get(numbers , 20);

for(int i = 1; i < numbers[i]; i+=2)
{
cout << numbers[i];
sum += numbers[i];
}
cout << endl;
cout << sum;
cout << endl;
}

Are you sure you understand what is to be done? I think you are supposed
to find the odd *digits*. You are only examining half the digits, IOW you
are looking at odd *locations*. (the i+= 2 code) Look at all the
locations and determine if the digit is odd or even. Use the modulo
operator(%) to make your decision.

Look up the words digit and integer in a dictionary; they are not the same
thing.

I admit there is a certain amount of guesswork in my answer. Because, in
the C world, an array of char does not contain any integers. There is a
messy bit about the distinction between things and the representation of
those things. And I am *postulating* what seems to me a reasonable
assignment in a course on C.


I don't know what happened to the corner brackets in that post - they seem
to have disappeared.

-- Osmium.
Jul 23 '05 #7

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

Similar topics

38
3504
by: jrlen balane | last post by:
basically what the code does is transmit data to a hardware and then receive data that the hardware will transmit. import serial import string import time from struct import * ser = serial.Serial()
31
14314
by: da Vinci | last post by:
OK, this has got to be a simple one and yet I cannot find the answer in my textbook. How can I get a simple pause after an output line, that simply waits for any key to be pressed to move on? Basically: "Press any key to continue..." I beleive that I am looking for is something along the lines of a....
7
4115
by: jmac | last post by:
Greetings fellow programmers, I have created a C program that has a few bugs and would like to get some help with working them out. Here is a list of the problems that I am experiencing: - The program calls for the input to be added in one line (? 100 Smith 24.98), but my right now my program skips a line each time for example: ? 100
5
7229
by: Rob Somers | last post by:
Hey all I am writing a program to keep track of expenses and so on - it is not a school project, I am learning C as a hobby - At any rate, I am new to structs and reading and writing to files, two aspects which I want to incorporate into my program eventually. That aside, my most pressing problem right now is how to get rid of the newline...
51
8243
by: Alan | last post by:
hi all, I want to define a constant length string, say 4 then in a function at some time, I want to set the string to a constant value, say a below is my code but it fails what is the correct code? many thx!
8
2119
by: SK | last post by:
Hi I am trying to write a simple C program with devc++ as the complier using the concept of arrays. I cannot get the program to compile without mutiple errors. If anyone has the time to help me I would really apprecaite it. Thanks SK //Specs to be added later //C Libraries #include <stdio.h>
4
3967
by: NT | last post by:
Hi there! I am puzzled by what I think must be a subtlety of C++ when list-initializing member variables in derived classes... Here's what I mean... class A { // warning l337proggy alert! ;-) public: A(int v=9812); // default value provided since this base constructor
4
2459
by: learnfpga | last post by:
Here is a little code I wrote to add the numbers input by the user.....I was wondering if its possible to have the same functionality without using dynamic arrays.....just curious..... //trying to get input from the user to add all the numbers that user inputs //tried to do it without dynamic memory usage but probably cannot achieve it...
24
3419
by: Michael | last post by:
Hi, I am trying to pass a function an array of strings, but I am having trouble getting the indexing to index the strings rather than the individual characters of one of the strings. I have declared an array as: char *stringArray = {"one","two","three","a"}; When I pass the array using:
0
7832
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
8093
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
8262
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7843
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
8129
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
6498
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
2262
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
1364
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1094
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.