473,624 Members | 2,154 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

First Program

mwt
Hello. Today I wrote my first program in C. It adds up the elements in
an array. I am just beginning to learn this language. Any tips or
pointers about better ways to write/structure/format/etc. this code
would be much appreciated. Thanks.
mwt.

#include <stdio.h>

int add_array(int arr[], int arr_size)
{
int j;
int total = 0;
for(j = 0; j < arr_size; j++)
total += arr[j];
return(total);

}

main()
{
int size;

printf("Input size of array>");
scanf("%d", &size);
int array[size];
int i;
for(i=0; i<size; i++)
{
array[i] = i+1;

}

printf("Sum of array elements is %d.\n", add_array(array ,
size));
}

Apr 13 '06 #1
26 2243
"mwt" writes:
Hello. Today I wrote my first program in C. It adds up the elements in
an array. I am just beginning to learn this language. Any tips or
pointers about better ways to write/structure/format/etc. this code
would be much appreciated. Thanks.
mwt.

#include <stdio.h>

int add_array(int arr[], int arr_size)
{
int j;
int total = 0;
for(j = 0; j < arr_size; j++)
total += arr[j];
return(total);

}

main()
{
int size;

printf("Input size of array>");
scanf("%d", &size);
int array[size];
int i;
for(i=0; i<size; i++)
{
array[i] = i+1;

}

printf("Sum of array elements is %d.\n", add_array(array ,
size));
}


Assuming that it works, I would say you are off to a good start.
Apr 13 '06 #2
"mwt" <mi*********@gm ail.com> writes:
Hello. Today I wrote my first program in C. It adds up the elements in
an array. I am just beginning to learn this language. Any tips or
pointers about better ways to write/structure/format/etc. this code
would be much appreciated. Thanks.

#include <stdio.h>

int add_array(int arr[], int arr_size)
{
int j;
int total = 0;
for(j = 0; j < arr_size; j++)
total += arr[j];
return(total);

}

main()
{
int size;

printf("Input size of array>");
scanf("%d", &size);
int array[size];
^--- looks like a gcc feature so it might not be portable
(is this in C99?).

you should use:

int *array = malloc(size*siz eof(*array))
int i;
for(i=0; i<size; i++)
{
array[i] = i+1;
}

printf("Sum of array elements is %d.\n", add_array(array ,
size));
and don't forget to free it when you're finished with it:

free(array)
}


Other than that it looks good. Style is fine AFAICT.

--
burton samograd kruhft .at. gmail
kruhft.blogspot .com www.myspace.com/kruhft metashell.blogs pot.com
Apr 13 '06 #3
mwt
>^--- looks like a gcc feature so it might not be portable
(is this in C99?).

I am compiling with gcc. Other than that, I have no idea what type of C
it is.
For learning maximally portable features, what linux-based compiler (or
perhaps flags on gcc) should I be using?

Apr 13 '06 #4
mwt
Ah. I see. If I use the -pendantic option in gcc, it enforces strict
compliance with ISO C90, and won't allow the

int array[size];

declaration.
Interesting.

Apr 13 '06 #5
osmium wrote:
"mwt" writes:
main()
{
int size;

printf("Input size of array>");
scanf("%d", &size);
int array[size];

Assuming that it works, I would say you are off to a good start.


You're pretty easy. What version of C allows both implicit declaration
of functions AND variable-length arrays?


Brian
Apr 13 '06 #6
"mwt" <mi*********@gm ail.com> wrote:
Hello. Today I wrote my first program in C. It adds up the elements in
an array. I am just beginning to learn this language. Any tips or
pointers about better ways to write/structure/format/etc. this code
would be much appreciated. Thanks.
mwt.
Compiling (under Linux) with "gcc -Wall -ansi -pedantic first.c"
produces a few warnings. I inserted them at the matching line.

#include <stdio.h>

int add_array(int arr[], int arr_size)
{
int j;
int total = 0;
for(j = 0; j < arr_size; j++)
total += arr[j];
return(total); ( The parenthesis are not necessary. I tend to use them here myself)
}

main() first.c:14: warning: return type defaults to `int'
(Should be "int main(void)" if you do not process command line
parameters) {
int size;

printf("Input size of array>");
scanf("%d", &size);
int array[size]; first.c:19: warning: ISO C89 forbids variable-size array `array'
first.c:19: warning: ISO C89 forbids mixed declarations and code
(Probably too early for you to bother about different versions of C,
but be aware that the language has changed over time) int i;
for(i=0; i<size; i++)
{
array[i] = i+1;

}

printf("Sum of array elements is %d.\n", add_array(array ,
size)); first.c:29: warning: control reaches end of non-void function
( missing return EXIT_SUCCESS; - defined in stdlib.h } }


