Vous êtes sur la page 1sur 66

C language

What Is C ?
C is a programming language developed at AT & T’s Bell Laboratories of USA in 1972. It designed and
written by Dennis Ritchie. C began to replace the more familiar languages like PL/I, ALGOL, BCPL, B
etc.
Future of C language..
C language runs all platforms. Because c using compiler for compile the program.
C language most popular system programming language.
C language is a structure oriented programming language.
C language also called high-level language but it can handle low-level activities.
C language was invented for implementing UNIX operating system.
C language use many predefined library function. And user also create own library
function.

Uses of C programming language:


The C programming language is used for developing system applications that forms a major portion of
operating systems such as Windows, UNIX and Linux. Below are some examples of C being used.
1. Database systems
2. Word processors
3. Spreadsheets
4. Operating system development
5. Compilers and Assemblers
6. Network drivers
7. Interpreters
What Is Compiler, assembler, interpreter ?

Assembler, Compiler, Interpreter


these are translators use for converting in the code of high level language and low level
language into the machine level language. Because It is difficult to write and maintain programs in
machine level language. Translators are of three types:
Assembler
Compiler
Interpreter
Assembler is type of software used for converting the code of low level language (assembly language)
into machine level language.
Compilers and interpreters are used to convert the code of high level language into machine language.
The high level program is known as source program and the corresponding machine level program is
known as object program. Although both compilers and interpreters perform the same task but there
is a difference in their working.
A compiler searches all the errors of a program and lists them. If the program is error free then it
converts the code of program into machine code and then the program can be executed by separate
commands.

An interpreter checks the errors of a program statement by statement. After checking one statement,
it converts that statement into machine code and then executes that statement. The process
continues until the last statement of program occurs.
What is C STRUCTURED ?
This section use to written a comment lines. Comment line display information
for user or other person can understood the program. Comment line not
compile if run program.
Document Section Ex… Single line //--------------------
Multiple line /*-----------------*/

Link Section This section use to link predefine function or system libraries.
Ex… #include<stdio.h>
Definition Section This section use to declare all symbolic constant.
Ex… #define PI 3.4128
Global Declaration Section
This section use to declare variable outside the main function and they variable
use one or more times in main function.
Main Function Ex… int x, y, z;

All C programs must one main function. And main function have a two parts.
{ Ex… Void main()

Declaration Part This section use to declare variable inside the main function and they variable
use in executable part.
Ex… int x =5, y =8;
Executable Part
This section use to written a set of instruction in sequence. And executed
variables those declare in declaration part.
} Ex… printf(“Hello World\n”);

Sub Program This section use to written a function by user. Sub program section always write
after declare main function.
How To Executing a ‘C’ Program If Writing a C Programs, We Face
Some Error, Error Also Known As
Enter Program Bugs. Basically There Are Three
Types Of Errors In C Programming.
Edit Source Program
Syntax errors: These errors occur of wrongly typed
Compile Source Program statements, which are not according to the syntax
or grammatical rules of the language.
printf(“Hello, world”) - semicolon missing.
Syntax printf(“Hello, world”); - correct.
Errors ?
Logical errors: These errors occur of logically
incorrect instructions in the program. if there
should be an instruction, which multiplies two
Link With System Library numbers and is wrongly written to perform
addition. This logically incorrect instruction may
Execute Object Code produce wrong results.
int average(int a, int b)
{
Logic & Data return a + b / 2; /* should be (a + b) / 2;*/
Errors ? }
Runtime errors: These errors occur during the
execution of the programs, though the program is
Correct Output free from syntax and logical errors. Runtime error
also known as a compile error.
How To Learn a ‘C’ Program

Before learn any languages first you learn alphabets of languages,


in C language you learn character set.
After learn alphabets of languages you can grouped to form
meaningful word, in c language you create tokens.
And after creating word you also creating sentence, in c language
you can create statement.
And after creating sentences you creating a paragraph, in c
language you can create program.
What Is Character Set ?

They character are use writing a C program.


A to Z, a to z

Letters…. 0-9

