Sie sind auf Seite 1von 16

PROGRAMMING

IN

C
WHAT IS C

C is a general-purpose, high-level language that was originally developed by


Dennis M. Ritchie to develop the UNIX operating system at Bell Labs. C was
originally first implemented on the DEC PDP-11 computer in 1972.
In 1978, Brian Kernighan and Dennis Ritchie produced the first publicly available
description of C, now known as the K&R standard.
The UNIX operating system, the C compiler, and essentially all UNIX application
programs have been written in C. C has now become a widely used professional
language for various reasons:
 Easy to learn
 Structured language
 It produces efficient programs
 It can handle low-level activities
 It can be compiled on a variety of computer platforms

HISTORY OF C

 C was invented to write an operating system called UNIX.


 C is a successor of B language which was introduced around the early 1970s.
 The language was formalized in 1988 by the American National Standard Institute (ANSI).
 The UNIX OS was totally written in C.
 Today C is the most widely used and popular System Programming Language.
 Most of the state-of-the-art software have been implemented using C.
 Today's most popular Linux OS and RDBMS MySQL have been written in C.

WHY USE C?

C was initially used for system development work, particularly the programs that
make-up the operating system. C was adopted as a system development
language because it produces code that runs nearly as fast as the code written
in assembly language. Some examples of the use of C might be:

 Operating Systems Language Compilers


 Assemblers
 Text Editors
 Print Spoolers
 Network Drivers
 Modern Programs
 Databases
 Language Interpreters
 Utilities

C PROGRAMS

A C program can vary from 3 lines to millions of lines and it should be written
into one or more text files with extension ".c"; for example, hello.c. You can
use "vi", "vim" or any other text editor to write your C program into a file.
This tutorial assumes that you know how to edit a text file and how to write
source code inside a program file.
THE C COMPILER

The source code written in source file is the human readable source for your
program. It needs to be "compiled" into machine language so that your CPU can
actually execute the program as per the instructions given.
The compiler compiles the source codes into final executable programs. The
most frequently used and free available compiler is the GNU C/C++ compiler,
otherwise you can have compilers either from HP or Solaris if you have the
respective operating systems.
The following section explains how to install GNU C/C++ compiler on various OS.
m We keep mentioning C/C++ together because GNU gcc compiler works for
both C and C++ programming languages.

TOKENS IN C

A C program consists of various tokens and a token is either a keyword, an


identifier, a constant, a string literal, or a symbol. For example, the following C
statement consists of five tokens:

printf("Hello, World! \n");

SEMICOLONS

In a C program, the semicolon is a statement terminator. That is, each individual


statement must be ended with a semicolon. It indicates the end of one logical
entity.
Given below are two different statements:

printf("Hello, World! \n");


return 0;

COMMENTS

Comments are like helping text in your C program and they are ignored by the
compiler. They start with /* and terminate with the characters */ as shown
below:

/* my first program in C */

You cannot have comments within comments and they do not occur within a
string or character literals.

IDENTIFIERS

A C identifier is a name used to identify a variable, function, or any other userdefined


item. An identifier starts with a letter A to Z, a to z, or an underscore ‘_’
followed by zero or more letters, underscores, and digits (0 to 9).
C does not allow punctuation characters such as @, $, and % within identifiers.
C is a case-sensitive programming language. Thus, Manpower and manpower
are two different identifiers in C. Here are some examples of acceptable
identifiers:

mohd zara abc move_name a_123


myname50 _temp j a23b9 retVal
KEYWORDS

The following list shows the reserved words in C. These reserved words may not
be used as constants or variables or any other identifier names.

auto else long switch


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

WHITESPACE IN C

A line containing only whitespace, possibly with a comment, is known as a blank


line, and a C compiler totally ignores it.
Whitespace is the term used in C to describe blanks, tabs, newline characters
and comments. Whitespace separates one part of a statement from another and
enables the compiler to identify where one element in a statement, such as int,
ends and the next element begins. Therefore, in the following statement:

int age;
there must be at least one whitespace character (usually a space) between int
and age for the compiler to be able to distinguish them. On the other hand, in
the following statement:

fruit = apples + oranges; // get the total fruit