A few comments on style: be consistent. You use braces around the
single statement in the for() loop in the main function, (which is
good,) but not in a similar loop in add_array().

Likewise, you use a "double level" indentation for the function
blocks, but not for the for() loops. Pick a style and stick with it.

A few comments describing the program's purpose would be helpful. They
become much more important for more complex programs.

All in all, very good for a first program!
Apr 13 '06 #7
mwt wrote:
Hello. Today I wrote my first program in C. It adds up the elements in
an array. I am just beginning to learn this language. Any tips or
pointers about better ways to write/structure/format/etc. this code
would be much appreciated. Thanks.
mwt.

#include <stdio.h>

int add_array(int arr[], int arr_size)
{
int j;
int total = 0;
for(j = 0; j < arr_size; j++)
total += arr[j];
return(total);
The parentheses around total are necessary. While not harmful, it
implies that you believe return to be function.
}

main()
This should be declared as:

int main(void)
{
int size;

printf("Input size of array>");
scanf("%d", &size);
You have no way of know whether the person entered a legal value for
size here. Hint, scanf() returns a value, find out why and what it
means. You should also use an unsigned type for size, as you don't want
people entering a negative number. At the very least, you need to check
the number to make sure it's greater than 0.
int array[size];
int i;
for(i=0; i<size; i++)
{
array[i] = i+1;

}

printf("Sum of array elements is %d.\n", add_array(array ,
size));
}


The things used above (variable length arrays and declaration of
objects following code) are C99 features. That's not to say that you
shouldn't learn them, just be aware that you won't find them in some
textbooks, notably K&R.

If you are going to use C99, I would recommend moving the declaration
of i into the for loop:

for (int i=0; i<size; i++)
While it is ok to leave out a return from main() in C99, I prefer to
see an explicit one anyway. Purely stylistic.


Brian
Apr 13 '06 #8
"mwt" <mi*********@gm ail.com> writes:
Hello. Today I wrote my first program in C. It adds up the elements in
an array. I am just beginning to learn this language. Any tips or
pointers about better ways to write/structure/format/etc. this code
would be much appreciated. Thanks.
mwt.
If this is your first C program, it's an excellent start. I'll offer
a few minor suggestions.
#include <stdio.h>

int add_array(int arr[], int arr_size)
Keep in mind that, in a parameter declaration "int arr[]" is exactly
equivalent to "int *arr"; in other words, you're really passing a
pointer, not an array. Section 6 of the comp.lang.c FAQ,
<http://www.c-faq.com/>, covers arrays and pointers very well.

Some programmers (myself included) prefer not to use this
looks-like-an-array-but-acts-like-a-pointer declaration, but that's
just a matter of style; feel free to use whatever you're comfortable
with.

{
int j;
int total = 0;
for(j = 0; j < arr_size; j++)
total += arr[j];
return(total);
The parentheses are unnecessary. Again, this is a matter of style,
but I prefer "return total;"; a return statement isn't a function
call, and it shouldn't look like one.
}

main()
This should be "int main(void)".
{
int size;
Consider calling this "length" rather than "size". The word "size"
implies sizeof, which gives the size of an object in bytes; the number
of elements in an array is its length. (If sizeof(int)==4, a
10-element array of int has a length of 10 and a size of 40.)
printf("Input size of array>");
Due to buffering, it's not guaranteed that this will appear
immediately. Add "fflush(stdout) ;" to ensure that the prompt appears
before the program starts waiting for input.
scanf("%d", &size);
You'll find that the scanf() function has some pitfalls. In this
case, it will skip all leading whitespace, including newlines. If you
enter a valid integer, it will leave any characters *following* that
to be read by further calls; for example, if you type "123<ENTER> ",
then read a single character, the character you read will be the
new-line character.

It doesn't matter in a small program like this, but it will matter
later on. One good approach is to use fgets() (*never* use gets()) to
read a full line, then use sscanf() to parse it.

Also, scanf() returns a result, which you're ignoring. What happens
if you enter something other than a valid number?
int array[size];
There are two C standards, C90 and C99. C99 theoretically supersedes
C90, but it's not yet universally implemented. For maximum
portability, you should consider sticking to C90 features.

Here you're using two C99-specific features (or perhaps gcc
extensions). C90 doesn't allow declarations to follow statements
within a block, though you can work around it by introducing a new
block. Also, C90 requires array lengths to be compile-time constants;
C99 introduces variable-length arrays, and gcc has supported something
very similar as an extension for some time. Burton Samograd already
suggested using malloc() instead (which also has the advantage that
you can catch allocation errors).
int i;
for(i=0; i<size; i++)
{
array[i] = i+1;

}

