Introduction to C

 

C

Introduction – C was an offspring of the “BASIC COMBINED PROGRAMMING LANGUAGE (BCPL) "called B, developed in 1960’s at the Cambridge University.

B language was modified by Dennis Ritchie and implemented at Bell laboratories in 1972. The new language was named C. Since it was developed along with the UNIX operating system, it is strongly associated with UNIX. UNIX was also developed at Bell laboratories and was almost entirely coded in C.

C is general purpose structured programming language and it combines the features of High Level programming language with the elements of assemblers. Thus, it is close to both man and machine, in this context, C is considered a middle level programming language.

 

Structured Programming -Structured programming (sometimes known as modular programming) follows a top-down approach, in which programmer separates the overall program structure into different subsections.

Advantages of Structured Programming

Reduced Complexity

Easy to Code

Take less time

Easy to debug

Reuse of modules

Flow of control is clear

 

Features of C Language

Structured

Middle Level Language

Case Sensitive

Extendable

Types of C language :

There are two different types of C languages:

a.                 Common C

b.                 American National Standard Institute (ANSI) C

 

Characteristics of C:

a.          C can  be used to develop both system and application programs.

b.         It has enough numbers of in-built functions and operators and a variety of data types to represent different kinds of data.

Advantages of C language :

a.                 Program of C are easy to read and maintain

b.                 Programs are easy to port across different computer platforms.

 

Data types supported by C:

All C compilers support four basic data types

a.                 Integer (int)

b.                 Character (char)

c.                  Floating point (float)

d.                 Double precision floating point (double)

*note* Except the basic data types there are many derived data type

Examples of Derived Data Types – Arrays, Pointers, Structure, Unions,  Enums, (Enum erations)

i)                   Integer (int)- An Integer is a whole number either positive, negative or zero but no decimal values. For example, 0, -5, 10

Declaring an integer variable

int a,b

 In the above example, the int keyword is used to declare a and b as integer variables


ii)                float -It accepts Floating point values.

Declaring float type variable

float b; b = 1.732

 

iii)              double- It also accepts the real numbers like float data type but its range is higher than float data type

Declaring double type variable

double x;

x = 67823.34456;

 

iv)              char- It holds only one character at a time.

Declaring char type variable

char m;

v)                void – void data type has no value. Void does not return a value.

 

Variable in C language: In C language you need to declare variables explicitly. Declaration of a variable specifies its data type and name.

int x = 5; ( here int is data type, x is variable name and 5 is the value)

float pi=3.14; (here float is data type, pi is variable name and 3.14 is the value)

char grade = “t” ; ( here char is data type, grade is variable name and t is text value.

A variable name can be up-to 31 characters long.

 

Constant – Constant is a value that cannot change during program execution. The types of constant c supports are

Integer constant

Real constant

Character constant

String constant

  

C Token - C tokens are the basic buildings blocks in C language which are constructed together to write a C program. Each and every smallest individual unit in a C program are known as C tokens. C tokens are of six types.

They are:

a) Keywords (eg: int, while),

b) Identifiers (eg: main, total)

c) Constants (eg: 10, 20),

 d) Strings (eg: “total”, “hello”)

e) Special symbols (eg: (), {}),

f) Operators (eg: +, /,-,*)

 

C keywords (reserved word)- Keyword is a set of special words which are already defined for some tasks. C has only a set of 32 keywords, which have their predefined meaning and cannot be used as a variable name. These words are also known as “reserved words”.

Example of keywords – auto, int, char, void, short, long, unsigned etc.

 

Identifiers -Identifiers are the names given to the entities such as variables, functions, arrays structures and unions.

For example

int price;

float total;

Here, price and total are called identifiers

Rules for naming Identifiers:

i)                   The Identifier must start with an alphabet or an under score (_).

ii)                Identifier can be made from the combination of alphabets, digits and under score.

iii)              Not any C keyword can be used as an Identifier.

