Sie sind auf Seite 1von 158

• Mohit sharma=9928686346

• itsmohitonly@gmail.com
• Contact for software development and
web site development work,projects
C is a general-purpose,
 Block structured,
structured
 Procedural,
Procedural
 Computer programming language
 Developed in 1972
 by Dennis Ritchie
at the Bell Telephone Laboratories for use with the Unix
Operating System.

[1] It has since spread to many other platforms.


Although C was designed as a system implementation
language,
[2] it is also widely used for applications.
C has also greatly influenced many other popular languages,
[3] especially C++, which was originally designed as an
extension to C.
Uses of C

• C was initially used for system development work.

Some examples of the uses of a C might be =

 Operating System
 Language Compilers
 Assemblers
 Text Editors
 Modern Programs
 Data Bases
 Language Interpreters
Why C?

C is simple.
• C is fast.
• C offers better interaction with hardware.
hardware

ENGLISH C
Alphabets, digits Alphabets, digits, special
symbols
Words, numbers Constants, variables, keywords

Sentences Statements or instructions


Paragraph Program
History of ANSI
• ANSI=American national standard institute

• ISO=international standard organization

 1960=ALGOL (Arithmetic language)


 1967=BCPL (Basic combined programming language)
 1970=B language
 1972=traditional c
 1978=k & r ’c’
 1989=ANSI C
 1990=ANSI / ISO C
DATA TYPES
DATA TYPES OF THREE TYPES:

 PRIMARY DATA TYPES / FUNDAMENTAL DATA TYPES / BUILT IN


DATA TYPES

INTEGER int
FLOAT float
CHARACTER char
void void

• ………………………………………………………………………………………………………………..
 USER DEFINED DATA TYPES
TYPEDEF
ENUM
• ………………………………………………………………………………………………………………

 DERIEVED DATA TYPES


ARRAY
STRUCTURE
UNION
POINTER
FUNCTIONS
Integer data
type in c 8bit Int

16 bit short

32bit long

Float 32 bit ( 4 byte)


Floating
Point data Double 43 bit ( 8 byte)
type in c

long double 80 bit ( 10 byte)


Character data type in c

char 1byte

signed char 8bit

unsigned char 8bit

DATA TYPE SIZE(BYTE) RANGE

CHAR 1 -128 to +128


Int 2 -32768 to +32768
Float 4 3.4e-38 to 3.4e+38
Double 8 1.7e-308 to 1.7e+308
RULES / NOTE :

 C is lower case language so program are written in


small letter

 \n is used for go to next line


for ex:
ram\nmohan
than result is =
ram
mohan
 \t is used for text far from its actual position.
 \b a backspace
 \r a carriage return (without a line feed)
 \‘ a single quote (e.g. in a character constant)
 \" a double quote (e.g. in a string constant)
 \\ a single backslash
…………………………………………………….
 we don’t write in program r2
we write r*r
………………………………………………………
 we use 3.14 in the PLACE of pie
……………………………………………………..
 Computer is always read right to left.
…………………………………………………….
C is case sensitive
 …………………………………………………….
Rules:

By clrscr( );
 we can clear the screen,
 it can used after data type declaration.
we use clrscr(); after the data type declaration and before
the printf( ).
…………………………………………………………

Always write short form of the data type declaration


• for ex.
 kilometer km
 meter m
 parameter pa
SAVING THE FILE
 by F2 we can save the program .
 the another method is to go to file menu
and then save from that position with extension .c
and then press ok
………………………………………………………………………………………..
• # include <stdio.h> allows the program to interact with the screen,
keyboard and file system of your computer.
• You will find it at the beginning of almost every C program

Full Forms
 .h = Extension

 Conio = Console input output

 conio.h = Console input output system file

 stdio = Standard input output

 stdio.h = Standard input output system file


Question

 Why all the program will always start with main()?


Ans : bcoz in compiler it is written that translation is start from where
main is written that position.
Every C program contains a function called main. This is the start
point of the program .
We can not use after main() function any semicolon.
• ………………………………………..
 What is the mean of getch ( ) ?
• Ans: getch is a library function ,by this we can see the output on
screen. if we will not write the getch function in program then the
program is not run and we can't see the result.
Use of some key in the C - language

 F2 = to save the program


 F3 = to open the file
 F5 = to set the screen big and short
 Ctrl+F9 = to see the result
 Alt+F9 = to see the error
 F8 = to trace the prog.
Comments in C
 Single line comment //
 Multi line comment /* */
Note 
Comment ignored by compiler
Comment u can write any where in the program
Useful to a person trying to read and understand the
program.
The format to write the simple program

#include<stdio.h> //HEADER FILE


#include<conio.h>
void main() / main() //FUNCTION NAME
{ //START OF PROGRAM
int/float ; //DATA TYPE DECLARATION
clrscr(); //FOR CLEAR SCREEN

printf("\n enter the value of ...");


//PROGRAM STATEMENT
scanf("%d"/"%f"/"%c",&...);
//TO TAKE VALUE FROM USER
formula
printf("%d"/"%f"...); //to print output
getch(); //TO SEE OUTPUT
} //END OF PROGRAM
Flow Chart

 The flow chart can easy to understand.

 Flow chart is a pictorial representation of a algorithm that uses boxes


of different shapes to denote different types of instructions.

 The logic of all program of flowchart should be from top to bottom


and from left to right.

 Normally flow lines could not cross each other.

 Each symbol except (decision box) used in the flow chart should have
one entry point and one exit point.

 As far as possible the instructions within the symbol of a program


should be independent of any particular programming language.
Start / Stop

Input /output
/read /write

Processing