Digits…… 
~ Tiled ] Right Bracket
# Hash . Dot
Symbol...  ^ Caret ; Semicolon
( Left Parentheses “ Double Quotation
% Percent : Colon
= Assignment < Less Than
- Minus Sign > Greater Than
) Right Parentheses , Comma
_ Underscore \ Back Slash
+ Plus Sign ? Question Mark
{ Lift Brace
} Right Brace White Space
| Vertical Bar \T Tab
/ Division \N New Line
‘ Single Quote \R Carriage Return
* Asterisk
[ Left Bracket
What Is C Tokens ?

A tokens is a smallest or basic unit of any program. The token are


classified as shown below.

Keyword Identifiers
Constant Operators
Special Symbols

What Is Statement of C ?

A statement is a command given to the program that instructs


the program to take a specific action or control the flow of
program execution.
Program

// This is a hello print program.

#include<stdio.h>
void main()
{
printf(“Hello World”);
}
What Is Keyword ?

The words which have predefined meaning in c language, they are


called keyword. They keyword for specific purpose, keyword also known
as reserved word.
Keywords are not use as variables name, function name and not
write capital letter. Because keyword are case sensitive and in C there
are 32 keywords.

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
What Is Identifiers ?

All variable, function, array name in program called identifiers, they


declared by user. Identifier consist of letter, number or underscore. The
first character in the identifier should be a letter or underscore, not
include space or identifier name not same in keyword.
The identifiers also case sensitive so capital or small word are
different mean, maximum length of up to 31 characters.

int ram; //valid


int ram_sharma; //valid
int 1ram; //invalid
int ram sharma; //invalid
What Is Constant ?
An constants is a data item and which is not change during the program execution.
The constants are basically two types
1. Numeric constant 2. Character constant
 Integer constant  Single character constant
 Real constant (floating point)  String constant
 Backslash character constant

An integer constant is a whole number without any decimal point.


Integer constant can be classified into three types.
1. Decimal number >>>>> 1, 147, 254
2. Octal number >>>>> 017, 0105
3. Hexadecimal number >>>>> 0X6, 0x5B

The numeric quantities having fractional part are called floating point
constants. Floating point constant can be represented using two forms.
Fractional part >> 0.5, 0.99, 2.58
Exponent notation >> 7.e82, 1.23e1
Character enclosed within a pair of single quote is called single character
constant. Each character associated unique value.
‘9’ ‘a’ ‘$’ //valid
“9” ‘99’ //invalid

A sequence of character enclosed within a pair of double quote is called


string constant. String constant always ends with null character.
“9” “ram” //valid
‘9’ ‘ram’ //invalid

Backslash constant use for effects. They are also called escape sequence
character constant.
\a \t \n \v ….etc.
Backslash constant use for effects. They are also called escape sequence
character constant.
Bell \a beep sound
Backspace \b move one position left side
Horizontal tab \t move 8 position right side
Vertical tab \v this is not support
Newline \n move next line
Form feed \f move next page
Carriage return \r start of current line
Quotation mark \” “
Question mark \? ?
Backslash \\ \
NULL \0 NULL character
What Is Operators ?
A operator is a symbol that perform arithmetic or logical operation.
+ - / * //operators
2, 5, 8 //operands

The operators that are used to perform arithmetic operations such as


addition, subtraction, multiplication etc…
Description Symbols Meaning
Addition + Add
Subtraction - Subtract
Multiplication * Multiply
Division / Divide
Mod % Remainder

The operators that are used to compare two operand and find the
relationship between operand.. The two operand may be variables, constants or
expressions.
Description Symbols Description Symbols
Less than < Greater/equal >=
Equal == Not equal !=
Lesser/equal <= Greater >
The operators that are used to store value of statement into the variable.

Syntax:- =

Example : a=20; b= 30; c=a+b;

They operator that are used to increment or decrement value of variable n times
( if conditions true ). These operator are also called unary operator and they are four
types…
Types Example
Post - increment i++
Pre - increment ++i
Post - decrement i--
Pre - decrement --i
The operator that are use to join two or more than relational operators for
compare the operand.
Description Example
AND &&
OR !!
NOT !

The operator that are use to process data in bit level. These operators use only int
or char data type not in float or double data type … Description
Symbol
Bitwise AND &
Bitwise OR |
Bitwise Exclusive OR ^
Shift left <<
Shift right >>
One’s complement ~
The operator that are use to process special data.
Description Symbol
Comma ,
Size of sizeof(variable name)
Pointer operators &, *
Selection operator . and ->

The operator also called ternary operator. An operator that operates on


three operands …
Example
Condition ? exp 1 : exp 2;
What Is Special Symbols ?

The special symbols are used in some special meaning and


thus, cannot be used for some other purpose.

[] () {} , ; : * = #

Braces{ }: These opening and ending curly braces marks the


start and end of a block of code containing more than one executable
statement.

Parentheses( ): These special symbols are used to indicate


function calls and function parameters.

Brackets[ ]: Opening and closing brackets are used as array


element reference. These indicate single and multidimensional
subscripts.
What is Data type.
1. A data types is a types of data.
2. Data types is a data storage format that can contain a specific types or range of values.
3. When program store data in variables, each variable must be assigned a specific data type.
There are four data types in C language
S.no Types Data Types

1 Primitive data types int, char, float, double

2 Derived data type pointer, array, structure, union


Primitive data types
Integer : This data type allows a variable to store numeric values.
We can’t store decimal values using int data type.
If we use int data type to store decimal values, decimal values will be truncated and we
will get only whole number.

Character : This data type allows a variable to store only one character.
“char” keyword is used to refer character data type.

Floating: point data type consists of 2 types. They are,


1. float
Float data type allows a variable to store decimal values.
We can use up-to 6 digits after decimal using float data type.
2. double
Double data type is also same as float data type which allows up-to 10 digits after decimal.
Modifiers are prefixed with basic data types to modify (either increase or decrease) the amount of
storage space allocated to a variable.
They are some modifiers available in C language.
1. short 2. long 3. signed 4. unsigned 5. long

S.No C Data types storage Size Range

1 char 1 –127 to 127

2 int 2 –32,767 to 32,767

3 float 4 1E–37 to 1E+37 with six digits of precision

4 double 8 1E–37 to 1E+37 with ten digits of precision

5 long double 10 1E–37 to 1E+37 with ten digits of precision

6 long int 4 –2,147,483,647 to 2,147,483,647

7 short int 2 –32,767 to 32,767

8 unsigned short int 2 0 to 65,535

9 signed short int 2 –32,767 to 32,767

10 long long int 8 –(2power(63) –1) to 2(power)63 –1

11 signed long int 4 –2,147,483,647 to 2,147,483,647

12 unsigned long int 4 0 to 4,294,967,295

13 unsigned long long int 8 2(power)64 –1


What is Variable.

C variable is a named location in a memory where a program can manipulate the data. This
location is used to hold the value of the variable.
• The value of the C variable may get change in the program.
• C variable might be belonging to any of the data type like int, float, char etc.
Rules for naming C variable:
• Variable name must begin with letter or underscore.
• Variables are case sensitive
• They can be constructed with digits, letters.
• No special symbols are allowed other than underscore.
Declaring & initializing C variable:
• Variables should be declared in the C program before to use.
• Variable initialization means assigning a value to the variable.
There are three types of variables in C program They are,
Local variable
The scope of local variables will be within the function only.
These variables are declared within the function and can’t be accessed outside the function
Global variable
The scope of global variables will be throughout the program. These variables can be accessed
from anywhere in the program.
This variable is defined outside the main function. So that, this variable is visible to main
function and all other sub functions.
Control Statements
Simple-if

If-else

Nested-if
Sequential Statements
Conditional Statements Else-if-ladder

switch

Branching Statements
goto

break
Un-Conditional Statements
continue

return
for

Loop Statements while

Do-while
Sequential Statements The programmer writes a sequence of statements to do a
specific activity. All these statements in a program are executed in the
order in which they appear in the program. These programming
statements that are executed sequentially, that is one after the other,
are called sequential control statements.

Branching Statements In sequential control, we know that all the statements are
executed in the order. However, computer can skip execution of some
statements. This skipping facility is provided by the instruction called
skip instructions. these skip instruction are also called branching
statement. The branching statement are two types.

We know that all the statements are executed in the order. The
computer can skip the execution of some statements based on some
Conditional condition. These condition statement are also called conditional
branching statement.

We know that all the statements are executed in the


Un-Conditional order. But some time user wants to transfer the control fro one point
to another point during executing without any condition. These
condition statement are also called conditional branching statement.

Loop Statements The statements that enable by programmer to execute a set of


statement repeatedly till the required activity.
Simple-if

if statement or simple if statement use as simple selection or decision


statement. When a set of statement have to be executed or skipped when
the condition is true or false. If –statement used as a one way decision
statement. but another action has to performed when the condition is false,
then if –statement not recommended.

Syntax:-
if(Condition )
{
Statement;
}
Next
statement;
if-else

If-else statement is a simple selection or decision statement. These


statement have tow part, one part execute when a condition are true and
second part execute when a condition are false. The true part takes if and
false part takes else.

Syntax:-
if(Condition )
{
Statement;
}
else
{
statement;
}
Nested if- statement

All if or If-else statement with in another if or if else statement is called


nested if-statement. when an action has to be performed based on many
decisions, then nested if-statement is used. It also called multi-way decision
statement.

Syntax:-
if(Condition )
{
if(Condition )
{
Statement;
}
}
else
{
if(Condition )
{
Statement;
}
}
if- else-if ladder

when series of action have to be performed based on decisions one by one,


then if-else-if ladder statement is used. If-else-if ladder is a form of nested
if statement.
if(Condition )
{
Statement;
Syntax:-
}
Else if
{
Statement;

}
Else if
{
Statement;

}
Else
{ }
Switch
Switch case statements are a substitute for long if statements that compare
a variable to several "integral" values ("integral" values are simply values
that can be expressed as an integer, such as the value of a char).

Syntax:- Switch (expression )


{
case valuse-1:
block- 1;
break;
case valuse-2:
block- 2;
break;
case valuse-3:
block- 3;
break;
default :
block;
break;
}
goto
This is an unconditional branch statement. Goto statements is a jump
statement that transfers the control to the specified statement in a
program. This specific statement written in label .
Label is a variable name and not necessary to declaration label variable to
first.

Syntax:-
goto label; Label:
{ {
skip(statement) statement
} }
label: goto Label;

Forward jump Backward jump


break
This is an unconditional branch statement or jump statement. this jumping
statement we can terminate the further execution of the program and
transfer the control to the end of any immediate loop

Syntax:- break;

continue
This is an unconditional branch statement or jump statement. this jumping
statement, we can terminate the further execution of the program and
transfer the control to the beginning of any immediate loop.

Syntax:- continue;
While loop
A while loop in C programming language repeatedly executes a target
statement as long as a given condition is true. It also called entry controlled
loop.

Syntax:- while(condition)
{
statement ;
increment/ decrement;
}
do while loop
for and while loops, which test the loop condition at the top of the loop,
the do...while loop in C programming language checks its condition at the
bottom of the loop. It also called exit control loop.

Syntax:- do
{
statement ;
increment/ decrement;
}
while(condition)
for loop
A set of statement may have to be repeatedly executed for a specified
number of times. In this situations we use for loop. The for loop is also an
entry-controlled loop. for loop hold three expression.

for (expr1; expr2; expr3)


Syntax:-
{

Statement;
}
What difference between a string and an array ?

- String can hold only char data. Where as an array can hold any data type.
- An array size can not be changed. Where as a string size can be changed if
it is a char pointer
- The last element of an array is an element of the specific type. The last
character of a string is a null – ‘\0’ character.
- The length of an array is to specified in [] at the time of declaration
(except char[]). The length of the string is the number of characters + one
(null character).
- Array use index number for store data in array variable. Index number
start number of 0 to n numbers.
- String use to store series of char in string variable. Start number 1 to \0
(-1 length of string )
String

The string in C programming language is actually a one-dimensional array of


characters which is terminated by a null character '\0'. Thus a null-terminated string
contains the characters that comprise the string followed by a null.
• This null character indicates the end of the string.
• Strings are always enclosed by double quotes. Whereas, character is enclosed by
single quotes in C.

char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};


