Basics of C programming

Structure of C Program

A C program is divided into different sections. There are six main sections to a basic c program.

The six sections are:

  • Documentation
  • Link
  • Definition
  • Global Declarations
  • Main functions
  • Sub programs

The whole code follows this outline. Each code has a similar outline. Now let us learn about each of these layers in detail.

Documentation Section

The documentation section is the part of the program where the programmer gives the details associated with the program. He usually gives the name of the program, the details of the author, and other details like the time of coding and description. It gives anyone reading the code an overview of the code.

Link Section

This part of the code is used to declare all the header files that will be used in the program. This leads to the compiler being told to link the header files to the system libraries.

Definition Section

In this section, we define different constants. The keyword define is used in this part.

Example:

#define PI= 3.14

Global Declaration Section

This part of the code, where the global variables are declared. All the global variable used are declared in this part. The user-defined functions are also declared in this part of the code.

Example:

float a (float rd);
int x;

Main Function Section

Every C-programs has the main function. Each main function contains 2 parts. A declaration part and an Execution part. The declaration part is the part where all the variables are declared. The execution part begins with the curly brackets and ends with the curly close bracket. Both the declaration and execution part are inside the curly braces.

Example:

void main ()
{
float x=10.9;
printf(“%f”,x);
}

Sub Program Section

All the user-defined functions are defined in this section of the program.

Example:

int sum (int x, int y)
{
Return x+y;
 }

Sample Program

The C program here will find the area of a square.

Example:
File Name: areaofasquare.c
Aim: A C program to find the area of a square ( user enters the value of a side).

#include<stdio.h>
#include<conio.h>
void main()
{
int side,area;
printf(“Enter the value of side”);
scanf(“%d”,&side);
area=side*side;
printf(“The area of a Square is %d”,area);
getch();
}

Basic Data Types

C language provides very few basic datatypes. The datatypes are specified by a standard keyword. The data types are used to define the type of data for particular variable. Various data types that are used in C is enlisted in the following table.

Type Size Range
char 1 byte -127 to 127 or 0 to 255
unsigned 1 byte 0 to 255
signed char 1 byte -127 to 127
int 4 bytes -2147483648 to 2147483647
unsigned int 4 bytes 0 to 4294967295
signed int 4 bytes -2147483648 to 2147483647
short int 2 bytes -32768 to 32767
unsigned short int 2 bytes 0 to 65535
signed short int 2 bytes -32768 to 32767
long int 4 bytes -21147483647 to 2147483647
signed long int 4 bytes -21147483647 to 2147483647
unsigned long int 4 bytes 0 to 4294967295
float 4 bytes +/-3.4e +/-38
double 8 bytes +/-1.7e +/-308
long double 8 bytes +/-1.7e +/-308

Constants:

Constants are identifiers whose value does not change.

Integer type Constant

A constant of integer type consists of a sequence of digits. Example: 1,34,546,8909 etc. are valid integer constants.

Floating point type constant

Integer numbers are inadequate to express numbers that have a fractional point. A floating point constant therefore consists of an integer part, a decimal point, a fractional part, and an exponent field containing an e or E (e means exponents) followed by an integer where the fraction part and integer part are a sequence of digits.

Example: Floating point numbers are 0.02, -0.23, 123.345, +0.34 etc.

Character Constant

A character constant consists of a single character enclosed in single quotes. For example, „a‟, „@‟ are character constants. In computers, characters are stored using machine character set using ASCII codes.

String Constant

A string constant is a sequence of characters enclosed in double quotes. So “a” is not the same as „a‟. The characters comprising the string constant are stored in successive memory locations. When a string constant is encountered in a C program, the compiler records the address of the first character and appends a null character („\0‟) to the string to mark the end of the string.

Declaring Constant

#define PI 3.14159
#define service_tax 0.12

Rules for declaring constant

  • Rule 1: Constant names are usually written in capital letters to visually distinguish them from other variable names which are normally written in lower case characters.
  • Rule 2: No blank spaces are permitted in between the # symbol and define keyword.
  • Rule 3: Blank space must be used between #define and constant name and constant value.
  • Rule 4: #define is a pre-processor compiler directive and not a statement.Therefore, it does not end with a semi-colon.

Variables

A variable is defined as a meaningful name given to the data storage location in computer memory. C language supports two basic kinds of variables

Numeric Variable

Numeric variable can be used to store either integer value or floating point values. While an integer value is a whole number without a fraction part or decimal point a floating point value can have a decimal point.