iv)              Identifier must be unique and can be used for a single purpose only.

 

C character set:

A character set denotes any alphabet, digit or special symbol used to represent information. The C character set consist of alphabets, upper case and lower case, the digits 0 – 9 and certain special symbols ( + , -, {, }, & ). These are valid characters and can be used as building blocks to construct basic program elements.

Format Specifier- The format specifier is used during input and output operation. It tells the compiler what  type of data is stored in a variable during the input and output operation such as taking data from keyboard and display data on the screen. Some examples are

Variable or Data Type

Format Identifier

Char

%c

Int

%d

long int

%ld

Float

%f

 

Operators used in C language:

The operators used in C language are: 

i.                        Arithmetic operator (+, -, *, /, %) (a-b)

ii.                      Relational operator (= =, < , >, <=, >=, !=) ( x<y)

iii.                    Logical operator   (&&(AND), ( || (OR), ( ! (NOT) ( a&&b) (a||b) (!a)

iv.                     Assignment operator ( =, +=, -=, *=, /=, %=)

v.                        Unary operator

vi.                     Conditional operator. ( a>b ?a:b)

 

Header files While writing program in C, we need to include different header files in the beginning. Different library functions are used to do different tasks in C language. For example, we use scanf() function to ask data from keyboard. Each function is defined in a special type of file. These files are called Header File and have extension .h. These header files must be included using #include directive otherwise the compiler doesn’t understand the library function we use and gives an error message. Examples of some header files – stdio.h, string.h, math.h, ctype.h etc.

Library files- the functions which are declared on header files such as stdio.h are known as library files.

Here is the list of some commonly used Header file and their purposes:

Header Files

Purpose

Functions Declared

stdio.h

Used for standard input and output (I/O) operations.

printf(), scanf(), getchar(), putchar(), gets(), puts(), getc(), putc(), fopen, fclose(), feof()

conio.h

Contains declaration for console I/O functions.

clrscr(), exit()

ctype.h

Used for character-handling or testing characters.

isupper(), is lower, isalpha()

math.h

Declares mathematical functions and macros.

pow(), squr(), cos(), tan(), sin(), log()

stdlib.h

Used for number conversions, storage allocations.

rand(), srand()

string.h

Used for manipulating strings.

strlen(), strcpy(), strcmp(), strcat(), strlwr(), strupr(), strrev()

 

C program structure

A C program basically consists of

·        Preprocessor commands

·        Functions

·        Variables

·        Statements and expressions

·        Comments.

 

Rules to develop C program

·        C statements are entered in lower case.

·        Every C statement ends with a semicolon (;)

·        # include is a directive/preprocessor statement and must be used at the beginning of the program

·        C program must start with main () function. This is the entry point of the program

·        In C language, each function is defined inside parenthesis { }

 

Source file -------------> object file --------------------->executable file

C              compile              .obj               linker                  .exe

 

C is entirely functional language and the primary function should be named as main ()

 

C program structure 

# include <header file>

main ()

{

Set of statements

---------------------------- ;

--------------------------- ;

-------------------------- ;

}

 

Example 1.

# include <stdio.h> /*creates programming environment by including the needed header                                     files)*/

main ()        /*(begins execution of the program)*/

{                  /*(denotes the beginning of set of functions)*/

printf (“hello world”) ;

}

The output of the program – hello world

Explanation of the program:

# include – (# include is the first word of any C program, it is also known as pre-processor or directive. The function of pre processor is to initialize the environment of program, i.e. to link the program with the header file.

Header file <stdio.h>- header file is a collection of library or built in functions that helps us code in C. Header files contain definitions of functions and variables which can be incorporated into any C program by pre processor # include statement.

main ()- main () is a function that must be used in every C program, main function begins the execution of the program

printf () - it is a standard library function to display data on screen.

scanf () – It allows to accept input from the keyboard.

*note* -

Each C statement must be terminated by a semicolon(;).

/* comments */ - used to write comments similar to REM in Qbasic.


Example 2.

# include <stdio.h>

main ()

{

printf (“hello world\n”) ;          /* for new line \n */

printf (“good morning\”) ;      

}

 

The output of the program – hello world

     good morning

 

example 3.

/*program to find sum of two values */

# include <stdio.h>

main ()

{

int x;

int y;

int z;

x=5;

y=6;

z=x+y;

printf (“\n the result is %d”,z);

}

 

example 4

/* program to find the sum of two numbers accepting input from the user */

 #include <stdio.h>

#include <conio.h>

void main()

{

clrscr()

int a,b,c;

printf ("Enter the first number ");

scanf("%d",&a);

printf ("Enter the second number ");

scanf("%d",&b);

c=a+b;

printf("Sum = %d",c);

getch();

}

*note*-The above C program asks any two numbers from the keyboard and displays their sum. In this program, three variables a,b and c are used and their types are declared as integer (int). Unlike QBASIC, we need to declare the type and name of the variables in the beginning of the program


Example 5

/* To find the product of any two numbers */

 #include <stdio.h>

#include <conio.h>

void main()

{

int a,b,c;

printf ("Enter the first number ");

scanf("%d",&a);

printf ("Enter the second number ");

scanf("%d",&b);

c=a*b;

printf("product = %d",c);

getch();

}

  

Example 6.

/* to accept character */

#include <stdio.h>

#include <conio.h>

void main()

{

char ch;

clrscr();

ch=getch();

printf("The typed character is %c.",ch);

getch();

 }

 

Example 7

/*program to accept string */

 #include <stdio.h>

#include  <conio.h>

void main()

{

char name [20] ;

char add [30] ;

printf ("enter your name ");

scanf ("%s",name);

printf ("%s",name);

printf (“enter address”); 

scanf ("%s”, add);

printf ("%s",add);

getch();

}

 

Example 8 of Arithmetic Calculation

 /* Calculate area and volume of a room*/

 #include <stdio.h>

 #include <conio.h>

void main()

{

clrscr();

int l,b,h,a,v;

printf ("Type length, breadth and height ");

scanf ("%d%d%d",&l,&b,&h);

a=l*b;

 v=l*b*h;

printf("\nArea=%d",a);

printf ("\nVolume=%d",v);

getch();

}

 

Example 9 of Arithmetic Calculation  

/* Calculate total marks and percentage */

 #include <stdio.h>

#include <conio.h>

 void main()

 {

clrscr();

int e,m,c,t;

float p;

printf("Marks in English, Math & Computer ");

scanf("%d%d%d",&e,&m,&c);

t=e+m+c; p=t/3; //Full mark for all subject is 100

printf("\nTotal Marks = %d ",t); printf("\nPercentage = %f ",p);

 getch();

}

 

Control structures in C

C supports three types of basic control structures, which are used to alter the flow of execution of the program.

a) Sequence structure (straight line paths)

b) Selection structure (one or many branches)

c) Loop structure (repetition of a set of activities)

 

a) Sequential Structure- In sequential structure, the statements are executed one after another sequentially from top to bottom without changing the flow of program.

 