char greeting[6] = “Hello”;
char greeting[ ] = “Hello”;
C String functions:

String.h header file supports all the string functions in C language. All the
string functions are given below.
S.no String Description
functions
1 strcat ( ) Concatenates str2 at the end of str1.
2 strncat ( ) appends a portion of string to another
3 strcpy ( ) Copies str2 into str1
4 strncpy ( ) copies given number of characters of one string to another
5 strlen ( ) gives the length of str1.
6 strcmp ( ) Returns 0 if str1 is same as str2. Returns <0 if strl < str2. Returns >0 if str1 > str2.
7 strcmpi_(.) Same as strcmp() function. But, this function negotiates case. “A” and “a” are treated as same.
8 strchr ( ) Returns pointer to first occurrence of char in str1.
9 strrchr ( ) last occurrence of given character in a string is found
10 strstr ( ) Returns pointer to first occurrence of str2 in str1.
11 strrstr ( ) Returns pointer to last occurrence of str2 in str1.
12 strdup ( ) duplicates the string
13 strlwr ( ) converts string to lowercase
14 strupr ( ) converts string to uppercase
15 strrev ( ) reverses the given string
16 strset ( ) sets all character in a string to given character
17 strnset ( ) It sets the portion of characters in a string to given character
strcat ( )

strcat( ) function in C language concatenates two given strings. It concatenates


