C Tutorial (2) : Your first C Program

The first program is extremely simple:

/* Prints a message on the screen */
#include <stdio.h>
main()
{
   printf(" @Ji : ");
   printf(" My first program.\n");
   return 0;
}

-----------------------------------------
Output:
 @Ji :  My first program.

Open your programming software and type in the program as listed above.

Actually, of the eight lines in the program, only two—the ones that start with printf—do the work that produces the output. The other lines provide “housekeeping chores”  common to most C programs.

Note : In addition to making sure you don’t type the wrong character, be careful when typing code in a word processor and then copying it to your IDE. You may get errors due to quotes, Smart quotes (“) are created by the word processor (to give that cool slanted look), and the compiler did not recognize them. So if you get errors in programs, make sure the quotes are not the culprit.

C isn’t picky about everything. For instance, most of the spacing you see in C programs makes the programs clearer to people, not to C.  As you program, add blank lines and indent sections of code that go together to help the appearance of the program and to make it easier for you to find what you are looking for.

C requires that you use lowercase letters for all commands and predefined functions.
About the only time you use uppercase letters is on a line with #define and inside the printed messages you write.

The main() Function

The most important part of a C program is its main() function. Although at this point the distinction is not critical, main() is a C function, not a C command. A function is nothing more than a routine that performs some task.  Some functions come with C, and some are created by you. C programs are made up of one or more functions. Each program must always include a main() function.

A function is distinguished from a command by the parentheses that follow the function name.

These are functions:
 main() calcIt() printf() strlen()
and these are commands:
 return while int if float

Note : One of the functions just listed, calcIt(), contains an uppercase letter. However, the preceding section said you should stay away from uppercase letters. If a name has multiple parts, as in doReportPrint(), it’s common practice to use uppercase letters to begin the separate words, to increase readability. (Note : Spaces aren’t allowed in function names.)

The required main() function and all of C’s supplied function names must contain
lowercase letters. You can use uppercase for the functions that you write, but most
C programmers stay with the lowercase function name convention.

Just as the home page is the beginning place to surf a website, main() is always the first place the computer begins when running your program. Even if main() is not the first function listed in your program, main() still determines the beginning
of the program’s execution.

After the word main(), you always see an opening brace ({). When you find a matching closing brace (}), main() is finished. You might see additional pairs of braces within a main() function as well.

Data types

Your C programs must use data made up of numbers, characters, and words; programs process that data into meaningful information. Although many different kinds of data exist, the following three data types are by far the most common used in C programming:

  • Characters
  • Integers
  • Floating points (also called real numbers)

You have to understand data types so that you will know how to choose the correct type when your program needs it.

Characters

A C character is any single character that your computer can represent. Your computer knows 256 different characters. Each of them is found in something called the ASCII table, “The ASCII Table.”  Anything your computer can represent can be a character. Any of the following can be considered characters:
A    a    4    %    Q     !    +    =    ]

The American National Standards Institute (ANSI), which developed ANSI C, also developed the code for the ASCII chart.

Even the spacebar produces a character. Just as C needs to keep track of the letters of the alphabet, the digits, and all the other characters, it has to keep track of any blank spaces your program needs.
As you can see, every letter, number, and space is a character to C. Sure, a 4 looks like a number, and it sometimes is, but it is also a character. The plus sign (+) is a character, but the plus sign also performs addition.

All of C’s character data is enclosed in apostrophes (‘). Some people call apostrophes single quotation marks. Apostrophes differentiate character data from other kinds of data, such as numbers and math symbols. For example, in a C program, all of the following are character data:

‘A’      ‘a’     ‘4’      ‘%’     ‘ ‘      ‘-‘

Note: None of the following are valid characters. Only single characters, not multiple characters, can go inside apostrophes.
‘C is fun’
‘C is hard’

The first program contains the character ‘\n’. At first, you might not think that \n is a single character, but it’s one of the few two-character combinations that C interprets as a single character. This will make more sense later. If you need to specify more than one character (except for the special characters that you’ll learn, like the \n just described), enclose the characters in quotation marks (“). A group of multiple characters is called a string. The following is a C string:
“C is fun to learn.”

Numbers (Integers & Floating-point)

Your C program must have a way to store numbers, no matter what the numbers look like. You must store numbers in numeric variables. Before you look at variables, a review of the kinds of numbers will help.

Whole numbers are called integers. Integers have no decimal points. Any number
without a decimal point is an integer. All of the following are integers:
10    54    0    –121    –68    752

NOTE: Never begin an integer with a leading 0 (unless the number is zero), or C will think you typed the number in hexadecimal or octal. Hexadecimal and octal, sometimes called base-16 and base-8, respectively, are weird ways of representing numbers. 053 is an octal number, and 0x45 is a hexadecimal number. If you don’t know what all that means, just remember for now that C puts a hex on you if you mess around with leading zeroes before integers.

Numbers with decimal points are called floating-point numbers. All of the following are floating-point numbers:
547.43       0.0          0.44384             9.1923         –168.470         .22
As you can see, leading zeroes are okay in front of floating point numbers.

The choice of using integers or floating-point numbers depends on the data your programs are working with. Some values (such as ages and quantities) need only integers; other values (such as money amounts or weights) need the exact amounts floating-point numbers can provide.

Internally, C stores integers differently than floating-point values. As you can see from Figure below, a floating-point value usually takes twice as much memory as an integer. Therefore, if you can get away with using integers, do so—save floating points for values that need the decimal point.

memory

Integers take less memory than floating-point values, no matter how large or small
the values stored there are. On any given day, a large post office box might get much less mail than a smaller one. The contents of the box don’t affect what the box is capable of holding. The size of C’s number storage is affected not by the value of the number, but by the type of the number.

Different C compilers use different amounts of storage for integers and floating-point values. As you will learn later, there are ways of finding out exactly how much memory your C compiler uses for each type of data.

Another sample code

At this point, don’t worry about the specifics of the code you see. Practice will increase your coding confidence! So here is a second program, one that uses the data types you just covered:

/* A Program that Uses the Characters, Integers, and Floating-Point Data Types */
#include <stdio.h>
main()
{
printf("@Ji \nI am learning the %c programming language\n", 'C');
printf("I have just completed tutorial %d\n", 2);
printf("I am %.1f percent ready to move on ", 99.9);
printf("to the next chapter!\n");
return 0;
}

Output
------------
@Ji
I am learning the C programming language
I have just completed tutorial 2 
I am 99.9 percent ready to move on to the next chapter!

This short program does nothing more than print three messages on screen. Each
message includes one of the three data types mentioned in this chapter: a character
(C), an integer (2), and a floating-point number (99.9).

Assignment : Try playing around with the program, changing the messages or data. You should even try making a mistake when typing, like forgetting a semicolon (;) at the end of a line, just to see what happens when you try to compile the program. Learning from mistakes can make you a better programmer!

C Programming < Prev                                                          Next > Comments in C code

Advertisements

2 comments

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s