Condition

connector

Flow line
Example of Flow Chart
Q. Draw a flow chart to calculate 2 number ?

Start

Read a,b

Sum=a+b

Print sum

Stop
Algorithm

• The term algorithm may be formally defined as a sequence of


instructions designed in such a way that
• if the instructions are executed in the specified sequence.

• The desired results will be obtained the instructions.

• However should be precise and unambiguous and the result


should be obtain after a finite number of execution steps
• Characteristics of Algorithm

• Each and every instructions should be precise and


unambiguous

• Each instructions should be such that it can be performed in


a finite time

• One or more instructions should not be separated infinitely

• After performing the instructions that is after the algorithm


terminates the desired result must be obtained.
Algorithm: To find the area of rectangle
• Step1: Read Length L and breadth b
• Step2: Calculate area a = L * b
• Step3: Display area
• Step4: Stop
…………………………………………………………
TO FIND WHETHER THE GIVEN NO IS ODD OR EVEN

STEP1: READ NO. N


• STEP2: CALCULATE REMAINDER R=N%2
• STEP3: IF R=0 THEN DISPLAY”NO IS EVEN”
• STEP4: IF R=1 THEN DISPALAY “NO IS ODD”
• STEP5: STOP
• ERRORS
• There are types of errors
Syntax Error
Logical Error
Run time Error

Syntax error
 when rules or syntax of programming language are not followed

Logical error
 error in planning the programming logic.

RUN TIME ERROR


 ERROR COMES WHEN PROGRAM RUNS.
Software
• software is a set of instructions that directs the computer to process information ,these
instructions are called programs.
• without software computer can not work.
Types of software=
• System software
• Application software

System Software=
the system software contains those programs that control and support the computer system
and its data processing applications
it includes=
• the operating system
• the language translators

Operating System
• operating system is a organized collection of integrated set of specialized programs that
controls the overall operations of a computer.
• it helps the computer to supervise and manage its resources.
• operating system calls the application program whenever needed.
• translate the special service programs and manages data needed to produced the output as
desired by the users.
Application Software
 Application software is a set of program designed
for a specific uses or application such as word
processing ,graphics ,or spreadsheet analysis.
The operating system acts as a communication link
between the hardware and the application program.
 It is responsible for loading the application
software into memory and then staring the program.
 When we have finished using application software
we return to the operating system.
PROGRAMMING LANGUAGE
A language is a system of communication.
 A PROGRAMMING LANGUAGE consists of all
symbols ,characters and usage rules that permit
people to communicate with computers
 A program is a set of logically related instructions
that are arranged in a sequence that guides the
computer to solve a problem.
 The process of writing a program is called
programming.
Machine Language
this is a sequence of instructions written in the form of binary
numbers consisting of 1's and 0's to which is the computer
responds directly.
A machine language has 2parts =
 the first part is the command or an operation that tells the
computer what functions are to be performed.
 the second part of the instruction is the operand that tells
the computer where to find or store the data on which the
desired operation is to be performed.

 the machine language is the only one that computer can


understand directly.
 so this language is very difficult to understand .
 but the main advantage of this language is that it is faster in
execution as the computer directly starts executing it.
Assembly language=

 A program written by a programmer in an


assembly language is called a Source Program.
 After this source program has been converted
into machine code by an assembler;
 It is referred to as an object program.
 The main advantage of assembly language is
that the programs written in it are easy to
understand as compared to the programs of
Machine Language.
 for example
LDA,7 LOAD REGISTER A WITH 7
High Level Language

 Readability
 Portability
 Easy Debugging
 Easy Software Development

• High Level Language are FORTRAN,COBOL


FIRMWARE
 How does your computer know what to do when u turn it on ?

How does it know to check out your hardware components


(such as keyboard and monitor) to see that they have been
connected correctly ?

 instructions to perform such operations ,

 which are critical to the operation of a computer. are stored


permanently on a Read Only Memory (ROM) chip installed by
the manufacturer inside the computer.

 this ROM chip are also called FIRMWARE,

 when the power in the computer is turned off.

 the instructions stored in ROM are not lost.


Translator
 These are system software and program's that are
used to convert assembly or high level language into
the Machine Code.
 These are also called Language Processors.
Source Program Translator  Object Program

TYPES =
 Assembler
 Compiler
 Interpreter
Interpreter
 simple and easy to write.
 does not require much memory space to store itself
 translate the program line by line into machine language.

 check for the syntax errors line by line and execute each line or
statement immediately when statement become error free.

 takes less time in translation.


 takes more time to execute the program.
 fast for debugging detection and correction) of syntax and logical
errors.

 the object code is produce by an interpreter is not saved for future


reference.
Compiler
 Complex and difficult to write.
 Requires large memory space to store itself.
 Translate the entire program into machine language at
once.
 Checks the syntax errors in the program and when the
whole program becomes error free than it is translated into
machine code and executed.
 Takes more time in translation.
 Takes less time to execute the program
 Slow for debugging.

 The object code produce by the compiler is saved for the


future reference.
Testing and Debugging

Testing

 Completes when all desired verification against


specification have been performed.

 Testing can be planned

 Testing can begin at early stages.


Debugging

Programming errors are removed.

Completes when there are no known errors.

Cannot be planned ahead of time.

 Cannot begin until the end of development Cycle.


Program Development Life Cycle

It is divided into the following phases=


 Defining the problem.
 Designing the program.
 Coding the program.
 Documenting the program.
 Implementing and Maintaining the
program.
Documentation=

 System documentation involves collecting,


organizing, storing, and otherwise maintaining a
complete historical record of program and other
documents used or prepared the different phases of
the SDLC.