Numeric variables may also be associated with modifiers like short,long, signed, and unsigned. The difference between signed and unsigned numeric variable is that signed variable can be either negative or positive but unsigned variables can only be positive.

Character Variable

Character variables can include any letter from the alphabet or from the ASCII chart and numbers 0 – 9 that are given within single quotes.

Example:

int emp_num;
float salary;
double balance;

In C variable are declared at three basic places as follows:

  • When a variable is declared inside a function it is known as a local variable.
  • When a variable is declared in the definition of function parameter it is known as formal parameter.
  • When the variable is declared outside all functions, it is known as a global variable

Keywords

Keywords are special reserved words associated with some meaning.

auto double int struct
continue if volatile break
else long switch default
signed while case enum
register typedef do sizeof
char extern return union
for static const float
short unsigned goto void

Operators

C provides a rich set of operators to manipulate data. We can divide all the C operators into the following groups.

  • Arithmetic Operators
  • Unary Operator
  • Relational Operators
  • Logical Operators
  • Assignment Operator
  • Bitwise Operators

Arithmetic Operators

The following table list arithmetic operators.

Operator Description Example
+ Addition A + B
Subtraction A – B
* Multiplication A * B
/ Division A/B
% Modulus A%B

Example to understand Arithmetic operator:

#include<stdio.h>
#include<conio.h>
void main()
{
int a = 10, b=3;
printf("a + b = ", (a + b) );
printf("a - b = ",(a - b) );
printf("a * b = ",(a * b) );
printf("a / b = ",(a / b) );
printf("a % b = ",(a % b) );
}

Output:

a + b = 13
a - b = 7
a * b = 30
a / b = 3 a
a% b = 1

Unary Operators

The following are the unary operators.

Operator Description Example
+ Unary plus operator +A
Unary minus operator -A
++ Increment operator ++A or A++
Decrement operator –A or A–

++ and – – works in two different modes:

  • Pre increment/decrement – When it is part of a statement,increment/decrement gets evaluated first, followed by the execution of the statement.
  • Post increment/decrement – When the operator is part of a statement,the statement gets processed first, followed by increment/decrement operation.

Example for pre increment/decrement:

#include<stdio.h>
#include<conio.h>
void main()
{
int a = 10, b=3;
printf("a++ = ", (a ++) );
printf("a - - = " , (a - -) );
}

Output:

a++ = 11
b-- = 2

Relational Operators

Relational operators are used to test conditions and results for true or false value, The following table lists relational operators.

Operator Description Example
== Two values are checked, and if equal, then the condition becomes true (A == B)
!= Two values are checked to determine whether they are equal or not, and if not equal, then the condition becomes true (A != B)
> Two values are checked and if the value on the left is greater than the value on the right, then the condition becomes true. (A > B)
< Two values are checked and if the value on the left is less than the value on the right, then the condition becomes true (A < B)
>= Two values are checked and if the value on the left is greater than equal to the value on the right, then the condition becomes true (A >= B)
<= Two values are checked and if the value on the left is less than equal to the value on the right, then the condition becomes true (A <= B)

Example to understand Relational operator:

#include<stdio.h>
#include<conio.h>
void main()
{
int a = 10, b=20;
printf("a= = b=", (a ==b) );
printf("a !=b= " , (a!=b) );
printf(“a>b=”,(a>b));
printf(“a>=b=”,(a>=b));
printf(“a<b=”,(a<b));
printf(“a<=b=”,(a<=b))
}

Output:

a == b = false
a != b = true
a > b = false
a <b>= a = true
b <= a = false

Logical Operators

Logical operators are used to combine more than one condition. The following table lists logical operators:

Operator Description Example
&& This is known as Logical AND & it combines two variables or expressions and if and only if both the operands are true, then it will return true (A && B) is false
|| This is known as Logical OR & it combines two variables or expressions and if either one is true or both the operands are true, then it will return true (A || B) is true
! Called Logical NOT Operator. It reverses the value of a Boolean expression !(A && B) is true

Example:

#include<stdio.h>
void main()
{
boolean a = true;
boolean b = false;
printf("a && b = " + (a&&b) );
printf("a || b = " + (a||b) );
printf("!(a && b) = " + !(a && b) );
} 

Output:

a && b = false
a || b = true
!(a && b) = true

Assignment Operator

1. Simple Assignment:
=, assigns right hand side value to left hand side variable.

Example:

int a;
a = 10;

2. Compound Assignment:
+=, -=, *=, /=, %=, &=, |=, ^=, >>=, <<=, assigns right hand side value after the computation to left hand side variable.

Example:

int a;
int b;
a += 10; // means a = a + 10;
a &= b; // means a = a & b;

Bitwise Operators

Bitwise operator act on integral operands and perform binary operations. The lists of bitwise operators are.

Bitwise AND &
Bitwise OR |
Bitwise EXOR ^
Bitwise NOT ~ (unary operator)
Shift Left <<
Shift Ri >>

1. Bitwise AND: The & operator compares corresponding bits between two numbers and if both the bits are 1, only then the resultant bit is 1. If either one of the bits is 0, then the resultant bit is 0.

Example:

int x = 5; int y = 9; x & y = 1
5 - >   0 1 0 1
9 - >   1 0 0 1
           0 0 0 1

2. Bitwise OR: The | operator will set the resulting bit to 1 if either one of them is 1.It will return 0 only if both the bits are 0.

Example:

int x = 5;
int y = 9;
x | y = 13
5 - >    0 1 0 1
9 - >    1 0 0 1
            1 1 0 1

3. Bitwise EXOR: The ^ operator compares two bits to check whether these bits are different. If they are different, the result is 1. Otherwise, the result is 0.This operator is also known as XOR operator.

Example:

int x = 5;
int y = 9;
x | y = 12
5 - >    0 1 0 1
9 - >    1 0 0 1
            1 1 1 0
#include<stdio.h>
void main()
{
int x = 5;
int y = 9;
int a = x & y; int b = x | y; int c = x ^ y;
printf("x & y = "+a);
printf(" x | y = "+b);
printf("x ^ y = "+c);
} 

Output:

x & y = 1
x | y = 13
x ^ y = 12

4. Bitwise NOT: The negation ~ operators complements all the bits, 1 are converted to 0 and 0s are converted to 1s.

Example:

int a =5;
~a = -5
5 ->   0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1
~5 ->  1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 1 0

Shift Operators

The shift operators (<>) shift the bits of a number to the left or right, resulting in a new number. They are used only on integral numbers (and not on floating point numbers, i.e. decimals).

1. Shift Right: The right shift operator(>>) is used to divide a number in the multiples of 2, while the left shift operator(<>) is used to multiply a number in the multiples of 2. For example:

int x = 16; x = x >> 3;

right shift operator >>, divides by 2 to the power of number specified after the operator. In this case, we have 3 as the value after the right shift operator. So, 16 will be divided by the value 2 to the power of 3, which is 8. The result is 2.

When we represent 16 in binary form, we will get the following binary value:

0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0

When we apply >> which is the right shift operator,the positions to the right (represented by the number after the binary digit 1, we will get : bit represented by 1 moves by 3 right shift operator). After shifting:

0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0

2. Shift Left.

Example:

int x = 8;
x = x << 4;

left shift operator <<, multiplies by 2 to the power of number specified after the operator. In this case, we have 4 as the value after the left shift operator. So, 8 will be multiplied by the value 2 to the power of 4, which is 16. The result is 128.

When we represent 8 in binary form, we will get the following binary value:

0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0

When we apply << which is the left shift operator,bit represented by 1 moves by the positions to the left (represented by the number right shift 4 After after the binary digit 1, we will get :operator).

0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0

X=128