no whitespace characters are necessary between fruit and =, or between = and


apples, although you are free to include some if you wish to increase readability.

DATA TYPES

Data types in C refer to an extensive system used for declaring variables or


functions of different types. The type of a variable determines how much space
it occupies in storage and how the bit pattern stored is interpreted.
The types in C can be classified as follows:

INTEGER TYPES

The following table provides the details of standard integer types with their
storage sizes and value ranges:
FLOATING-POINT TYPES

The following table provides the details of standard floating-point types with
storage sizes and value ranges and their precision:

CONSTANTS AND LITERALS

Constants refer to fixed values that the program may not alter during its
execution. These fixed values are also called literals.
Constants can be of any of the basic data types like an integer constant, a
floating constant, a character constant, or a string literal. There are enumeration
constants as well.
Constants are treated just like regular variables except that their values cannot
be modified after their definition.

CHARACTER CONSTANTS

Character literals are enclosed in single quotes, e.g., 'x' can be stored in a
simple variable of char type.
A character literal can be a plain character (e.g., 'x'), an escape sequence (e.g.,
'\t'), or a universal character (e.g., '\u02C0').
There are certain characters in C that represent special meaning when preceded
by a backslash, for example, newline (\n) or tab (\t). Here, you have a list of
such escape sequence codes:

STRING LITERALS

String literals or constants are enclosed in double quotes "". A string contains
characters that are similar to character literals: plain characters, escape
sequences, and universal characters.
You can break a long line into multiple lines using string literals and separating
them using whitespaces.
Here are some examples of string literals. All the three forms are identical
strings.
"hello, dear"
"hello, \
dear"
"hello, " "d" "ear"

DEFINING CONSTANTS

There are two simple ways in C to define constants:


· Using #define preprocessor
· Using const keyword

THE #DEFINE PREPROCESSOR

Given below is the form to use #define preprocessor to define a constant:


#define identifier value
The following example explains it in detail:
#include <stdio.h>
#define LENGTH 10
#define WIDTH 5
#define NEWLINE '\n'
int main()
{
int area;
area = LENGTH * WIDTH;

printf("value of area : %d", area);


printf("%c", NEWLINE);
return 0;
}

THE CONST KEYWORD

You can use const prefix to declare constants with a specific type as follows:
const type variable = value;
The following example explains it in detail:
#include <stdio.h>
int main()
{
const int LENGTH = 10;
const int WIDTH = 5;
const char NEWLINE = '\n';
int area;
area = LENGTH * WIDTH;
printf("value of area : %d", area);
printf("%c", NEWLINE);
return 0;
}
DECISION MAKING LOOP

If statement is a conditional branching statement. In conditional branching statement a condition is evaluated, if it


is evaluate true a group of statement is executed. The simple format of an if statement is as follows:
if (expression)
statement;
If the expression is evaluated and found to be true, the single statement following the "if" is executed. If
false, the following statement is skipped. Here a compound statement composed of several statements bounded
by braces can replace the single statement.
Here's an example program using simple if statement:

#include<stdio.h>
#include<conio.h>
int main()
{
int number;
clrscr();
printf(“enter a number\n”);
scanf(“%d”,&number);
if(number>0)
printf(“given number is positive\n”);
getch();
return 0;
}

IF ELSE STATEMENT:
This feature permits the programmer to write a single comparison, and then execute one of the two statements
depending upon whether the test expression is true or false. The general form of the if-else statement is

if(expression)
statement1
else
statement2

Here also expression in parentheses must evaluate to (a boolean) true or false. Typically you're
testing something to see if it's true, and then running a code block(one or more statements) if it is true, and
another block of code if it isn't. The statement1 or statement2 can be either simple or compound statement.
The following program demonstrates a legal if else statement:

#include<stdio.h>
#include<conio.h>
int main()
{
int number;
clrscr();
printf(“enter a number\n”);
scanf(“%d”,&number);
if(number==0)
printf(“given number is Zero\n”);
else
printf(“given number is not Zero\n”)
getch();
return 0;
}