• Uses of Documentation=
easier maintenance
 avoid duplication
CHARACTER SET
C character set includes the

 LETTERS=
 UPPER CASE (A-Z) 
 LOWER CASE (a-z)
 digits (0 - 9)
 special character

 White spaces=
• BLANK SPACES
HORIZONTAL TAB
NEW LINE
FORM FEED

• alphanumeric ,digits, and special symbol


Escape Sequence Character in C

character Escape sequence character

bell \a
back space \b
horizontal tab \t
vertical tab \v
form feed \f
carrier return \r
back slash \\
null \0
question mark \?
C TOKENS
KEYWORD (EX. FLOAT ,WHILE)
( RESERVED WORD )

CONSTANTS (15.5,100)

STRINGS ("ABC","YEAR")
SPECIAL SYMBOL ([ ],{ })

OPERATORS ( + - * , )

IDENTIFIER /
VARIABLE NAME
CONSTANTS IN C=
Constant=quantity that does not change

• Constant are of 2 types=


• primary constant
• secondary constants
• -----------------------------------------------------------------------------
• Primary constant-
• integer constant
• real (FLOAT) constant
• ----------------- -----------------------------------------------------------------
• Character constant
• SINGLE
• STRING
• ------------------------------------------------------------------------------------------
• Secondary Constant
• Arrays
• Pointer
• Structure
• Enum
• Union
• ==============================
Integer Constant=

It must have at least one digit.


• Must not have a decimal point.
• It can be either positive or negative but default is positive.
• No commas and blanks are allowed.
Integer constant are of three types=

(1) Decimal integer =


consists of a set of digits 0 through 9
231, - 333, +55,0, 47777
-----------------------------------------------------------------------------------------------------------------------
(2) Octal integer = Consist of any combination of digits from the set 0 through 7 with a
leading zero .for ex. 0551, 037
----------------------------------------------------------------------------------------------------------------------
(3) Hexadecimal integer= Represent A through F,
-----------------------------------------------------------------------------------------------------------------------
 Real constants (floating point Constants)
a) fractional form=it must have at least one digit and a decimal point.
could be negative and positive.
-------------------------------------------------------------------------------------------------------------
b) exponent form=
< mantissa > e < exponent >
exponent is always in the integer form
and mantissa is always in the fractional form
--------------------------------------------------------------------------------------------------------------
 character constant=
single alphabet or digit or special symbol enclosed within single inverted commas.
Variable=
Name given to the location in the memory where this constant is stored.
• 2 X + 3 Y = 33
• Here X and Y is variable
• here 2 ,3,33 are constant

Rules for Constructing VARIABLE / IDENTIFIER Names

 first character must be alphabet or underscore(_)

 must consist of letters, digits, underscore(_)

 keyword /reserve word are not allowed.

 uppercase and lower case are identical

 must not contain white spaces.


spaces
• C keyword and Reserve Word=
• The words whose meaning has already been explained to the c compiler are
known as keyword the keywords can not be use as variable names.

Standard keyword/Reserve Word in C


