The layout of a C program

The general form of a C program is as follows:

pre-processor directives
global declarations

main()
{
local variables to function main;
statements associated with function main;
}

fun1()
{
local variables to function fun1;
statements associated with function fun1;
}

fun2()
{
local variables to function fun2;
statements associated with function fun2;
}

All C programs will consist of at least one function, but it is usual (when your experience grows) to write a C program that comprises several functions. The only function that has to be present is the function called main. For the more advanced program the main function will act as a controlling function calling other functions in their turn to do a specific work. The main() function is the first function that is called when a C program executes.

Note the use of the bracket set () and {}. The () are used in conjunction with function names whereas {} are used to delimit the C statement that is associated with that function. Also, note that a semicolon (;) is used to terminate the C statement. C is a free format language and long statements can be continued, without truncation, onto the next line. The semicolon informs the C compiler that the end of the statement has been reached. Free-format also means that you can add as many spaces as you like to improve the look of your programs.

A very common mistake made by everyone, who is new to the C programming language, is to miss the semicolon. The C compiler will concatenate the various lines of the program together and then tries to understand them- which it will not able to do. The error message produced by the compiler will relate to a line of your program, which could be some distance from the initial mistake.

Our first C program

Now let us write our first C program as follows

#include<stdio.h>
/*main function starts here*/
void main()
{
printf(“Hello world!\n”);
}

Line by line explanation

Line 1: #include<stdio.h>

As part of the compilation, the C compiler runs a program called the C pre-processor. The pre-processor is able to add and remove code from your source file. In this case, the preprocessor directive #include  tells the compiler to include code from the file stdio.h. this file contains declarations for functions that the program needs to use. A declaration for the printf function is in this file.

Line 2: /*main function starts here*/

This is a comment. A comment is a note to yourself or others that you put into your source code. The compiler ignores all comments. Comments are used primarily to document the meaning and purpose of the source code so that we can remember later how it functions and how to use it. You can also use a comment to temporarily remove a line of code. Simply surround the lines with the comment symbols. In C, the start of a comment is signaled by the /* character and is ended by */.

Line 3: void main()

This statement declares the main function. A C program can contain many functions but must always have one main function. A function is a self-contained module of code that can accomplish some task. The “void” specifies the return type of main. In this case, nothing is returned to the operating system.

Line 4: {

This opening curly bracket denotes the starting of the main function.

Line 5: printf(“Hello world! \n”);

Printf is a function from a standard C library that is used to print strings to the standard output device, normally the screen. The compiler links code from these standard libraries to the code you have written to produce the final executable. The “\n” is a special format modifier that tells the printf to put a line feed at the end of the line. If there were another printf in this program, its string would print on the next line.

Line 6: }

This closing curly bracket denotes the end of the main function.

Type it in a new file and save it as Hello.c. then use the compiler to compile it, the linker to link it and finally run it.

The output is as follows:

Hello World!

Note on Header files and Pre-processor directives

The file in which we find the definition of different built-in library functions is called a header file. If we use any basic input-output functions or any other in-built library functions in a C program then we also have to include the corresponding header file in that C program before the main function starts. Here, in this example, we have included the header file “stdio.h”, because, the definition of the basic output function “printf()” is given in this header file. We will come to know about other header files as we proceed.

As a part of compilation, the C compiler runs a program called the C pre-processor. The preprocessor directives give direction to the compiler that, what to do before compiling a C source code. In this case, the preprocessor directive #include tells the compiler to include the codes from the header file stdio.h. This file contains declarations for functions that the program needs to use. A declaration for the printf function is in this file.

It is already mentioned that C is a free format language and that you can layout your program how you want to use as much white space as you like. The only exception is the statement associated with the pre-processor directives. All preprocessor directives begin with a # symbol and do not use semicolons as delimiters. The most common preprocessor directives to all C programs are:

#include<stdio.h>

Note the use of the angle bracket (< and >) around the header file’s name. these indicate that the header file is to be looked for on the system disk, which stores the rest of the C program application. We can also write the above statement as follows:

#include “stdio.h”

The double quotes indicate that the current working directory should be searched for the required header file. This will be true when you write your own header files. But, the standard header files should always have the angle brackets around them.

The building blocks of a C program

Now we have to start looking into the details of the C language. How easy you find the rest of this section will depend on whether you have ever programmed before- no matter what the language was. There are a great many ideas common to programming in any language and C is no exception to this rule. So if you haven’t programmed before, you need to take the rest of this section slowly and keep going over it until it makes sense.

The basic things we need to know that are required to learn the C programming language are as follows:

  1. Character set
  2. Keywords
  3. Data types
  4. Variables
  5. Constants
  6. Different operators & expressions
  7. Basic I/O statements

Character set

The set of characters we can use in C programs are as follows:

Alphabets a-z, A-Z
Digits 0-9
Special symbols ~`[email protected]#$%^&*()_+{}:”;’<>,./?

Keywords

There are 32 words defined as keywords in C. these have predefined uses and cannot be used for any other purposes such as the naming of a variable or a constant in a C program. They are always written in lower case. A complete list follows which combine with the formal syntax to the form the C programming language.

Auto Double Int Struct
Break Else Long Switch
Case Enum Register Typedef
Char Extern Return Union
Const Float Short Unsigned
Continue For Signed Void
Default Goto Sizeof Volatile
Do If Static While

Data types

Any C program has two entities to consider, the data, and the program. They are highly dependent on one another and careful planning of both will lead to a well planned and well-written program. To handle the data in a C program we create variables to store values in it and in C it is mandatory to mention the type of each of the variables we are going to do anything with it prior to the execution of the program. The data types in C are classified into four categories and they are as follows:

Type Bytes Range Precision
Short int 2 -32768 to +32768
Unsigned short int 2 0 to +65535
Unsigned int 4 0 to +4294967295
Int 4 -2147483648 to +2147483648
Long int 4 -2147483648 to +2147483648
Signed char 1 -128 to +127
Unsigned char 1 0 to +255
Float 4 +/- 1E-37..1E+37 6 digits
Double 8 +/- 1E-37..1E+37 10 digits
Long double 12 +/- 1E-37..1E+37 10 digits

Note: these figures only apply to today’s generation of PCs. Mainframes and midrange machines could use different figures, but would still comply with the rule above.

Variables

A variable is just a named area of the main memory that can hold a single value either numeric or character. In C it is necessary that you declare the name of each variable that you are going to use and its type before you actually try to do anything with it.

Rule for constructing variable name

  • A variable name may be of any length with the combination of digits and alphabets.
  • A variable must be of a specific data type.
  • The first character in the variable name must be an alphabet.
  • No comma or space or special symbols are allowed within a variable name except underscore (_).
  • Uppercase and lowercase letters are distinct.
  • A keyword cannot be used as a variable name.

e.g. int no1; float interest_rate; char choice;

constants

a constant is a value that does not change its value during the execution of the program. There are three techniques used to define constants in C. They are

  1. Using #define
  2. Using const
  3. Using enumerations

Using #define

Constants may be defined using the preprocessor directive #define. The #define directive is used as follows.

#define BELL ‘\a’

Whenever the constant appears in your source file, the preprocessor replaces it by its value. So for instance, every ‘BELL’ in your source code will be replaced by ‘\a’. The compiler will now see the value ‘\a’ in your source code, not “BELL”. Every “BELL” is just replaced by its value. Here is a simple program illustrating the preprocessor directive #define.

#include<stdio.h>
#include<conio.h>
#define BELL ‘\a’
void main()
{
Printf(“Press any key to hear the bell!”);
getch();
printf(“%c”, BELL);
}

Using const

The second technique is to use the keyword const when defining a constant variable. When used the compiler will catch attempts to modify variables that have been declared const.

const float PI=3.1428571428571;

There are two main advantages to the first technique. First, the type of the constant is defined, like here PI is a float type constant. This allows some type checking by the compiler. Second, the constants are variables with a definition scope. The scope of a variable relates to parts of your program in which it is defined.

#include<stdio.h>
void main()
{
const float PI=3.142857142857;
float area, perimeter, radius;
printf(“enter the radius:”);
scanf(“%f”, &radius);
area=PI*radius*radius;
perimeter=2*PI*radius;
printf(“Area=%f sq. unit and perimeter=%f unit”, area, perimeter);
}

Using enumerations

The third technique to declare constants is called enumeration. An enumeration defines a set of constants. In C an enumerator is of type int. the enumeration is useful to define a set of constants instead of using multiple #defines. For example,

enum {“sun”, “Mon”,”Tue”,”Wed”,”Thur”,”Fri”,”Sat”};

This is the definition of an enumeration type (enum). Every one of the word constants will be assigned a numeric value, counting up and starting at 0[*]. So the constants will have the following values:

[*] you can override this default numeric value by adding an explicit=value after the constant; the counting for subsequent constants will then continue from there.

Different operators & expression

Operators: an operator in general is a symbol that operates on certain values or variables of some data types and produces a result.

Expression:  the combination of variables, constants and operators written according to the syntax of the language is called an expression.

Types of operators

  1. Arithmetic operators
  2. Relational operators
  3. Logical operators
  4. Assignment operators
  5. Increment and decrement operators
  6. Conditional operators
  7. Bitwise operators
  8. Comma operator
  9. Other operators

Arithmetic operators

The arithmetic operators perform arithmetical operators can be classified into unary and binary arithmetic operations. The following are the list of arithmetic operators.

Operator Meaning
+ Addition
Subtraction
* Multiplication
/ Division
% modulus

Note: C has no operator for exponential operation.

Relational operators

The relational operators are used to compare arithmetic, logical and character expressions. We often compare two quantities and depending upon that we take a decision. So, these comparisions can be done using relational operators. The expression evaluates to 0 (zero) if the condition false and 1 if it is true. The operators are as follows:

Operator Meaning
Greater than
Less than
<= Greater than or equals to
<= Less than or equals to
== Equals to
!= Not equals to

Logical operators

These operators are used to compare the logical and relational expressions. The operators are as follows:

Operator Meaning
&& Logical AND
|| Logical OR
! Logical NOT

Assignment operators

Generally, the = symbol is called the assignment operator. This operator evaluates the expression on the right side and assigns the resulting value to the variable on the left side. The remaining assignment operators are the compound assignment operators. They allow useful shorthand, where an assignment containing the same left and right-hand sides can be compressed and a list of all the compound assignment operators is as follows:

*= /= %= += =
&= |= ^= >>= <<=

Increment and Decrement operators

These operators are used to increase or to decrease the value of a variable. These are as follows:

Operator Meaning
++ Increase the value by 1
Decrease the value by 1

Note: these operators manifest into two forms,

  1. Postfix/post increment or post decrement

e.g. j++ means assign the value of j and increase the value by 1

k—means assign the value of k and decrease the value by 1

  • Prefix/pre increment or pre decrement

e.g. ++j means to increase the value by             1 and assign the value

–k means to decrease the value by 1 and assign the value of k.

Conditional operator

This operator consists of two symbols, question mark (?) and colon (:). It has three parts – the text expression, true part and false part like,

Text expression ? true part : false part

It assigns either the true part value or the false part value to a variable depending on the test expression.

i = (j>5) ? 2 : 3

here if the value of j is greater than 5 then 2 will be assigned to i otherwise 3.

Bitwise operator

These operators operate on each bit of data. They are used for testing, complementing or shifting of bits to right or left. These are as follows:

Operator Meaning
& Bitwise AND
| Bitwise OR
^ Bitwise XOR
<<  Bitwise shift left
>>  Bitwise shift right
~ Bitwise complement

Comma operator

This operator is used to separate a set of variables. The, symbol is called the comma operator.

Other operators

The sizeof() operator returns the size of the data types of a variable or the no. of bytes occupied by the variable in the memory. Member selection operators (. And ->) are used with structures and unions. Pointer operators (*), Address of operator (&), array subscript ([]), (typecast), etc.

The following lists all C operators in order of their precedence (highest to lowest). Their associativity indicates in what order operators of equal precedence in an expression are applied.

Operator Description Associativity
() [] . -> Parentheses (expression grouping) Brackets (array subscript) Member selection via object  name Member selection via pointer Left-to-right
++ — + – ! ~ (type) * & Sizeof Unary pre-increment/pre-decrement Unary plus/minus Unary logical negation/bitwise complement Unary cast (change type) Deference Address Determine size in bytes Right-to-left
. / % Multiplication/division/modulus Left-to-right
+ – Addition/substration Left-to-right
<< >> Bitwise shift left, bitwise shift right Left-to-right
< <= > >= Relational less than/less than or equal to Relational greater than/greater than or equal to Left-to-right
== != Relational is equal to/is not equal to Left-to-right
& Bitwise AND Left-to-right
^ Bitwise exclusive OR Left-to-right
| Bitwise inclusive OR Left-to-right
&& Logical AND Left-to-right
|| Logical OR Left-to-right
? : Ternary conditional Left-to-right
= += -= *= /= %= &= ^= |= <<= >>= Assignment Addition/subtraction assignement Multiplication/division assignment Modulus/bitwise AND assignment Bitwise exclusive/inclusive OR assignment Bitwise shift left/right assignment Left-to-right
, Comma (separate expression) Left-to-right

Basic Input and Output statements

Usually I/O, input and output, form an important part of any program. To do anything useful your program needs to be able to accept input data and report back your results. In C, the standard library provides routines for input and output. The standard library has functions for I/O that handles input, output, and character and string manipulation. Here, all the input functions described read from standard input and all the output functions described write to standard output. Standard input is usually the keyboard. Standard is usually the monitor.

Formatted output

Printf(): this is a very versatile function for displaying the output. It can handle any basic data type and offers several facilities with which we can specify the way in which the data is to be displayed.

printf(“%d”, x);
printf(“%d %d %f”, x, y, z);

scanf(): this is a very useful function for taking the input from the keyboard. It can handle any basic data type and also offers to take multiple values at a time from the keyboard.

scanf(“%d”, &x);
scanf(“%d %d %f”, &x, &y, &z);
#include<stdio.h>
main()
{
printf(“this is an example of something printed!”);
return 0;
}
#include<stdio.h>
main()
{
float y;
int x;
puts(“enter a float, then an int”);
scanf(“%f%d”, &y, &x);
printf(“\nYou entered %f and %d”, y, x);
return 0;
}

You may also like...

%d bloggers like this: