User Tools

Site Tools


Sidebar

projects

ntr0 (due 20210825)
pct1 (bonus; due 20210819)
wcp1 (due 20210818)
fwf0 (due 20210825)
pct2 (due 20210825)
wcp2 (due 20210825)
sof0 (due 20210901)
pct3 (bonus; due 20210901)
wcp3 (due 20210901)
dow0 (due 20210908)
pct4 (due 20210908)
wcp4 (due 20210908)
cbf0 (due 20210915)
gfo0 (due 20210915)
pct5 (bonus; due 20210915)
wcp5 (due 20210915)
sam0 (due 20210922)
pct6 (due 20210922)
wcp6 (due 20210922)
cnv0 (due 20210929)
pct7 (bonus; due 20210929)
wcp7 (due 20210929)
cnv1 (due 20211006)
pct8 (due 20211006)
wcp8 (due 20211006)
cos0 (due 20211020)
pct9 (bonus; due 20211020)
bwp1 (bonus; due 20211020)
wcp9 (due 20211020)
oop0 (due 20211027)
gfo1 (due 20211027)
pctA (due 20211027)
wcpA (due 20211027)
oop1 (due 20211103)
pctB (bonus; due 20211103)
wcpB (due 20211103)
oop2 (due 20211110)
pctC (due 20211110)
wcpC (due 20211110)
gfo2 (due 20211117)
pctD (bonus; due 20211117)
pctE (bonus; due 20211201)
bwp2 (bonus; due 20211201)
EoCE (due 20211209)
haas:fall2021:cprog:projects:helloworld

Corning Community College

CSCS1320 C/C++ Programming

~~TOC~~

Hello, World! (first program, and development cycle)

It is time to develop and deploy your first program!

Overview

A C program's code is referred to as source code, or the list of instructions indicating what we'd like the computer to do, and is in a more human-readable (and writable) form- the computer cannot natively understand it.

Just as with any language (think English, French, Spanish, LOLspeak, etc.) there is a structure and form- rules indicating how we can arrange various tokens (words, punctuation marks) as well as the particular words themselves (vocabulary).