source string at the end of destination string.

Syntax :- char * strcat ( char * destination, const char * source );

#include <stdio.h>
Example:-
#include <string.h>
#include <conio.h>
void main( )
{
char source[ ] = " india" ;
char target[ ]= " welcome" ;
clrscr();
printf ( "\nSource string = %s", source ) ;
printf ( "\nTarget string = %s", target ) ;
strcat ( target, source ) ;
printf ( "\nTarget string after strcat( ) = %s", target ) ;
getch();
}

Output: welcome india


strncat ( )

strncat( ) function in C language concatenates ( appends ) portion of one string at


the end of another string.

Syntax :- char * strncat ( char * destination, const char * source, size_t num );

#include <stdio.h>
Example:-
#include <string.h>
#include <conio.h>
void main( )
{
char source[ ] = “ india " ;
char target[ ]= " welcome " ;
clrscr();
printf ( "\nSource string = %s", source ) ;
printf ( "\nTarget string = %s", target ) ;
strncat ( target, source, 4 ) ;
printf ( "\nTarget string after strncat( ) = %s", target ) ;
getch();
}

Output: welcome ind


strcpy ( )

strcpy( ) function copies contents of one string into another string. Syntax for strcpy
function is given below.

Syntax :- char * strcpy ( char * destination, const char * source );