#include<stdio.h>
Void main()
{
 int x =8;
 printf("The original value of x is “,x);
 printf("After using << 2, the new value is “,x << 2);
 printf("After using >> 4, the new value is “, x >> 4);
 }

Output:

The original value of x is 8
After using << 2, the new value is 2
After using >> 4, the new value is 128

Expression

An expression is a formula in which operands are linked to each other by the use of operators to compute a value. An operand can be a function reference, a variable, an array element or a constant.

Example:

x = 9/2 + a-b;

Input /Output Statements:

Input means to provide the program with some data to be used in the program and Output means to display data on screen or write the data to a printer or a file.

C programming language provides many built-in functions to read any given input and to display data on screen when there is a need to output the result.

Streams

A stream act in two ways. It is the source of data as well as the destination of the data. C programs input and output data from a stream. It is associated with a physical devices such as the monitor or with a file stored on the secondary memory. C use two forms of streams Text and Binary.

We can do input/output from the keyboard from any file. Consider input of data is the keyboard and output data is the monitor.

Printf() and Scanf () functions

The standard input-output header file, named stdio.h contains the definition of the functions printf() and scanf(), which are used to display output on screen and to take input from user respectively.

#include<stdio.h>
#include<conio.h>
void main()
{
float i;
printf(“Enter the value”);
scanf(“%f”,&i);
printf(“The value is %f=“,i);
getch();
}
Format String Meaning
%d Scan or print an integer as signed decimal number
%f Scan or print a floating point number
%c To scan or print a character
%s To scan or print a character string

Putchar() & getchar() functions

The getchar() function reads a character from the terminal and returns it as an integer.This function reads only single character at a time. The putchar() function displays the character passed to it on the screen and returns the same character.

#include<stdio.h>
void main()
{
char q;
Printf(“Enter a Character”);
q=getchar();
putchar(q);
}

Assignment Statement

An assignment statement sets the value stored in the storage location denoted by a variable_name. In other words, it copies a value into the variable.

Syntax:

variable = expression;

Decision Making Statement

Decision making statements are mainly three type.

  • if
  • if … else
  • if … else … if
  • Simple if

    syntax :

    if(Booleanexpressio)
    {
    statement–block;
    }
    Next statement;
    #includ<stdio.h>
    void main() {
    int n=5;
    if(n<25) {
    printf(“This is if statement”); 
    }
    }

    Output:

    This is if statement

    if … else statement

    Syntax:

    if(boolean expression) {
    True-block statements;
    }
    else {
    False-block statements;
    }
    Next statement;
    #include<stdio.h>
    void main()
    {
    int age;
    printf(“Enter the age”);
    scanf(%d”,&age);
    if(age>18)
    {
    printf(“Eligible to vote”);
    }
    else
    {
    printf(“Not eligible to vote”);
    }
    }

    Cascading if..else

    Syntax:

    if (condition1)
    {
    statement-1
    }
    ...
    else if(conditio-n)
    {
    statement-n
    }
    else
    {
    default statement
    }
    next statement;

    program to find largest three number:

    #include<stdio.h>
    void main()
    {
    int n1,n2,n3;
    printf(“Enter the number”);
    scanf(“%d%d%d”,&n1,&n2,&n3);
    if(n1>n2 && n1>n3)
    {
    printf(“%d is largest number”,n1);
    }
    else If(n2>n3)
    {
    printf(“%d is the largest number”,n2);
    }
    else
    {
    printf(“%d is the largest number”,n3);
    }
    }

    Switch Statement

    The switch-case conditional construct is a more structured way of testing for multiple conditions rather than resorting to a multiple if statement.

    Syntax:

    switch(expression)
    {
    case 1: case 1 block
    break;
    case 2: case 2 block
    break;
    default: default block;
    break;
    }
    statement;

    This is an example of a switch case statement:

    #include<stdio.h>
    Void main()
    {
    int w;
    printf(“Enter the week”);
    scanf(“%d”,&w);
    switch(w)
    {
    case 1:
    printf(“Sunday”);
    break;
    case 2:
    printf(“Monday”);
    break;
    case 3:
    printf(“Tuesday”);
    break;
    case 4:
    printf(“Wednesday”);
    break;
    case 5:
    printf(“Thursday”);
    break;
    case 6:
    printf(“Friday”);
    break;
    case 7:
    printf(“Saturday”);
    break;
    Default:
    Printf(“Invalid input please enter number between (1 – 7)”);
    }
    }

    Looping Statement

    A loop execute the sequence of statements many times until the stated condition becomes false. Looping statements are:

    • for
    • while
    • do … while

    for Loop

    The for loop initialize the value before the first step. Then checking the condition against the current value of variable and execute the loop statement and then perform the step taken for each execution of loop body. For-loops are also typically used when the number of iterations is known before entering the loop.

    Syntax:

    for(initialization; condition; increment/decrement)
    {
    Body of the loop
    }

    This is an example of a for loop:

    #include<stdio.h>
    void main()
    {
    int i;
    for(i=0;i<=5;i++)
    {
    printf(“i:”,i);
    }

    While Loop

    It‟s a entry controlled loop, the condition in the while loop is evaluated,and if the condition is true, the code within the block is executed. This repeats until the condition becomes false.

    Syntax:

    while(condition)
    {
    Body of the loop
    }

    This is an example for a while loop:

    #include<stdio.h>
    void main()
    {
    int i = 0;
    while (i < 5)
    {
    printf("i: “,i);
    i = i + 1;
    }
    }

    Output:

    i: 0
    I: 1
    i: 2
    i: 3
    i: 4

    do … while Loop

    It’s a exit controlled loop, the body of the loop gets executed first followed by checking the condition. Continues with the body if the condition is true, else loops gets terminated.

    Syntax:

    do
    {
    body of the loop
    }
    while(Boolean expression);

    This is an example of a do-while loop:

    #include<stdio.h>
    void main()
    {
    int i=5;
    do
    {
    println("i: “,i);
    i = i + 1;
    }
    while (i < 5);
    }

    Output:

    I: 5

    Pre-processor Directives

    This preprocessor is a macro processor this is used automatically by the C compiler to transform your program before actual compilation. It is called macro processor because it allows you to define macros, which are brief abbreviations of longer constructs. A macro is a segment of code which is replaced by the value of macro. Macro is defined by #define directive.

    Preprocessing directives are lines in your program that start with #. The # is followed by an identifier that is the directive name. For example, #define is the directive that defines a macro. Whitespace is also allowed before and after the #. The # and the directive name cannot come from a macro expansion. For example, if foo is defined as a macro expanding to define, that does not make #foo a valid preprocessing directive.

    Some of the preprocessor directives are:

    • #include
    • #define
    • #undef
    • #ifdef
    • #ifndef
    • #if
    • #else
    • #elif
    • #endif
    • #error
    • #pragma

    #include

    The #include preprocessor directive is used to paste code of given file into current file. It is used include system-defined and user-defined header files.

    #define
    A macro is a segment of code which is replaced by the value of macro. Macro is defined by #define directive.

    Syntax:

    #define token value

    #undef

    To undefine a macro means to cancel its definition. This is done with the #undef directive.

    Syntax:

    #undef token
    #include<stdio.h>
    #define PI 3.1415
    #undef PI
    Main()
    {
    Printf(“%f”,PI);
    }

    #ifdef

    The #ifdef preprocessor directive checks if macro is defined by #define. If yes, it executes the code.

    Syntax:

    #ifdef MACRO
    //code
    #endif

    #ifndef

    The #ifndef preprocessor directive checks if macro is not defined by #define. If yes, it executes the code.

    Syntax:

    #ifndef MACRO
    //code
    #endif

    #if

    The #if preprocessor directive evaluates the expression or condition. If condition is true, it executes the code.

    Syntax:

    #if expression
    //code
    #endif

    #else

    The #else preprocessor directive evaluates the expression or condition if condition of #if is false. It can be used with #if, #elif, #ifdef and #ifndef directives.

    Syntax:

    #if
    //code
    #else
    //else code
    #endif

    #error

    The #error preprocessor directive indicates error. The compiler gives fatal error if #error directive is found and skips further compilation process.

    #include<stdio.h>
    #ifndef _MATH_
    #error First include then compile
    #else
    void main()
    {
    int a;
    a=sqrt(9);
    printf(“%f”,a);
    }
    #endif

    #pragma

    The #pragma preprocessor directive is used to provide additional information to the compiler. The #pragma directive is used by the compiler to offer a machine or operating system features. Different compilers can provide different usage of #pragma directive.

    Syntax:

    #pragma token

    Compilation Process

    The compilation is a process of converting the source code into object code. It is done with the help of the compiler. The compiler checks the source code for the syntactical or structural errors, and if the source code is error-free, then it generates the object code.

    The c compilation process converts the source code taken as input into the object code or machine code. The compilation process can be divided into four steps, i.e., Pre-processing, Compiling, Assembling, and Linking.

    Preprocessor

    The source code is the code that is written in a text editor and the source code file is given an extension “.c”. This source code is first passed to the preprocessor, and then the preprocessor expands this code. After expanding the code, the expanded code is passed to the compiler.

    Compiler

    The code which is expanded by the preprocessor is passed to the compiler. The compiler converts this code into assembly code. Or we can say that the C compiler converts the pre-processed code into assembly code.

    Assembler

    The assembly code is converted into object code by using an assembler. The name of the object file generated by the assembler is the same as the source file. The extension of the object file in DOS is ‘.obj,’ and in UNIX, the extension is ‘o’. If the name of the source file is ‘welcome.c’, then the name of the object file would be ‘hello.obj’.

    Linker

    Mainly, all the programs written in C use library functions. These library functions are precompiled, and the object code of these library files is stored with ‘.lib’ (or ‘.a’) extension.The main working of the linker is to combine the object code of library files with the object code of our program. Sometimes the situation arises when our program refers to the functions defined in other files; then linker plays a very important role in this. It links the object code of these files to our program. Therefore, we conclude that the job of the linker is to link the object code of our program with the object code of the library files and other files. The output of the linker is the executable file. The name of the executable file is the same as the source file but differs only in their extensions. In DOS, the extension of the executable file is ‘.exe’, and in UNIX, the executable file can be named as ‘a.out’. For example, if we are using printf() function in a program, then the linker adds its associated code in an output file.

    Related Post