You can set up an if-else statement to test for multiple conditions. The following example uses two conditions so
that if the first test fails, we want to perform a second test before deciding what to do:
if (x%2==0)
{
printf(“x is an even number”);
}
else
{
if (x>10)
{
printf(“x is an odd number and greater than 10”);
}
else
{
printf(“x is an odd number and less than 10”);
}
}
This brings up the other if-else construct, the if, else if, else. This construct is useful where two or
more alternatives are available for selection.
The syntax is
if(condition)
statement 1;
else if (condition)
statement 2;
.....................
.....................
else if(condition)
statement n-1;
else
statemens n ;
The various conditions are evaluated one by one starting from top to bottom, on reaching a condition
evaluating to true the statement group associated with it are executed and skip other statements. If none of
expression is evaluate to true, then the statement or group of statement associated with the final else is executed.
The following program demonstrates a legal if-elseif-else statement:

#include<stdio.h>
#include<conio.h>
int main()
{
int number;
clrscr();
printf(“enter a number\n”);
scanf(“%d”,&number);
if(number==0)
printf(“given number is Zero\n”);
else if(number>0)
printf(“given number Postive\n”);
else
printf(“given number is negative\n”);
getch();
return 0;
}

UNION
Union is a data type with two or more member similar to structure but in this case all the members
share a common memory location. The size of the union corresponds to the length of the largest member. Since
the member share a common location they have the same starting address.
The real purpose of unions is to prevent memory fragmentation by arranging for a standard size for
data in the memory. By having a standard data size we can guarantee that any hole left when dynamically
allocated memory is freed will always be reusable by another instance of the same type of union. This is a natural
strategy in system programming where many instances of different kinds of variables with a related purpose and
stored dynamically.

#include<stdio.h>
#include<conio.h>
int main()
{
Struct testing
{
int number;
char b;
float c;
}var;
clrscr();
printf(“sizeof(var)=%d\n”,sizeof(var));
printf(“sizeof(var.a)=%d\n”,sizeof(var.a));
printf(“sizeof(var.b)=%d\n”,sizeof(var.b));
printf(“sizeof(var.c)=%d\n”,sizeof(var.c));
var.a=10;
printf(“%d\n”,var.a);
var.b=’w’;
printf(“%c\n”,var.b);
var.c=3.14;
printf(“%d\n”,var.a);
printf(“%c\n”,var.b);
printf(“%f\n”,var.c);
getch();
return 0;
}

FOR LOOP
For loop in C is the most general looping construct. The loop header contains three parts: an
initialization, a continuation condition, and step.
Syntax:
for (initialization, condition, step)
{
Statement 1;
Statement 2;
…………...
Statement n;
}
For statement contain three parts separated by two semicolons. The first part is known as initialization.
The variable called loop control variable or index variable is initialized in this part.
The second part is known as the condition. The condition should be a value one. The condition check
can be a compound expression made up of relational expression connected by logical AND, OR.
The third part is known as step. It should be an arithmetic expression. The initialization need not be
contained to a single variable. If more than one variable is used for initialization they are separated by commas.
The step can also applied to more than one variable separated by commas.

When for statement is encountered at first index variable is get initialized. This process is done only
once during the execution of for statement. When condition is evaluated, if it is true the body of the loop will be
executed. If more than one statement has to be executed it should end with a pair of braces. The condition of for
loop is executed each time at the beginning of the loop. After executing the body of the loop the step is executed,
again the condition is executed. If the condition become false it exit from the loop and control transferred to the
statement followed by the loop.
The following example executes 10 times by counting 0..9.
for (i = 0; i < 10; i++)

The following example illustrates the use of for loop.