#include <stdio.h>
Example:-
#include <string.h>
#include <conio.h>
void main( )
{
char source[ ] = " welcome india" ;
char target[ 20]= " " ;
clrscr();
printf ( "\nSource string = %s", source ) ;
printf ( "\nTarget string = %s", target ) ;
strcpy ( target, source ) ;
printf ( "\nTarget string after strcpy( ) = %s", target ) ;
getch();
}

Output: welcome india


strncpy ( )

strncpy( ) function copies portion of contents of one string into another string.

Syntax :- char * strncpy ( char * destination, const char * source, size_t num );

#include <stdio.h>
Example:-
#include <string.h>
#include <conio.h>
void main( )
{
char source[ ] = " welcome india" ;
char target[ 20]= " " ;
clrscr();
printf ( "\nSource string = %s", source ) ;
printf ( "\nTarget string = %s", target ) ;
strncpy ( target, source, 5 ) ;
printf ( "\nTarget string after strncpy( ) = %s", target ) ;
getch();
}

Output: welcom
strlen( )

strlen( ) function in C gives the length of the given string.

Syntax :- size_t strlen ( const char * str );

Example:- #include <stdio.h>


#include <string.h>
#include <conio.h>
void main( )
{
int len;
char a[20]=“welcome" ;
clrscr();
len = strlen(a) ;
printf ( "\string length = %d \n" , len ) ;
getch();
}

Output: 7
strcmp( )

strcmp( ) function in C compares two given strings and returns zero if they are
same.

Syntax :- int strcmp ( const char * str1, const char * str2 );

Example:- #include <stdio.h>