b) Selection Structure- It is also called branching structure. In this structure, the control of the program is transferred from one part of the program to another on the basis of specified condition or without condition.

 

c) Looping Structure- Looping is the process of repeating the execution of a statement or a block of statements guided by a condition. A loop is terminated when the given condition is satisfied.

 

if statement- if statement is used to test one or more condition and execute statement(s) if the given condition is True.

Syntax: if (condition)

{

statements …………………

}

If the condition mentioned in the syntax is True, then the statements written inside the parenthesis { } will be executed.

 

Example of if statement

#include <stdio.h>

#include <conio.h>

void main()

{

int a;

printf ("Type your marks ");

scanf ("%d",&a);

if(a>=40)

{

printf ("You are Pass");

printf ("\nCongratulations!!!");

}

getch();

}

 

if … else statement-This statement is used to check one or more condition and execute the condition either the condition is True or False.

Syntax : if (condition)

{

statements …………..

 }

Else

{

statements …………..

}

Example of if ....else  statement

#include <stdio.h>

#include <conio.h>

void main()

{

int a;

clrscr();

printf ("Type your marks ");

scanf ("%d",&a);

if(a>=40)

{

printf ("You are Pass");

}

Else

{

printf ("You are Fail");

}

getch();

}

 

Example of Logical Calculation #1