• Auto break case
• Character count continue
• Default do double
• Else enum extern
• Float for goto
• If long register
• Return ` sign signof
• Static struct switch
• Typedef union unsign
• Void volatile while
C operators =

 ARITHMATIC OPERATOR
 RELATIONAL OPERATOR
 LOGICAL OPERATOR
ASSIGNMENT
 INCREMENT (++)
 DECREMENT (--)
 CONDITIONAL (IF,ELSE)
 BITWISE
 COMMA ( ,)
 SIZEOF( ) C COMPILE TIME
 POINTER OPERATOR (*.&)
COMMA OPERATOR

• Sum=(x=20,y=30,x+y)
• Expressions are evaluated left to right and the value of rightmost
expressions is the value of the combined expression.
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Sizeof Operator (Compile time operator)

• Returns the number of bytes the operand occupies

• Used to determine the length of array and structure when their sizes are not known
to the programmer

• Used to allocate memory space dynamically to variable during execution of a


program

• Also known as compile time operator.


Ternary / Conditional Operator

• C includes a very special operator called the ternary or conditional


operator
It is called ternary because it uses three operand
• The ternary operator acts like a short hand version of the ternary
operator is
• Expression1: expression2:expression3

• Example:
If (first>second)
Max=first;
Else
Max=second;
The above statement can be written as
Max=(first>second) first: second;
The ? : operator
• C language has a special operator, useful for making two way
decisions .
• This operator is a combinational of ? And : takes three
operands.
• This operator is popularly known as conditional operator or
ternary operator
• The general form of conditional operator is as follows:
• Conditional expression ?<expression1>:<expression2>
• The conditional expression is evaluated first.
• If the result is true, expression 1 is evaluated and returned as
the value of the conditional expression.
• Otherwise expression 2 is evaluated and its value is returned .
• In general conditional operator is used as substitute for simple
if…else Statement
• Consider the following code:
• int a=10;
• Int b=20;
• Int c;

If (a>b)
c=a;
else
c=b;
• This code segment can be written as follows using ternary
operator
C=(a>b) ? a: b
Unary Operator

• - ++ -- ! * & sizeof (type)


• C includes a class of operators that act upon a
single operand to produce a new value such
operator are unary operator
Arithmetic Operator
Operator meaning

+ Addition

- Subtraction

* Multiplication

/ Division

% Module division
Relational Operator
OPERATOR MEANING

< IS LESS THAN


> GREATER THAN
>= Greater than equal to
<= Less than equal to
== Equal to
!= Not equal to
Logical Operator
Operator Meaning

&& AND

|| OR

! NOT
Assignment Operators
• The assignment operator = assigns a value to a variable.
• For example,
• x = 1 sets x to 1,
• and a = b sets a to whatever b's value is.
• We've called the = sign the ``assignment operator'' and
referred to ``assignment expressions'' because, in fact, = is
an operator just like + or -.
• C does not have ``assignment statements''; instead, an
assignment like a = b is an expression and can be used
wherever any expression can appear.
• Since it's an expression, the assignment a = b has
a value, namely, the same value that's assigned
to a. This value can then be used in a larger
expression;
• for example, we might write
• c = a = b which is equivalent to c = (a = b) and
assigns b's value to both a and c.
• (The assignment operator, therefore, groups from
right to left.).
BITWISE OPERATOR
OPERATOR MEANING
& BITWISE AND

| BITWISE OR

^ BITWISE EXCLUSIVE
OR

<< SHIFT LEFT

>> SHIFT RIGHT


• INCREMENT & DECREMENT OPERATOR

• + + and - - are the increment and decrement operator

• + + adds 1 to the operand

• -- subtract 1

• + + and – - -are unary operator and takes the following form

• + + i or I + +

• - - i or I - -
----------------------------------------------------------------------------------------------------------

• ++i
• I=I+1
• I+=1 are equivalent
--------------------------------------------------------------------------------------------------------
• -- i
• I=I-1
• I -=1 are equivalent
---------------------------------------------------------------------------------------------------------
Control Structure in C

 Conditional statement
» If-else

» Else-if

» switch case

 UNCONDITIONAL STATEMENT

• While STATEMENT
• Do while
• for STATEMENT
• jump
• continue
• break
• goto
if -else
• The first statement or block of statements
is executed if the condition is true,
• and the second statement or block of
statements (following the keyword else) is
executed if the condition is not true.
• While loop
• The while loop continues to loop until the conditional expression
becomes false. The condition is tested upon entering the loop.
• Loops generally consist of one or more control expressions which
control the execution of the loop, and the body, which is the statement
or set of statements
• The most basic loop in C is the while loop. A while loop has one
control expression, and executes as long as that expression is true.
• The general syntax of a while loop is
• while( expression ) statement A while loop starts out like an if
statement: if the condition expressed by the expression is true, the
statement is executed.
• However, after executing the statement, the condition is tested again,
and if it's still true, the statement is executed again. (As long as the
condition remains true, the body of the loop is executed over and over
again. (If the condition is false right at the start, the body of the loop
is not executed at all.)
do.. while STATEMENT
do while is a exit control looping structure.
that is loop body will be executed first before evaluating loop control statement.

do while takes the following forms.

initialization of loop control variable:

do
{
body of the loop;
.............
.............

}
While (test condition)
statement x;
do while

once the program get to the do statement the program proceeds


executing the statements in the loop body ,and once it reaches the end of
the loop body, it evaluates the test condition.

if test condition returns true,


the loop body is executed once again and again the test condition is
evaluated once the loop body finishes the execution.
the repeated execution of the loop body continues as long as the test
condition returns true.

the loop get terminated once the test condition returns false
and the program control is passed to the statement that is next to the
loop control.
for statement

the for statement is the most popular and more concise loop control
structure supported by almost all the programming languages.
for is an entry control looping structure.
for is quite efficient looping structure when compared while or do while
because it takes cares of initialization of loop control variable evaluating
loop control statement,
increasing /decreasing the value of loop control variable.
the execution of the loop control variable is done first ,
using assignment statement such as i=1, or count =10 etc,
here i and count are referred as loop control variables,
the value of the loop control variable is tested using test
condition.

the test condition is a relational or logical expression such


as i<10 or (i<10)&&(k>=0) etc.
the test condition is used to direct the execution of the loop
body

if the test condition n is true the body of the loop will be get
executed otherwise the loop will be get terminated and the
execution follows to the next statement that immediately
follows the loop.
when the loop body completes the execution the control is
passed back to the for statement

and then the value of the control variable is incremented


/decremented and tested against the test condition.
to see whether it satisfies the test condition.
if the test condition is satisfied that is if the loop condition
returns true, the loop body will get executed once again.

the process of repeated execution continue till the value of the


loop control variable fails to satisfies the loop condition
C Basic Programs

 write a c program to print ur name?

#include<stdio.h>
#include<conio.h>
void main()
{
int a,b;
clrscr();
printf("my name is MOHIT SHARMA \n3 k 21");
getch();
}
// (print positive –negative )

#include<stdio.h>
#include<conio.h>

void main( )
{
int n;
clrscr();
printf("enter n");
scanf("%d",&n);

if(n>0)
{printf("positive value");
}
else
{
printf("negative value");
}

getch();

}
// (voting program)

#include<stdio.h>
#include<conio.h>

void main()

{
int age;
clrscr();
printf("enter age");
scanf("%d",&age);

if(age>18)

{printf("u can vote");


}

else
{
printf(“ u r child ");
}
getch();
}
// A AND B WHICH IS MAX

#include<stdio.h>
#include<conio.h>

void main()
{
int a,b;
clrscr();
printf("enter a,b");
scanf("%d%d",&a,&b);
if(a>b)
{printf("a is max");
}
else
{
printf("b is max");
}

getch();

}
• FEATUES OF POINTER

• POINTER which points address of a variable

• Pointer Operator * , &


1. pointers are more efficient in handling arrays and data table.

2. use to return multiple values from function.

3. pointer allow and support dynamic memory management.

4. pointers use for manipulating dynamic data structure such as link list, queue,
stack, graph.

5. pointer reduce complexity of program.

6. pointer increase the execution speed of the program.

7. pointer reduce the program execution time


• Rules for Pointer Operation

• A Pointer variable can be assigned the address of another variable.

• A Pointer variable can be assigned the values of another pointer variable

• A Pointer variable can be initialize with zero or null.

• A Integer value can be subtracted or added from pointer variable.

• 2 Pointers variables can not be added.

• When 2 pointer point the same array one pointer variable can be subtracted from the
another variable.

• A Pointer variable can be used increment and decrement operator.


“String Handling Function
in C"
strlen( ) calculates length of a string
strcpy( ) copy the contents of one string into another
strcmp( ) Used to compare to string
strlwr( ) Convert all characters in the given string
from upper case to lower case
strrev( ) Rearrange all character in the given string
in reverse order
Strcat( ) Used to add two given strings
Strupr( ) Convert all characters in the given string
from lower case to upper case
Header file =
The c standard library contains files containing the standard functions that ur program may
use these files are known as header files

<ctype.h> Character class test

<error.h> Error codes reported by some library function

<float.h> Implementations defined floating point limits.

<limits.h> Implementation defined limits


<locale.h> Locale specific information
< stdio.h > Input and Output

< stdlib.h > Utility Functions

< string.h > String Functions


< time.h > Time and Date Function
< signal.h > Signals
< math.h > Mathematical Function
Modular Programming=

 Modular Programming is a strategy applied to the design and development of software


system.

 It is defining as organizing large program into small program.


Into small independent program segment called modules.

Some Characteristics of Modular Programming

 Each module should do only one thing.

 Communication between module is allot only by calling a module.

 A module can be call by one and only one higher module.

 All module design a single entry and single exit.


Executing a c program
 Creating the program
 Compiling the program
 Linking the program
 Executing the program

BASIC structure of c program

 DOCUMENTATION SECTION
 LINK SECTION
 DEFINITION SECTION
 GLOBAL DECLARATION SECTION
 MAIN FUNCTION SECTION
 SUB PROGRAM SECTION
• Documentation section
 consist of a set of comment lines giving the name of the program
 the author or programmer and other details

• Link section
 provides instructions to the compiler to link functions from the system
library

• Definition section
 defines all symbolic constants.

• Global declaration
 global variables and user define function

• main() function (declaration and executable part)


 declaration part declares all the variables used in the executable part
that consist of group of statements.
• Subprogram section (user defined function)
 contains all the user define functions called in the main program of the
function.
AN ARRAY IS A :
collection of data element that are of identical data type
stored in consecutive memory locations and are referred by a common
name.
till now in our programs we've seen variables which can store only one
value at any given point of time,.
but it is often required in programming that u may need to store a
group of values in one variable.
for example
u want to store marks obtained by 100 students of the class in a
particular subject
or u want to store name of a 100 student which is of 10 character in
length.
but where as an integer or characters variable can store only value at a
given point of time,
in such sought of cases arrays come in handy for the programmer.
for ex.
if we want to store marks of 100 students instead of declaring 100
variables u can declare a special kind of variable called array in the
following manner

int marks[100] ;

now marks is an array which can store 100 integer values.


if u want to store name of a student which is of 15 character in length, u
can declare a character array in the following form.
char name[15] ;
now name is an array which is capable of storing 15 character values.
u can arrays for all the data type that are supported by C.
Declaring an Array

like any other variables arrays must be declared before they are used

the general form of array declaration is


type variable-name[size]

the type specifies the data type of the element in an array


variable name specifies the name of the array
size specifies the no. of elements going to be stored in an array.

for ex.
int arr[5];
now we have created an array that can store 5 integer values.
Memory Representation of Array

for ex.
int arr[5];
now we have created an array that can store 5 integer values.

all the elements of the array gets stored in consecutive memory locations.

in the above ex. we have declared an array that can stored 5 integer values
suppose the first element of the array is stored in 80th address location then the
second element gets stored in 82th ,
third in 84th ,
fourth in 86th and fifth in 88th address location
(remember each integer occupies 2bytes of storage in memory ,that is why address
locations are 80,82,84,86,88)
the above statement int arr [5] creates an array in the following manner in
computer memory

Size of an array:
U can find the size of an array ,by performing following
computation.
No of elements in an array *size of an array
Hence the size of the array int arr [5] would be 5 * sizeof (int)
That is 5*2=10 bytes (size of an int type on a 16bit machine is 2
bytes.)
Initialize an array
We can initialize the element of array either at the time of declaration or any where else in the
program .
Some of the general forms of the initializing an array are as follows
Initializing an array elements at the time of declaration
Int arr[5]={42, 13 ,87 ,76 ,54};

Initialize an array element after declaration


Int arr[5];
arr[0]=42;
arr[1]=13;
arr[2]=87;
arr[3]=76;
arr[4]=54;
Code for initializing elements of array by accepting values from
keyboard

Int arr[5];
Int i;
For (i=0; i<5; i++)
{
Scanf (“ %d ”, & arr [i] );
}
Array in memory after initialization

Value stored in an array

42 13 87 76 54

Addresses of an individual
element in an array
Referring to the elements of an array
The main thing after declaring and initializing an array is how to
access the individual element of an array.
If u observe, while initializing elements of an array we have used
arr[0],arr[1]…. and so on.
From that we got a little bit of idea on how to refer to individual
element of an array.

We can access or refer to the individual elements of an array


through their position or location in the array.
The position or location of an element in an array is commonly
referred as array subscript.
An array subscript always starts from().
That is the first element of an array can be referred as arr[0],
Second element can be referred as arr[1]
Third element is referred as arr[2]
And so on ………

42 13 87 76 54
Storage class in C
Automatic storage class, auto
local variable known to only to the function in
which it is declared .default is auto.

Register storage class register


Local variable which is stored in register

Static storage class static


Local variable which exists and retains its value
even after the control is transferred to the
calling function.
External storage class extern
Global variable known to all functions in the
file.
User defined type declaration
• C support a feature known as type definition” that
allows users to define an identifier that would
represent an existing data type.
• The user define data type identifier can later be used
to declare variables.
It takes a general form:
typedef type identifier;
• Where type refers to an existing data type and
“identifier “ refers to the “new” name given to the data
type.
• The existing data type may belongs to any class of
type, including the user defined ones.
• Remember that the new type is new only in name, but
not the data type .
• typedef cannot create a new type.
• Some examples of type definition are:

typedef int units;


typedef float marks;

• Here unit symbolizes int and marks symbolizes float.


• They can be later used to declare variables as follows:

Units batch1,batch2;
marks name1[50],name2[50] ;

• Batch1 and batch2 are declared as int variable and name[50] and
name2[50] are declared as 50 element floating point array variable.
• The main advantage of typedef is that we can create meaningful data type
names for increasing readability of the program.
• Another user defined data type is enumerated data type provided by ANSI
standard .
• It is defined as follows.
FUNCTION
User Define Function

 the use of user define function allows a large program to be


broken down into a no of smaller self content component.

 c program can be modular with the use of a function.


for ex.
many program require that a particular group of instructions
be access repeatedly from several different places with in the
program

 the repeated instructions can be placed with in a single


function which can then be accessed whenever it is needed.
The use of function avoids the need of redundant
programming in the same instructions=

a function is a self content program segment.

 every program consist of one or more function.

 one of the function must be call a main function.

 if program contain multiple function then there definition


may be in any order.

 thesame function can be access from several different


places with in a program.
Function Terminology

 function definition=

 formal parameter

 actual parameter

 function name

 calling a function

 prototype of a function (function declaration)


 call by value

 call by reference

 Recursion (function call by itself)

 function with argument but no return value

 function with argument but return value

 function with no argument and no return value.

 function returns multiple values.


function
user defined function

primitive function
math.h
•abs()

•log()

sqr()

•exp()

cos()

sin()
• Some points Regarding to the Recursion

• when function call by itself is called recursion

• in order to solve a problem recursively to condition must be


satisfied.
• the problem must be return in recursive form

• the problem statement must include a stopping condition.


• when recursive function is executed the function call are not
executed immediately they are placed on the stack.

• the tower of Hanoi is a good illustration example for the


recursion technique.
CATEGORY OF FUNCTION

category 1 = function with no argument no return value

category 2 = function with argument no return value.

category 3 = function with argument but return value.

category 4 = function with no argument but return value.

category 5 = function that return a multiple values.


Function
A function is a self contained block of statements that have been given a name
and performs different task of some kind.

Why we need functions ?


• most real programs are much larger than the small samples we have looked at.
• c follows procedural approach towards programming and hence , functions play a
major role in program development.

Advantages of using functions =


• function supports top down approach towards programming.

• The length of the source program can be reduced by using functions at appropriate
places.

• This factor is particularly important when functions are having limited memory.

• Function support reusability of code.

• A function once written ,compiled and packaged into a library can be reused in
many other program without rewriting the code.
C functions can be classified into two categories :
• Library functions
• User defined functions
• The basic difference between the two is =
• Library are prewritten, compiled packaged into
Header files and are made as a part of c standard
library.
• The functions like printf (), scanf () etc. are a part of
C Standard Library,
• Where as an user defined functions needs to be
written by the programmer according to the
requirements of the application he is developing.
User Defined Functions
for example:

# include < stdio.h >


int square( int) ; //function prototype
main ( ) //calling function
{
int num, s;
printf (“enter a no for which u want to find square \n ”) ;
scanf ( “ %d ” & num) ;
s=square (num) ; //called function
printf ( “square of %d is %d \n “ num , s );
}
int square (int i) //function definition (header)
{
return i*i ; //function definition( body)
}
Function Prototype
A function prototype provides the basic information that compiler
needs to check that a function is being used correctly or not in the
program.
The function prototype specifies the following :
Type of the return value:
for ex. (int /float/char)
• Function name
for ex. sum , multiply , divide etc.
• Number order and types of the argument passed to the function

• Essentially the same information as appears in the function


header with the addition of the semicolon.

• Function prototype must appear before the statement that call the
respective functions and are usually placed at the beginning of the
program
• In the above program the line int square (int) ; is the function
prototype.
• A part of the function prototype is the function signature
• A function signature is the consist of the name of the function and
order and type of the arguments
• In the above ex..=
int square (int) ; //function signature

• one more thing u need to remember is function signature must be


unique for each and every function and u cannot have two functions
with the same signature in one program
Function Definition
function definition contains the actual implementation of the function .
function definition can be divided into two parts=
• Function Header
• Function Body

Function Header
return type function name ( Argument list )
argument declaration ;

( or )

return type ( Argument along with Declaration)


ex.

int add (x ,y)


int x , y;

(or )

int add (int x, int y )


Function Body
function body contains the actual code that
implements the functionality of the function.
in general function body contains declaration of local
variables and statement and generally looks in the
following form:
{
local variable declarations;
function statements;
……………
……........
return ( expression) ;
}
hence, altogether ,
Function Header + Function Body
together makes function definition and a complete function
definition looks as follows:

return type Function name (Function arguments)


{
Local Variable Declaration;
Function Statements ;
…….......
……………..
return (expression) ;
}
Function Arguments
Function arguments are used to pass input to the function .
Arguments are optional and a function can have one or more Arguments
to a function each and every argument at all.
when u are pass multiple arguments to the function each and every
argument must be separated by a comma.
there are two types of function arguments =
Formal Arguments
Actual Arguments

Formal Arguments
Formal Arguments are valid variables that are used in Function
Header of the function definition in order to store the values of the
actual arguments.
Formal Arguments are must be surrounded by parenthesis.
must not be terminated by using a semicolon.
Actual Arguments
Actual Arguments are the values that are passed to a
Function during a Function Call
An actual argument can be either a variable or constant or
valid expression .
one more thing is to be remember is the type and order of
the actual arguments must match the formal arguments.
Function call
• A function is invoked using a function call.
A function call requires the programmer =
• To specify the specific function by name
• “Pass “data to the function that it needs: (arguments)
• Functions optionally return a single “value” to the
caller ,which needs to be trapped for further use in
the program.
The function that is invoking another function is
refereed as calling function , and the function that
has been invoked is referred as called function.
ex. boss to worker analogy
• a boss (the calling function or caller ) tells a worker
(the called function) to perform a task and return
(i.e. report back) the results when the task is done.
• one more thing we need to remember here is once function
call is made (calling function invokes Called Function),

• the program control is transferred from the calling function


to the called function , and when the called function finishes
its execution ,
• the program control is transferred back to the calling
function.
Return Value
• once the called functions finishes its execution, it may
return a value to the calling function informing whether it
has finished the execution successfully or not,
• which is commonly refereed as return value a function may
or may not send back any value to the calling function.
• if it does, it through a special statement known as return.
• while it is possible to pass any no. of arguments to the
called function, but a called function can return only one
value to the calling function ,that also by
• using return statement. The return statement can take one of the
following forms:
return ;

or

return (expression) ;

the first form return doesn’t return any value;


it acts simply as the closing brace for the function.
the second form of the return statement returns the value of the
expression to the calling function.
when return statement is encountered ,
the execution of called function gets terminated and
the program control is immediately passed back to the calling
function through return statement may or may not return a
value to the calling function .
a function may have more than one return statements.
this situation arises when the value returned is based on certain
conditions.
for example:
if (x<=0)
return 0;
else
return 1;
a function returns an int value by default .however we
can force the function to return a particular type of
data by using a type specifier in function header.
example:
float circle area (int radius)
float squareroot (num)
A function that doesn’t return any value to the calling
function simply specify its return type as
void (which means nothing )
void getsdetails()
void prime()
basics of functions

return type function name (type of argument) ; //function prototype


main() //calling function
{
……………..
……………//function call
variable =function name (actual arguments); //called function
………..
…………..
}
return type function name (declaration of formal arguments) //function header
{
declaration of local variables
function arguments;
……….
………….
return value;
}
• Components of a Function
• funcrtion header
• defines the function name,return type and the number and types of
the parameters

• Paramerters
• information flow to the function

• Local variables
• variables and witin the function (private to the function)created when
function is called, ”destroyed”when functions returns.

• Function Body
• contains the software that implements the function

• Return Staement
• specifies the value that is returned to the caller,returns flow of
execution to the caller
Without Return Value without Argument

• Rule :
• When the value is not return then it is essential to write void
in definition.

• When the value is return then we can not use void in the
definition part.
• when the value is return then we write
int function name;
then we also write
int definition;
and
then we also write
int declaration;
Calling a function:
• a function can be called by simplifying using the function
name in an statement .
• example:
void main()
{
int p;
p=mul(10 , 4);
printf (“ %d ”,p);
}
• when the compiler encounters a function call, the control is
transferred to the function mul (x , y).
• this function is then executed line by line as described and a
value is returned when a return statement is encountered
.this value is assigned to p.
No arguments and No return values

• when a function has no argument ,it does not receive


any data from the calling function.
• similarly when n it does not return a value, the
calling function does not receive any data from the
called function.
# header file //without return value without argument

void main()
{
void sum( ); //declaration
sum(); //calling the function
sum(); //calling the function
sum(); //calling the function
getch();
}
void sum() //definition
{
int x,y,z;
printf( “enter the value of x , y ”);
scanf (“%d %d”,&x,&y);
z=x+y;
printf (“ the z is % d ”,z”);
}
# header file //With return value Without argument
void main()
{
int a,b; //data type declare
int sum(); // function declaration
a= sum( ); //calling the function
b=sum( ); //calling the function
printf(“%d”,a);
printf(“%d”,b);
getch();
}
int sum() // function definition
{
int x,y,z;
printf( “enter the value of x , y ”);
scanf (“%d %d”,&x,&y);
z=x+y;
return(z);
}
# header file // Without return value With Argument
void main()
{
int square( int x ) ; //declaration
int z,a;
scanf(“%d”,&a);
z=square(a);
printf(“%d”,z);
getch();
}
int square (int x) //definition
{
int y ;
y = x * x;
printf (“%d”,y);
}
# header file //with return value with argument
void main()
{
int square( int x); // function declaration
int z, a; //datatype declare
scanf(“%d”,&a);
z=square(a);
printf(“%d”,b);
getch();
}
int square (int x) // function definition
{
int y ;
y =x *x ;
return (y);
}
VARIABLE DECLARATION=

 LOCAL
(ONLY FOR SUB PROGRAM)

 GLOBAL
(FOR WHOLE PROGRAM)

FOR EX.

int x,y,z;-->global declaration

main()
{
subprogram-->function

int p
......
return 0;
}
Unformatted Console I/O

 get char( ) one character read / scanf (“ %c “ ,


&x)

 putchar( ) one character output

 gets( ) string read

 puts( ) string output


The main( ) Function

Following forms are allowed

• main( )

• int main()

• void main()

• main(void)

• Void main (void)

• int main( void)


Function Declaration consist of 4 type=

 Return type

 Function Name

Parameter list / Argument

 Semicolon
Standard library files=
 conio.h
 math.h
 ctype.h
 string.h
 time.h
• Defining structures
• a structure is a collection of variables under a single
name.
• these variables can be of different types, and each
has a name which is used to select it from the
structure.
• a structure is a convenient way of grouping several
pieces of related information together.
Declaring structure
• the general form of declaring a structure is as follows:

struct <structure name>


{
structure element 1;
structure element 2 ;
structure element 3;
…………
…………..

};
example:

struct student
{
char name[20];
int age;
float height,weight;
};

note: a structure declaration must always terminate


with a semicolon.
Accessing element of structure
• in order to access the elements of a structure ,first of all we need to
create an instance variable for structure and then we can access the
elements of the structure through its instance3 variable
• we can create an instance variable for a structure either at the time of
declaring the structure or anywhere else in the program.

• once we declared the structure we create an instance variable for a


structure we can access the structure elements in the following form:
• structure_variable. structure element
example:
• s1.name;
• s1.height
• s1.float and so on.
• initializing the no. of a structure variable
• the members of the structure variable can be initializwed either at the time of
declaring the structure variable or any where else in the program

• exmple program for in\itializing structure variable at the time of declaration


#include<stdio.h>
struct student
{
char name[20];
int age;
float height, weight;
};
main()
{
struct students={“mohit”,23,5.5,54,0};
clrscr();
printf(“student name%s \n “,s.name);
printf(“student age%d \n” s.age);
printf(“student height %f weight %f \n”,s.height,s.weight);
printf(“student height %fweight %f \n “,s.height,s.weight);
}
• output of the above program is as follows:
• student name mohit
• student age 23
• student height 5.5 weight 54
• array of structures
• in array of structures we store the details of all the
students in a class.
• array of structure are similar to the normal array
except the difference that they belong to a structure
instead of primitive data type.
• the following example gives u a clear idea about the
same

#
#include<stdio.h>
struct student
{
char name[20];
int age;
float height, weight;
};
main()
{
struct students s[5];
int i;
clrscr( );
for( i=0 ; i<5; i++)
{
printf(“enter student name\n”);
scanf(“%s”,&s[i].name);
printf(“enter student age”);
scanf(“%d”,&s[i] ,age);

printf(“enter student height and weight”);


scanf(“%f %f ,&s[i].height,&s[i].weight);
}
clrscr();
for(i=0; i<5; i++)
{
printf(“student name%s \n”,s[i].name);

printf(“student height %f weight %f \n “,s.height,s.weight);


printf(“student age %d \n”,s[i].age);
printf(“student height %5.2f \n”s[i].height);
printf(“student weight %5.2f \n “,s[i].weight);

}
getch();
}
• structures and pointers

• a pointer pointing to a structure is referred as structure pointers’


• example program to access elements of a structure using pointer

#include<stdio.h>

strucrt student
{ char name[20];
int age;
float height,weight;
};
main()
{
struct student s,*ptr=&s;
printf(“enter name\n”);
scanf(“%s”,&ptr->age);
printf(“enter age \n”);
scanf(“%d”,&ptr->age);
printf(“enter height and weight of the student \n”);
scanf(“%f%f”,&ptr->height,&ptr->weight);
printf(“name\t%s\n”ptr->name);
printf(“age\t%d\n”,ptr->age);
printf(“height\t%5.5f \t weight \t %5.2f\n”,ptr->height,ptr->weight)”
getch();
}
File System

• File is a collection of Record.

File function in C =

• fopen
• fclose
• fscanf
• fprintf
• putc
• putw
• getc
• getw
• wind
• ftail
• fsick
• File Operation

• Creation
• updation
• Insertion
• deletion
• modification
• Maintenance
• retrieval
• Some question of c language
• who developed c language?
• Dennis Ritchie

……………………………………
• give 2 ex. of OOP?
• c++, java, c sharp
……………………………………..

• what is mean by token?


operator ,string, identifier
…………………………………….

• what is role of main() in c?


…………………………………………
what are variables? How u create a variable?

first character must be alphabet or underscore(_).

must consist of letters, digits, underscore(_).

keyword / reserve word are not allowed.

only first 31 character are significant.

uppercase and lower case are identical.

 must not contain white spaces.


• list the 3 types of integer supported by c?
• octal, hexa, decimal
• ……………………………………..
• what are escape sequence?
• escape sequence character in c

• character escape sequence character

• bell \a
• back space \b
• horizontal tap \t
• vertical tab \v
• form feed \f
• carrier return \r
• back slash \\
• null \0
• question mark \?
…………………………………………………..
• what are constants?
• int ,char, float
Q
• what are the fundamental data types in c?
……………………………………
• what is the range of integer, character, float?
…………………………
• name 4 data types modifier?
………………………………..
• name the operators in c?
…………………………..
• name dynamic data structure?
• stack, queue, linked list.
……………………………………
Q
• write the ways to write main()?

• write the name of user defined data types/

• what is the basic structure of c program/

• write the steps to execute the c program?

• what are the two types of errors?

• what do u mean by semantic errors?

• what are the various c compiler are available?

• name the Linux based c compiler?

• what are the three section of c pre processor?

• what is trigraph sequence?

• name some client side and server side scripting language?


Q
• Mohit sharma
• itsmohitonly@gmail.com
• Contact for software development and
web site development work,projects