#include <string.h>
#include <conio.h>
void main( )
{
char str1[ ] = “welcome" ;
char str2[ ] = “india" ;
int i, j, k ;
clrscr();
i = strcmp ( str1, “welcome" ) ;
j = strcmp ( str1, str2 ) ;
k = strcmp ( str1, “g" ) ;
printf ( "\n%d %d %d", i, j, k ) ;
getch();
}
Output: 0 1 1
strcmpi( )

strcmpi( ) function in C is same as strcmp() function. But, strcmpi( ) function is not


case sensitive. i.e, “A” and “a” are treated as same characters. Where as, strcmp()
function treats “A” and “a” as different characters.

Syntax :- int strcmpi ( const char * str1, const char * str2 );


Example:- #include <stdio.h>
#include <string.h>
#include <conio.h>
void main( )
{
har str1[ ] = “welcome" ;
char str2[ ] = “india" ;
int i, j, k ;
clrscr();
i = strcmpi ( str1, “WELCOME" ) ;
j = strcmpi ( str1, str2 ) ;
k = strcmpi ( str1, “g" ) ;
printf ( "\n%d %d %d", i, j, k ) ;
getch();
}
Output: 0 1 1
strchr( )

strchr( ) function returns pointer to the first occurrence of the character in a given
string.

Syntax :- char *strchr(const char *str, int character);

Example:-
#include <stdio.h>
#include <string.h>
#include <conio.h>
void main( )
{
char s [55] =“i am student in samarpit";
char *p;
clrscr();
p = strchr (s,‘u');
printf(“character ‘u’ find position at: %d ”,p-s+1);
getch();
}

Output: 8
strrchr( )

strrchr( ) function in C returns pointer to the last occurrence of the character in a


given string.

Syntax :- char *strrchr(const char *str, int character);

Example:-
#include <stdio.h>
#include <string.h>
#include <conio.h>
void main( )
{
char s [55] =“i am student in samarpit";
char *p;
clrscr();
p = strrchr (string,'i');
printf(“character ‘u’ find position at: %d ”,p-s+1);
getch();
}

Output: 23
strstr( )

strstr( ) function returns pointer to the first occurrence of the string in a given
string.

Syntax :- char *strstr(const char *str1, const char *str2);

Example:- #include <stdio.h>


#include <string.h>
#include <conio.h>
void main( )
{
char s [55] =“i am student in samarpit";
char *p;
clrscr();
p = strchr (string,'in');
if ( p )
{ printf(“string found”); }
else
{ printf(“string found”); }
getch();
}
Output: string found
strdup( )

strdup( ) function in C duplicates the given string.

Syntax :- char *strdup(const char *string);

Example:-
#include <stdio.h>
#include <string.h>
#include <conio.h>
void main( )
{
char *p1= “samarpit”;
char *p2;
clrscr();
p2 = strdup (p1);
printf("Duplicated string is : %s", p2);
getch();
}

Output: string found


strlwr( )

strlwr( ) function converts a given string into lowercase.

Syntax :- char *strlwr(char *string);

Example:-

#include <stdio.h>
#include <string.h>
#include <conio.h>
void main( )
{
char str[ ] = "MODIFY This String To LOwer";
clrscr();
printf("%s\n",strlwr (str));
getch();
}

Output: modify this string to lower


strupr( )

strupr( ) function converts a given string into uppercase.

Syntax :- char *strupr(char *string);

Example:-

#include <stdio.h>
#include <string.h>
#include <conio.h>
void main( )
{
char str[ ] = "Modify This String To Upper";
clrscr();
printf("%s\n",strupr(str));
getch();
}

Output: MODIFY THIS STRING TO LOWER


strrev( )

strrev( ) function reverses a given string in C language.

Syntax :- char *strrev(char *string);

Example:-

#include <stdio.h>
#include <string.h>
#include <conio.h>
void main( )
{
char name[30] = "Hello";
clrscr();
printf("String before strrev( ) : %s\n",name);
printf("String after strrev( ) : %s",strrev(name));
getch();
}

Output: Hello
olleH
strset( )

strset( ) function sets all the characters in a string to given character.

Syntax :- char *strset(char *string, int c);

Example:-
#include <stdio.h>
#include <string.h>
#include <conio.h>
void main( )
{
char name[20] = "Hello";
clrscr();
printf("Original string is : %s", name);
strset(name,’#’);
printf("After string set: %s",name);
getch();
}
Output: #####
strnset( )

strnset( ) function sets portion of characters in a string to given character.

Syntax :- char *strnset(char *string, int c);

Example:-
#include <stdio.h>
#include <string.h>
#include <conio.h>
void main( )
{
char name[20] = "Hello india";
clrscr();
printf("Original string is : %s", name);
strnset(name,'#',4));
printf("After string set: %s",name);
getch();
}
Output: ####o india
Array

Many application require processing of multiple data items that have


common characteristics. In such situations it is always convenient to place the data
item into an array, where they will share the same name. an array is a collection of
similar type of elements. All elements in the array are referred with the array name.
Array hold a group of data. Array size must be a constant value.

There are 2 types of C arrays.

One dimensional array


Syntax : data-type arr_name[array_size];

Multi dimensional array


syntax : data_type array_name[num_of_rows][num_of_column]
Single-dimensional array

A single-dimensional array (also called one-dimensional array) is a linear list


consisting of related and similar data items. In memory, all the data item are stored in
contiguous memory location one after the other

#include<stdio.h>
int main( )
{
int i, arr[5];
arr[0] = 10;
arr[1] = 20;
arr[2] = 30;
arr[3] = 40;
arr[4] = 50; output
for (i=0;i<5;i++)
{ value of arr[0] is 10
printf(“value of arr[%d] is %d \n”, i, arr[i]); value of arr[1] is 20
} value of arr[2] is 30
} value of arr[3] is 40
value of arr[4] is 50
search
More times we working with large amount of data. It may be necessary to
determine a particular item is present in the large amount of data or not. This process of
finding a particular item in the large amount of data is called searching.

Linear search
linear search is a simple search technique in which we search for a given key item in
the list in linear order. one after the other. The liner search is also called sequential search.
Therefore it is considered to be too slow to be used when searching elements in large lists. But
this is very simple and easier to implement.

Binary search
binary search is a also search technique in which we search for a given key item in
the list in sort order. This method starts by comparing the searched element to the elements in
the middle of the list.

What is the difference between Binary Search and Linear Search?


Even though both linear search and binary search are searching methods they have
several differences. While binary search operates on sorted lists, liner search can operate on
unsorted lists as well linear search is too slow to be used with large lists. binary search is
considered to be a more efficient method that could be used with large lists.
Sorting
More times we working with large amount of data. It may be necessary to arrange
them in ascending or descending order. This process of arranging the given elements so that
they are in ascending order or descending order is called sorting.
The two important and simple sorting techniques are bubble sort or selection
sort.

Selection Sort
Selection sort is to repetitively pick up the smallest element and put it into
the right position:
• Find the smallest element, and put it to the first position.
• Find the next smallest element, and put it to the second position.
• Repeat until all elements are in the right positions.

Bubble Sort
Bubble sort repetitively compares adjacent pairs of elements and swaps if
necessary.
• Scan the array, swapping adjacent pair of elements if they are not in relative
order. This bubbles up the largest element to the end.
• Scan the array again, bubbling up the second largest element.
• Repeat until all elements are in order.
Two-dimensional array
The term of dimension represents number of index used to access a particular item
in an array.
The element of the arrays that explain or represent two characteristics are called
two-dimensional array. Arrays with one set of square brackets ‘[ ]’ are single dimensional
arrays . Arrays with two sets of square brackets ‘[ ] [ ]’ are called two-dimensional array. Arrays
with two or more dimensional are called multi-dimensional arrays.
the-dimensional array is used when data item are arranged row-wise and column-
wise in a tabular form.

#include<stdio.h>
int main( )
{ RC
int i, j, arr[2][2];
arr[0][0] = 10;
arr[0][1] = 20;
arr[1][0] = 30;
arr[1][1] = 40;
for (i=0;i<2;i++) output
{
for (j=0;j<2;j++) Array value is: 10
{ printf(“\n array value is: %d”, arr[i][j]); Array value is: 20
} Array value is: 30
} Array value is: 40
}
Function
A large program can be divided into a series of individual related programs called
modules. These modules are called function. Thus function (also called sub-program) is a
program segment that carries out some specific and well-defined task.
function can be classified into two categories .
(1) library function ( Built-in function)
(2) User defined function (UDF)

(1) library function ( Built-in function)


the standard C library is a collection if various types of function which perform
some pre-defined tasks. These function which are part of the C compiler that have been
written for general purpose task solution are called library function.
Some library function here:- printf() , scanf(), getch(), clrscr() etc.

Advantage :
the programmer’s job is made easier because the function are already available.
The library function are simple to use and easy to reminder.

Disadvantage :
the library function are limited, programmer cannot completely depend only on
library function.
(2) User defined function (UDF)

The programmers need other than library function to achieve some specific tasks.
These types of function which are written by the programmer to do some specific task are
called user defined functions (UDF).
Advantage :
o Reusability
o Reduction of code size
o Increase in readability of the program
o Modular programming approach
o Easier debugging
o Extendibility
o Function sharing
There are 3 aspects in each C function.
• Function declaration or prototype - This informs compiler about the function name,
function parameters and return value’s data type.
• Function call – This calls the actual function
• Function definition – This contains all the statements to be executed.
.no C function aspects syntax
1 function definition return_type function_name ( arguments list )
{ Body of function; }
2 function call function_name ( arguments list );
3 function declaration return_type function_name ( argument list );
There are two ways that a C function can be called from a program. They are,
• Call by value
• Call by reference

Call by value:
The value of the variable is passed to the function as parameter.
The value of the actual parameter can not be modified by formal
parameter.

Actual parameter – This is the argument which is used in function call.


Formal parameter – This is the argument which is used in function definition.

Call by reference:
The address of the variable is passed to the function as parameter.
The value of the actual parameter can be modified by formal parameter.
C – Argument, return value
All C functions can be called either with arguments or without arguments
in a C program.

1. C function with arguments (parameters) and with return value


2. C function with arguments (parameters) and without return value
3. C function without arguments (parameters) and without return value
4. C function without arguments (parameters) and with return value
S.no C function syntax
1 with arguments and with return int function ( int ); // function declaration
values function ( a ); // function call
int function( int a ) // function definition
{statements; return a;}
2 with arguments and without return void function ( int ); // function declaration
values function( a ); // function call
void function( int a ) // function definition
{statements;}
3 without arguments and without void function(); // function declaration
return values function(); // function call
void function() // function definition
{statements;}
4 without arguments and with return int function ( ); // function declaration
values function ( ); // function call
int function( ) // function definition
{statements; return a;}
#include <stdio.h>
int add(int a, int b); //function prototype(declaration)
void main(){
int num1,num2,sum;
printf("Enters two number to add\n");
scanf("%d %d",&num1,&num2);
sum=add(num1,num2); //function call
printf(“total of value=%d",sum);
getch( );
}
int add(int a,int b) //function declarator
{
/* Start of function definition. */
int total;
total=a+b;
return total; //return statement of function
/* End of function definition. */
}
Pointer
We know that all the variables should be declared before they are used. Pointer
variables should also be declared before their use.
Syntax: - datatype * identifier;
Name of pointer variable.
* Use to identify the pointer variables.
Datatype of pointer variables.

Example: for normal variable declaration. a Variable name


int a; Content of box 5 Memory box
a=5; 2048 Address of box

Example: for use pointer variable declaration. a Variable name


int a;
Content of box 5 Memory box
int *p;
a = 5; 2048 Address of box
p=&a;
p Pointer Variable name
Content of box 2048 Memory box
2050 Address of box
program: for normal variable declaration.

#include<stdio.h> A Variable name


void main( ) Content of box 5 Memory box
{ 2048
int a; Address of box
a=5;
printf(“value of variable A is: %d”, a);
printf(“memory address of variable A is: %d”, &a);

} Notes.
• & is known as address of operator. It is an unary operator.
• Operand must be the name of variable.
• & operator gives address number of variable(Operand).
• & is also knows as referencing operator.
• * is indirection operator. It is an unary operator
• It`s takes address as an argument. It is also know as dereferencing.

Pointer is a variable that contains address of another variable.


Pointer always use 2 bytes of memory.
Pointer data types or variables data types always same.
Structure

A structure is defined as a collection of logically related variables under a single


name. All these variable may contain data items of similar or dissimilar data types.
Each variable in the structure represents an item and is called member of filed of the
structure.
Syntax: struct tag_name
{
datatypes member1;
datatypes member2;
datatypes member3;
}
• Struct is the keyword which tells the compiler that a structure is being defined.
• The members are also called fields or elements of the structure.
• The members are declared within curly braces. The members can be any of the
data types such as int, char, float, etc.
• structure variables can be declared for same structure and memory will be
allocated for each separately
Difference between C variable, C array and C structure:

• A normal C variable can hold only one data of one data type at a time.
• An array can hold group of data of same data type.
• A structure can hold group of data of different data types
• Data types can be int, char, float, double and long double etc.

Datatype C variable C array C structure


Syntax Example Syntax Example Syntax Example
int int a a = 20 int a[3] a[0] = 10 struct student a = 10
a[1] = 20 { b=
a[2] = 30 int a; “Hello”
a[3] = ‘\0′ char b[10];
char char b b=’Z’ char b[10] b=”Hello” }

Vous aimerez peut-être aussi