/*Check ODD or EVEN*/

 #include <stdio.h>

#include <stdio.h>

void main()

{

clrscr();

int n;

printf("Type any number ");

scanf("%d",&n);

if (n%2==0)

printf ("\nIt is even.");

}

else

{

printf ("\nIt is odd.");

}

getch();

}

 

Example of Logical Calculation #2

/* Find the GREATER number */

 #include <stdio.h>

#include <conio.h>

int main()

{

clrscr();

int a,b;

printf("Type first number ");

scanf("%d",&a);

printf("Type second number ");

scanf("%d",&b);

if(a>b)

{

printf("Greater number is %d ",a);

}

else

{

printf("Greater number is %d ",b);

} getch();

return 0;

}

 

Looping in C

The looping statement allows a set of instructions to be performed repeatedly until a certain condition is fulfilled. The looping statements are also called iteration statements.

Looping statements in C

C provides three kinds of loops:

i)                   while loop

ii)                do loop

iii)              for loop

 

i)                   while loop -The while loop continues executing a block of code till the given condition is t rue. The loop will be terminated when the condition becomes false.

 

Example: of while loop

#include <stdio.h>

#include <conio.h>

void main()

{

int num=1;

clrscr();

while (num<=10);

{

printf ("%d ",num);

num++;

 }

getch();

}

 

ii)                do loop - The do loop also executes a block of code as long as a condition is satisfied. The difference between a "do" loop and a "while" loop is that the while loop tests its condition before the execution of loop; the "do" loop tests its condition after the execution of loop.

Example of do loop

#include <stdio.h>

#include <conio.h>

void main()

{

int num=1;

clrscr();

do

{

printf ("%d ",num);

num++;

}

while (num<=10);

getch();

}

 

for loop- The for loop can execute a block of code for a fixed number of repetitions. It is easy to use and defined in a single statement.

 

Example of for loop

#include <stdio.h>

#include <conio.h>

void main()

{

clrscr();

int c;

for (c=1;c<=10;c++)

{

printf ("%d ",c);

}

getch();

 }

 

Program to generate Fibonacci series

//Fibonocci series 1 2 3 5 8 13 ...

#include <stdio.h>

#include <conio.h>

void main()

{

clrscr();

 int a=1,b=2,c,n=1;

do

 {

printf ("%d ",a);

c=a+b; a=b; b=c;

n++;

}

while (n<=10);

getch();

 }

 

//program to Check PRIME or COMPOSITE

#include <stdio.h>

#include <conio.h>

void main()

{

clrscr();

 int n,i,c=0;

printf ("Type any number ");

scanf ("%d",&n);

for (i=2;i<=n-1;i++)

{ if(n%i==0) c++;

}

if (c==0)

printf("The number is prime. ");

else

printf("The number is composite. ");

getch();

}

 

Similarity between C and Qbasic:

i.                        Both language can be used to develop structured programs.

ii.                        Both languages support local and global variables as well as procedures.

 

Differences between C and Qbasic

i.            Qbasic is a high level language whereas C is considered a middle level language.

ii.     Qbasic is used for developing elementary application programs whereas C can be used to develop both system and application software.   

iii.       C has 32 keywords whereas qbasic uses 163 or more keywords.

 

 

Comments

Popular posts from this blog

Grade8 Programming Concepts

Elementary Programming Concepts