Different words have different roles in sequences of words (what we'd call a sentence)… there are nouns and verbs and adjectives and adverbs, among others.

In many languages, verbs (the action words) are conjugated to fit the particular case it is being used.

For example:

  • I run down the street. (First person singular, current action)
  • She runs down the street. (Third person singular, current action)
  • They ran down the street. (Third person plural, past action)
  • We will run down the street. (First person plural, future/anticipated action)

Some verbs see only minor spelling changes (run, runs, ran). Others, as a result of language evolution, may see more drastic changes as they are put into context:

  • I go, I went (in older English there were 2 verbs– wend and go, giving us went and gaed for the past tense)

We (should) know this from all our years of experience with our particular known language(s). Even if English isn't your first language, these same sorts of rules hold true- you know how to arrange your given tokens in a way to effectively communicate to others.

And programming is no different: we are learning a foreign language, in this case an intermediary language between a human language (English) and a computer language (Machine Language).

The language we'll be learning is one of the most popular and influential in the realm of computing. It is over 40 years old and is showing no sign of being replaced anytime soon (although many derivatives exist, and some of those derivatives may see statistically higher usage). This language of course is C.

As indicated, C has a number of derivative languages that have been developed over the years. This is very much like learning Latin, then going on to learn one of its derivations (the so-called “Romance Languages”)… the structure is very similar, and a good deal of vocabulary may well be shared.

So it is with C… by learning this “root” language (note that C itself is a derived language), with a little effort you should be able to easily pick up C++ (which we will be exploring later this semester), Java, Objective C, C#, or PHP, to name a few.

C is classified as a structured/procedural/imperative paradigm of programming language (therefore all its derivations are similarly rooted in that paradigm).

To get a taste of some of the various programming paradigms out there, do a google search for programming paradigms. There is also a Wikipedia article on programming paradigms.

Ultimately, we will be focusing on learning imperative programming in C first, and then once we have picked that up effectively, transition to C++ and encounter some of its object-oriented capabilities.

By no means should you consider this the end all, be all of all possible computer programming languages. It may be the most practical and most taught and most encountered for the range of problems you are used to encountering (or have been taught to express solutions in), but it is not everything.

If you are serious in continuing on this path of study in Computer Science, you would do well to learn some additional languages, especially those outside the imperative paradigm, and those with grammars unlike C and its derivatives.

Some recommendations:

  • LISP: a functional language
  • Prolog or Haskell: logical languages
  • Scheme or Eiffel: other object-oriented languages
  • Python: a different grammar than you find in C-like languages, although it has many imperative elements to it.
  • Scripting Languages: if you take the UNIX course, you'll be exposed to bash, which is but one of many. (Python can be considered another)
  • Assembly Language: if you take Computer Organization, you may have the opportunity to learn a particular dialect of assembly language for a given architecture.

As you can see, the realm of languages is vast and can be explored much further.

Why not (just) C++?

Some may question why, if C++ is a derivation of C, and is frequently perceived to be “more popular”/“more widely used” than C, why “waste” the time on C?

The reasoning is this: for all intents and purposes, C++ contains all of C (think of how every square technically falls under the definition of a rectangle), but provides additional syntax and features (it extends the C syntax).

This “added” capability of C++ results in more grammar and syntax and rules that must be learned– more words and grammar and conjugation and punctuation– more noise to the learner approaching the subject.

Also, because one cannot write an “Object-Oriented” C++ program (at least from start to finish by our own hand) without involving ourselves with the imperative details of the solution, we are going to take the simpler approach and focus on C first- learn the basics of how to communicate our solutions to specific problems and familiarizing ourselves with the languages structure.

Once we work through that, we can then better appreciate what C++ has to offer.

Also, learning C first can also set you up to better learn other C-like languages— such as Objective C or Java. In the end, you'll find that the key to learning similar paradigmed languages is not so much the rules as it is the vocabulary (addition keywords, and libraries).

C program structure

As we are to be focusing on learning a particular language this semester (C)

Following is the layout of a typical single-file C program (NOTE that this is not something you should type in- it is more of a diagram, and certainly no working program):

/*
 * programname.c - brief description of what this file's functionality is all about
 *
 * comment block - although not required, makes the code more readable.
 * also- putting a big descriptive comment block like this at the top of the file 
 * really helps you (six months from now) and others quickly ascertain the point 
 * of the program.
 *
 * Note that there are two forms of comments in C/C++... the /* ... */ comment block
 * (which will ignore everything between the opening and closing markers), and the
 * simpler one-lined "//", which will only ignore from that point to the end of the line
 */
 
// Preprocessor directives - import library functionality or define/act on symbols
//
#ifndef SYMBOL
#define SYMBOL
#include <headerfile.h>
 
// Function prototypes (if any)
//
 
// Function definitions (every self-sufficient C/C++ (heck, even Java) program
// needs at least one function which it uses as a starting point. This function 
// needs to be called **main**.
//
int main()
{
   // local variable declarations
 
   // local variable initializations / general initialization
 
   // statements performing some process (this is where the bulk of the action is)
 
   // de-initialization / wrapping things up 
}
#endif

A mistake some people make when approaching programming is that it is “recipe”-based. You cannot just memorize a set of code snippets and copy/paste them to make a working program– just like you cannot do so to be fully conversant in any spoken foreign language (memorizing how to order a beer or get the check is not being conversant).

Similarly, languages (spoken, written, and computer) conceptually represent ideas in ways that may make certain things easier or more difficult to represent.

We use C/C++ because it is an effective means for communicating to the computer for solving a range of problems.

But just like comparing English to Japanese, English and C/C++ do not have a 1:1 idea-mappable translation.

Even with culturally similar languages (like English and Spanish, both being of European origin), each language conceptually represents ideas in different ways. To be fluent/effective in speaking a language, you must understand how to express your idea in terms of that language's structure.

So it is with C/C++. Your native language may be English, but to write effective C/C++ (or any computer) programs, you'll need to develop a sense of idea expression in terms of the destination language. Just knowing the syntax won't cut it (this is the abstract portion of language learning).

It isn't difficult, but needs practice to develop this skill.

Preparing a source directory

Every user on lab46 has their own src/ subdirectory where they can place files generated through coursework.

The purpose of directories is mostly a human satisfying of sanity through organization. While there are mild performance implications, directories help us keep our data sorted (provided we put in the effort to maintain some form of organization).

For this reason, we are going to take one more step and create a custom directory for this class (so you can re-use your src/ directory for additional classes and pursuits).

You can name it whatever you want… for this example I will be running with the name “cprog”.. if you want to use something else feel free (just remember to substitute your name in as appropriate).

Change into src/

First step, we need to change into our src/ directory (note the prompts):

lab46:~$ cd src
lab46:~/src$ 

Create a cprog subdirectory

Now, we're going to create a directory just for our C/C++ program files:

lab46:~/src$ mkdir cprog
lab46:~/src$ 

Change into your cprog directory

Once created, we can change into it:

lab46:~/src$ cd cprog
lab46:~/src/cprog$ 

and voila! If you remember to change into here each time you come to class, or set about working on coursework, all your C/C++ coursework will be nicely organized here (you do not need to recreate the cprog directory– that only needs to be done once).

And, for those really embracing these provided resources, feel free to create additional subdirectories to further organize your code. We'll be creating a lot of programs in here, and even this mild organization isn't enough to ward off a little searching later in the semester as the example programs pile up.

Text Editor

Text editors can be a matter of great personal preference.

Ultimately, they are a fundamental program development tool, for they handle the various low-level file operations, enabling you to place desired content in specified files.

If you are entirely new to lab46 (and don't know any better), I would recommend the use of the nano text editor. It works in a manner consistent to other text entry programs you are likely accustomed.

To open nano on a new or existing file, merely specify the file name after the editor on the command-line. In this example, we will be creating a new file called hello.c in our current working directory:

lab46:~/src/cprog$ nano hello.c

nano is a full screen editor, you'll notice a status bar on the top of the screen, and commands listed on the bottom few rows (^X means to press and hold the CTRL meta key and then hit the “X” key.. this particular example will let you save and exit).

If you have experience in UNIX on the command-line and know of/prefer other editors, feel free to use them.

For those also taking UNIX, you'll be learning the vi text editor, and I would encourage you to use it in as many settings as possible to aid you in your UNIX coursework (if you are not taking UNIX do not concern yourself with vi, it is a powerful editor that works according to a different philosophy).

Hello, World

For our purposes here, we will be writing our first program, which is also considered a classic.

It is simple, but it helps to start simple to understand the parts before adding in more an more details.

Your task is to manually type (please, no copy and paste, you won't be doing yourself any favors in the long run) in this program into a file (perhaps called hello.c) in a text editor:

#include <stdio.h>
 
int main()
{
    printf("Hello, World!\n");
 
    return(0);
}

And that's it. Compare this actual C program to the conceptual C program layout above.

Here is the same program again but with line numbers added (note you do NOT want to type the line numbers, they are to facilitate our navigation of the program):

1
#include <stdio.h>
 
int main()
{
    printf("Hello, World!\n");
 
    return(0);
}

Can you answer the following questions?:

  • Does this code have any preprocessor directives?
    • What line(s)?
    • What does the preprocessor directive do?
  • What line(s) encompass the main() function?
  • Are there any:
    • function prototypes?
    • local variable declarations?
    • initializations taking place?
    • statements performing some process (the “processing”)?
    • de-initialization / wrapping things up steps?
  • What does each keyword, function, or equation do? (hint, there are no equations in this program).
    • What is that printf(), a keyword or a function?
    • What is that return(), a keyword or a function?

We'll be focusing on learning the structure of the language first, and a select quantity of the vocabulary. There is considerably more vocabulary out there that will not directly be touched upon. This usually takes the form of libraries which can be utilized.

Compiling your program

In order for the computer to understand what we have just written (and for us to eventually utilize our program on the computer), we must present it to the computer in a form it can understand.

The journey from C code to executable machine code is a multi-stepped process which is certainly worthy of considerable study. In the scope of this document, however, we will only look at the practical steps (i.e. commands to be issued) to get us from point A to point B. Having a deeper understanding of the process is important, however.

Doing a search for “C program compilation process” may net you some addition information.

While it is by no means complete, here are some slightly expanded descriptions of the process (somewhat ordered from simple to more involved):

The nature of compilers themselves can warrant entire courses unto themselves. If you go on in Computer Science, at the 3rd/4th year or graduate level it is not uncommon to encounter a “Compiler Construction” course.

Familiarize yourself with file states

Before we get to actually compiling, you may want to take a look at the existing state of your working directory, so that you can see the results of your actions.

At this point, you should have just finished typing in your first program (hello.c), saved it, and exited from your text editor and be sitting at a lab46 prompt:

lab46:~/src/cprog$ 

At this point we are going to run the UNIX command ls, which will list all the files in the current directory (your ~/src/cprog/ directory). Depending on any previous or outside activity, you may have additional files kicking about.

lab46:~/src/cprog$ ls
hello.c
lab46:~/src/cprog$ 

Compile the program using gcc

The compiler on Lab46 is the GNU C compiler (gcc command).

To use it on a single file, in this case named hello.c, to create an executable named hello, we would run the following at the prompt:

lab46:~/src/cprog$ gcc -o hello hello.c
lab46:~/src/cprog$ 

A few important points to be aware of:

  • the -o argument specifies the OUTPUT (executable) file. This must NEVER be directly followed by your C source code (if it is, it will eat it and you will be unhappy).
  • The .c file can be before the -o, or well after, just not directly after.
  • gcc, like many UNIX tools, is user-friendly. That is, it assumes you know what you are doing and don't need any help. As such, if everything went A-OK and there were no problems, success is indicated by simply receiving a prompt. If there were any problems, they would be displayed on the screen.

Running the ls command before and after running gcc should show the lack and then presence of the executable.

Executing your compiled program

At this point you should have written your first program in a text editor, saved it, compiled it successfully, and now await the moment of truth- running the very program you just wrote.

While this was very much a packaged example leading you through the process, it will be more-or-less the same each time. Adopting this procedure as a baseline habit will certainly serve you well as we progress in the course.

So now, at the lab46 prompt, let us run our fleshly compiled hello binary:

lab46:~/src/cprog$ ./hello
Hello, World!
lab46:~/src/cprog$ 

And that's it! The development cycle of our first program.

Now we just have to learn all the various keywords and language rules, and familiarize ourselves with the necessary library functions to pull off even more spectacular solutions to problems.

You will want to place your C source code (hello.c) in a repository for safe keeping- working with repositories is another helpful programming habit to have.

Submission

To successfully complete this project, the following criteria must be met:

  • Code must compile cleanly (no warnings or errors)
  • Executed program must display the intended message, exactly as presented, to STDOUT.
  • Output must be correct (as per project specifications)
  • Code must be nicely and consistently indented (you may use the indent tool)
  • Code must be commented
    • have a properly filled-out comment banner at the top
    • have at least 5% of your program consist of //-style descriptive comments
  • Output Formatting (including spacing) of program must conform to the provided output (see sample program output above).
  • Track/version the source code in a repository
  • Submit a copy of your source code to me using the submit tool.

To submit this program to me using the submit tool, run the following command at your lab46 prompt:

$ submit cprog helloworld hello.c
Submitting cprog project "helloworld":
    -> hello.c(OK)

SUCCESSFULLY SUBMITTED

You should get some sort of confirmation indicating successful submission if all went according to plan. If not, check for typos and or locational mismatches.

haas/fall2021/cprog/projects/helloworld.txt · Last modified: 2014/01/27 14:58 by 127.0.0.1