printf("Sum of array elements is %d.\n", add_array(array ,
size));
You should add "return 0;" here. (It's not strictly required in C99,
but it's a good idea anyway.
}


<OT>

To get warnings about non-standard code (i.e., to persuade gcc to act
as a conforming C compiler), you can use:
gcc -ansi -pedantic -Wall -Wextra
or, for C99:
gcc -std=c99 -pedantic -Wall -Wextra
(but see <http://gcc.gnu.org/c99status.html> ).

The "-Wextra" option, equivalent to "-W", may give you more warnings
that are really appropriate.

</OT>

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Apr 13 '06 #9
"mwt" <mi*********@gm ail.com> writes:
Ah. I see. If I use the -pendantic option in gcc, it enforces strict
compliance with ISO C90, and won't allow the

int array[size];

declaration.
Interesting.


Please read <http://cfaj.freeshell. org/google/>.

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Apr 13 '06 #10

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

Similar topics

5
8797
by: Ron Adam | last post by:
Hi, I'm having fun learning Python and want to say thanks to everyone here for a great programming language. Below is my first Python program (not my first program) and I'd apreciate any feedback on how I might do things differently to make it either more consice, readable, or faster. ie... are there better ways to do it in Python? It won't break any records for calculating pi, that wasn't my goal, learning Python was. But it might...
30
2146
by: Pieter Provoost | last post by:
Hi, I just made my first c++ program, and I would like to know if there are things I can do better. Also, the exe is about 500 kb, can I make it smaller? Thanks! Pieter
27
3129
by: hokiegal99 | last post by:
Hi Guys, This is my first C program. I started programming in Python. Please look over this source and let me know if I'm doing anything wrong. I want to start out right with C, so if you see anything wrong tell me now while I am learning! Thanks !!! > #include <stdio.h>
13
2125
by: Todd | last post by:
I am curious of the origins of the "Hello World" program. Who was the first to make this popular? That is, where did it start? I did some Google search and did not find an answer. Was it Kerringan and Richie? I no longer have that book and I don't remember if it was in that ubiquitous C book. It was so long ago.
5
5422
by: cj | last post by:
Thanks to everyone that has helped me. Now I'm trying to write my first program. I have an example of one that I need to write about. Any help getting me started is appreciated. I'm having trouble getting my compiler to work, access to my a drive is denied, anyone know why this is? Ok here is the info for my program: The two laws of electricity are used in this program. Law #1 The first is Ohm's Law which relates voltage, curret, and...
16
4811
by: Martin Joergensen | last post by:
Hi, I wanted to try something which I think is a very good exercise... I read in data from the keyboard and store them in a structure. There's a pointer called "data_pointer" which I use to keep track on the structures... But it's a bit confusing - my program won't compile and I don't know what to do about the warnings/error messages. c:\documents and settings\dell\Desktop\test\main.c(5) : warning
7
1759
by: Chris Lasher | last post by:
Hi all, I have a simple script: --- #!/usr/bin/env python a = 1 b = 2
3
419
by: cs | last post by:
Hi, I'm new to C and would appreciate any feedback on the following program, asplit, which splits a file into 2 new files, putting a certain number of lines in the first file, and all the rest in the second file. Any comments as to non-portability, stylistic infelicities, outright bugs or anything else would be very much appreciated.
4
5690
by: Fritjolf | last post by:
Hi. I've got a strange problem... I've made a simple program to test encryption/decryption. I use Rijndael encryption and here are the most important properties. RijndaelManaged cipher = new RijndaelManaged(); cipher.KeySize = 256; cipher.BlockSize = 256;
0
8234
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 usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8677
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. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8620
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 captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8474
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 choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7158
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 launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6110
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 instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4079
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 the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
2605
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
1784
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.