#include<stdio.h>
#include<conio.h>
int main()
{
struct testing
{
int i;
clrscr();
for(i=1;i<=3;i=i+1)
printf(“%d\n”,i);
for(;i<=5;i++)
{
printf(“%d”,i);
printf(“\n”);
}
getch();
return 0;
}

While Loop

The while statement is also a looping statement. The while loop evaluates the test expression before
every loop, so it can execute zero times if the condition is initially false. It has the following syntax.

while (expression)
{
Statement 1;
Statement 2;
…………...
Statement n;
}
Here the initialization of a loop control variable is generally done before the loop separately. The testing
of the condition is done in while by evaluating the expression within the parenthesis. If the evaluation result is true
value, the block of statement within calibrates is executed. If the evaluation result is false value the block of
statements within the body of loop is skipped and the loop execution get terminated with the control passing to the
statement immediately following the while construct. The increment or decrement of the loop control variable is
generally done within the body of the loop.
The following example illustrates the use of while loop.

#include<stdio.h>
#include<conio.h>
int main()
{
struct testing
{
int i=1;
clrscr();
while(i<=5)
{
printf(“%d\n”,i);
i++;
}
getch();
return 0;
}

DO-WHILE LOOP

This construct is also used for looping. In this case the loop condition is tested at the end of the body of
the loop. Hence the loop is executed at least one.The do-while is an unpopular area of the language, most
programmers’ tries to use the straight while if it is possible.
Syntax of do while loop is
do
{
Statement 1;
Statement 2;
…………...
Statement n;
}
while(expression);
Here the block of statement following the do is executed without any condition check. After this
expression is evaluated and if it is true the block of statement in the body of the loop is executed again. Thus the
block of statement is repeatedly executed till the expression is evaluated to false.
do-while construct is not used as often as the while loops or for loops in normal case of iteration but
there are situation where a loop is to be executed at least one, in such cases this construction is very useful.
The following example illustrates the use of do-while loop.
ARRAYS

Array is a data structure, which provides the facility to store a collection of data of same type under
single variable name. Just like the ordinary variable, the array should also be declared properly. The declaration
of array includes the type of array that is the type of value we are going to store in it, the array name and
maximum number of elements.
The type may be any valid type supported by C. Array names, like other variable names, can contain
only letter, digit and underscore characters. Array names cannot begin with a digit character. I.e., The rule for
giving the array name is same as the ordinary variable. The size should be an individual constant. To refer to a
particular location or element in the array, we specify the name of the array and the index of the particular
element in the array. The index specifies the location of the element in the array. The array index starts from zero.
The maximum index value will be equal to the size of the array minus one. The array index can be an integer
variable for an integer constant.

One dimensional array in c programming language : ID array

The declaration form of one-dimensional array is


Data_type array_name [size];
The following declares an array called ‘numbers’ to hold 5 integers and sets the first and last
elements. C arrays are always indexed from 0. So the first integer in ‘numbers’ array is numbers[0] and the last is
numbers[4].

int numbers [5];


numbers [0] = 1; // set first element
numbers [4] = 5; // set last element
This array contains 5 elements. Any one of these elements may be referred to by giving the name of the
array followed by the position number of the particular element in square brackets ([]). The first element in every
array is the zeroth element.Thus, the first element of array ‘numbers’is referred to asnumbers[ 0 ], the second
element of array ‘numbers’is referred to as numbers[ 1 ], the fifth element of array ‘numbers’is referred to
as numbers[ 4 ], and, in general, the n-th element of array ‘numbers’is referred to as numbers[ n - 1 ].
Example:
RECURSION

Recursive functions are those functions, which call itself within that function. A recursive function must
have the following type of statements.
 A statement to test and determine whether the function is calling itself again.
 A statement that calls the function itself and must be argument.
 A conditional statement (if-else)
 A return statement.
Example: Factorial of a number
This is the most famous program on recursion. Many versions of this program are available. All programs
differ only in checking conditions. I prefer to write like the following one.
POINTERS

Pointer is a variable that represents the location of a data item, such as variable or an array
element. Within the computer’s memory, every stored data item occupies one or more contiguous memory cells.
The number of memory cells required to store a data item depends on the type of the data item. For example, a
single character will typically be stored in one byte of memory; an integer usually requires two contiguous bytes, a
floating-point number usually requires four contiguous bytes, and a double precision usually requires eight
contiguous bytes.
Suppose v is a variable that represents some particular data item. The compiler will automatically
assign memory cells to this data item. The data item can then be accessed if we know the address of the first
memory cell. The address of v’s memory location can be determined by the expression &v, where & is the unary
operator, called the address operator, that evaluates the address of its operand.

Das könnte Ihnen auch gefallen