SlideShare uma empresa Scribd logo
1 de 161
C-program
 Assembler is a translator software that
translates assembly language program
into equivalent binary language
 Compiler converts the high level source
program into machine readable form at
once.compiler will check all statements
for syntax error and after correcting
errors ,it will convert source program to
object code
 Interpreter translates the source program
statements one after another. Only after
the successful completion of first
instruction it will take next instruction.
Source and object code
 Programs written in high level languages
are known as source program.
 The source program which are
translated into machine language is
known as object program.
 There are mainly 3 translator programs
used to convert source program to
object program
1. Assembler
2. Compiler
3. interpreter
Algorithm
 An algorithm is the steps to solve a problem
 Written in simple English
 Every instruction should be precise
 First Understand the problem, i. e try to
find out objective , available data and which
process is suitable to get correct output
Sample,
Find total marks by adding internal and
external marks
Step 1: Start
Step 2: Read/Input internal mark and
external mark
Step 3: Add internal with external to get
total
Step 4: Display total marks
Step 5: Stop
flowchart
Flowchart is a pictorial representation of an
algorithm
Symbols
Terminal (oval )
Indicate beginning (START)
and ending (STOP)
Input/Output( parallelogram )
Denote input and
Output related functions
START
Display total
Processing(Rectangle)
Represents Arithmetic and
logical operations
e.g.
Decision( Diamond )
Indicates a point which a
decision has to be made
E.g. Checks that value of a is
t greater than value of b,
if it is true , continued to
f next task ,else it will go
to false side
total=a+b
Is
a>b
Flow lines
indicates flow of operation
Connector
If the chart becomes too long to fit in a single
page , we can use connectors
 Flowchart
for finding
total of
internal
and
external
marks
START
STOP
Read
Internal
,external
Display total
Total=internal+
external
Step 1: Start
Step 2: read
length(l)
and
breadth(b)
Step 3: A=l x b
Step 4: Display
Area,A
Step 5: Stop
START
STOP
Read l,b
Display
Area,A
A=l x b
Step 1: Start
Step 2: read
num1,num2
Step 3: check
num1>num2 if true
then Display num1 is
largest
Else Display num2 is
largest
Step 5: Stop
START
STOP
Read
num1,num2
Display num1 is
largest
Is
num
1>
num
2
Display
num2 is
largest
true
false
C language
 It is a high level language
 Developed by Dennis Ritchie in 1970s
 Used for system programming as well as
application programming
 Programs written in c are fast and
efficient
 Supports a variety of data types and
powerful operations
 There are 32 keywords which are easy to
learn and use
 It has many built in functions
Features of C Language:-
There are many features of c language are given
below.
1) Simple
2) Machine Independent or Portable
3) Mid-level programming language
4) structured programming language
5) Rich Library
6) Memory Management
7) Fast Speed
8) Pointers
9) Recursion
10) Extensible
C TOKENS:
 C tokens are the basic buildings blocks in C language
which are constructed together to write a C program.
 Each and every smallest individual units in a C program
are known as C tokens.
 C tokens are of six types. They are,
 Keywords               (eg: int, while),
 Identifiers               (eg: main, total),
 Constants              (eg: 10, 20),
 Strings                    (eg: “total”, “hello”),
 Special symbols  (eg: (), {}),
 Operators              (eg: +, /,-,*)
C TOKENS EXAMPLE PROGRAM:
 int main()
{
int x, y, total;
x = 10, y = 20;
total = x + y;
Printf (“Total = %d n”, total);
}
 where,
 main – identifier
 {,}, (,) – delimiter
 int – keyword
 x, y, total – identifier
 + - Operators
 main, {, }, (, ), int, x, y, total ,+ – tokens
IDENTIFIERS IN C LANGUAGE:
 Each program elements in a C program are
given a name called identifiers.
 Names given to identify Variables, functions
and arrays are examples for identifiers. eg. x
is a name given to integer variable in above
program
AUTO DOUB
LE
INT STRU
CT
CONS
T
FLOA
T 
SHOR
T
UNSIG
NED
BREA
K
ELSE LONG SWITCHCONTINUE FOR SIGNED VOID 
CASE ENUM REGISTERTYPEDEFDEFAULTGOTO SIZEOF
 
VOLATI
 
CHAR EXTERNRETURNUNION DO   IF STATIC
 
WHILE
AUTO DOUBLE INT STRUCTCONST FLOAT
 
SHORT UNSIGN
BREAK ELSE LONG SWITC
H
CONTI
NUE
 FOR SIGNE
D
VOID 
CASE ENUM REGIS
TER
TYPE
DEF
DEFA
ULT
GOTO SIZEO
F 
VOLA
TILE 
CHAR EXTE
RN
RETU
RN
UNION DO   IF STATI
C 
WHILE
KEYWORDS IN C LANGUAGE:
 Keywords are pre-defined words in a C
compiler.
 Each keyword is meant to perform a specific
function in a C program.
 Since keywords are referred names for
compiler, they can’t be used as variable
name.
 C language supports 32 keywords which are
given below
C - VariablesC - Variables
 A variable is nothing but a name given to a
storage area that our programs can
manipulate.
 The name of a variable can be composed of
letters, digits, and the underscore character.
 It must begin with either a letter or an
underscore.”first_name”
 Upper and lowercase letters are distinct
because C is case-sensitive. 
C - Data Types
 The type of a variable determines how
much space it occupies in storage and
how the bit pattern stored is
interpreted.
 Basic data types
------ char,int, float, double
 Derived data type
----- pointer, array, structure, union
 Void data type
----- void
Integer data type
 Integer data type allows a variable to
store numeric values.
 “int” keyword is used to refer integer
data type.
 The storage size of int data type is 2 byte
or 4 or 8 byte.
 int (2 byte) can store values from -32,768
to +32,767
Character data type
 Character data type allows a variable to store
only one character.
 Storage size of character data type is 1 byte.
We can store only one character using
character data type.
 “char” keyword is used to refer character data
type.
 For example, ‘A’ can be stored using char
datatype. You can’t store more than one
character using char data type.
Floating point data type
 Floating point data type consists of 2 types.
They are, Float & double
1. float:
 Float data type allows a variable to store
decimal values.
 Storage size of float data type is 4 byte. This
also varies depend upon the processor in the
CPU as “int” data type.
 We can use up-to 6 digits after decimal using
float data type.
 For example, 10.456789 can be stored in a
variable using float data type
2.double:
 Double data type is also same as float data
type which allows up-to 10 digits after decimal
point
Void data type in C:
 Void is an empty data type that has no value
operators
Two types of operators are there,
1. Arithmetic operators
2. Relational Operators
3. Logical Operators
4. Assignment Operators
5. Increment and decrement operator
Assume variable A holds 10 and
variable B holds 20, then −
30
Relational Operators
•Relational and comparison operators are
used for comparing two operands (Data).
•These operators give the result as either
true or false.
•Actually in C, any non-zero value is
treated as true and a zero is treated as
false
•Relational expressions are use in
decision making statements
Relational Operators used in C are
Operator Meaning
< Less than
> Greater than
<= Less than or equal to
>= Greater thanor equal
to
== equal to
!= not equal to
NOT(!)
Chooses the value from false to true
or from true to false.
Truth table of NOT is
!True False
! False True
The logical operators are used to test
more than one condition and make
Decisions
LOGICAL OPERATORS 
Operator Meaning
! NOT
&& AND
|| OR
AND(&)
In the case of and , the final answer is true
If both the condition on the left and on the
right of && operator Otherwise False
Truth table of AND is
True && True True
True && False False
False && True False
False && False False
OR Operator(||)
The result of an OR operator is true if
at least anyone condition in the left
side or the right side of the operator is
true; otherwise is false Truth table of
OR is
True || True True
True || False True
False || True True
False || False False
Assignment Operators
Assignment Operator is used to assign a
value or result of an Expression
Usual Assignment Operator is Equal to “=“
E. g
a=b; means the value of b is assigned to a.
= C = A + B will assign the value of A
+ B to C
+=
C += A is equivalent to C = C + A
-= C -= A is equivalent to C = C - A
*= C *= A is equivalent to C = C * A
/= C /= A is equivalent to C = C / A
%= C %= A is equivalent to C = C % A
Increment  and decrement operator 
C provides Two Special operators, one for
incrementing (++)and the other for
decrementing (--)
Increment operator add one with the operand.
It is a unary operator.
There are two forms of increment operators,
Prefix(++operand)
Postfix (operand++ )
If they are used with a single variable, both
are same,
However if they are used in expression prefix
and postfix operations give different results
In prefix operation,first variable is
incremented then the expression is
evaluated.
In Postfix operation, First it evaluate
the expression then the value of the
variable is incremented
Syntax
The rules for forming instruction
Comments
Comments are non executable
statements .
Syntax for comment,
/*this is comment*/
// also represents comment
//this is comment
Structure of c program
Documentation section
Preprocessor directives
Global variable declaration
main() function section
{
Declaration part
Statement part
}
Subprogram section
Function1
Function2
Preprocessor directive
Used to load built in functions and define
formulas
Start with # symbol
#define directive – used to define constants ,
formulas
E.g. #define Pi3.14
#include directive – used to include header
files
Syntax : #include<filename>
E. g. #include<stdio.h>
Header files
 Used with pre-processor directive
 Extension is “ .h ”
stdio.h
Standard input output functions , data types
are in this header file.
String.h
String functions are included in this file.
Math.h
Mathematical functions are defined in this header
file.
 The first line of the c program
#include<stdio.h>
The main() function
 Every c program have one
main() function
 () – indicates a function
 Main() contains two parts,
declaration part
execution part
All statements in these area
must terminate with a semicolon
“ ; ”
printf ()
  The usually used output statement is printf ().
 It is one of the library functions.
Syntax : printf (“format string”, argument list);
 Format string may be a collection of escape sequence
or/and conversion specification or/and string
constant. The format string directs the printf function
to display the entire text enclosed within the double
quotes without any change.
SCANF FUNCTION
The usually used input statement is scanf ()
function.
Syntax of scanf function is 
       scanf (“format string”, argument list);
 The format string must be a text enclosed in
double quotes. It contains the information
for interpreting the entire data for
connecting it into internal representation in
memory.
Example: integer (%d) , float (%f) , character
(%c) or string (%s).
format string
Type specifier
 %c –single character
 %d – decimal character
 %f – floating point value
 %s – string
 %x – hexadecimal value
 %l –long integers/double
  The argument list contains a list of variables
each preceded by the address list and
separated by comma. The number of
argument is not fixed; however
corresponding to each argument there should
be a format specifier
argument list
Escape sequence:
                 Escape sequence is a pair of character.
The first letter is a slash followed by a character.
Escape sequence help us to represent within the
format string invisible and non-printed character
although there are physically two characters in any
escape sequence.
Escape
sequence
Meaning
n New line
t Tab
b Back space
Basic structure
#include<stdio.h>
Void main()
{
printf(“this is my first
program:”);
}
#include <stdio.h>
Void main()
{
int a = 21;
int b = 10;
int c ;
c = a + b;
printf("Line 1 - Value of c is %dn", c );
c = a - b;
printf("Line 2 - Value of c is %dn", c );
c = a * b;
printf("Line 3 - Value of c is %dn", c );
c = a / b;
printf("Line 4 - Value of c is %dn", c );
c = a % b;
printf("Line 5 - Value of c is %dn", c );
c = a++;
printf("Line 6 - Value of c is %dn", c );
c = a--;
printf("Line 7 - Value of c is %dn", c );
Getch(); }
55
 Write a c program to read a number and print it .
#include <stdio.h>
void main()
{
int a;
 printf("Enter an integern");
scanf("%d",&a);  
printf("Integer that you have entered is %dn", a);  
getch();
}
 Write a C program to add two floating
point numbers.
#include<stdio.h>
Void main()
{
float a, b, c;
printf("Enter two numbers to addn");
scanf("%f%f",&a,&b);
c = a + b;
printf("Sum of entered numbers = %fn",c);
  getch();
}
 n – print in new line
 t – provide a tab space
Type casting
 Type casting is simply a mechanism by which we
can change the data type of a variable, no matter
how it was originally defined.
 When a variable is type casted into a different
type, the compiler basically treats the variable as
of the new data type. 
EXAMPLE
#include<stdio.h>
void main()
{
int a=5, c = 0, b=8;
float d = 0;
c = a/b;
printf("n Answer without type casting:%f
n",c);
d = (float)a/(float)b;
printf("n Answer with type casting: %f n",d);
getch();
}
 Write a C program to perform basic
arithmetic operations which are addition,
subtraction, multiplication and division of
two integer numbers
#include <stdio.h>
void main()
{
int first, second, add, subtract, multiply;
float divide;
printf("Enter two integersn");
scanf("%d%d", &first, &second);
add = first + second;
subtract = first - second;
multiply = first * second;
divide = first / (float)second; //typecasting
 
printf("Sum = %dn",add);
printf("Difference = %dn",subtract);
printf("Multiplication = %dn",multiply);
printf("Division = %.2fn",divide);
  getch();
}
Decision making in C
 Decision making is about deciding the order
of execution of statements based on
certain conditions
 or repeat a group of statements until
certain specified conditions are met.
 C language handles decision-making by
supporting the following statements,
1) if statement
2) switch statement
 Simple if statement
The general form of a simple if statement
is,
if( expression )
{
statement-inside;
}
statement-outside;
If the expression is true, then 'statement-
inside' it will be executed, otherwise
'statement-inside' is skipped and only
'statement-outside' is executed
Example :
#include <stdio.h>
void main( )
{
int x,y;
x=15; y=13;
if (x > y )
{
printf("x is greater than y");
}
getch();
}
if...else statement
 The general form of a
simple if...else statement is,
if( expression )
{
statement-block1;
}
else
{
statement-block2;
}
If the 'expression' is true, the 'statement-block1'
is executed, else 'statement-block1' is skipped
and 'statement-block2' is executed
#include <stdio.h>
void main( )
{
int x,y;
x=15;
y=18;
if (x > y )
{
printf("x is greater than y");
}
else
{
printf("y is greater than x");
}
}
 In if statement, a single statement can be
included without enclosing it into curly braces { }
int a = 5;
if(a > 4)
printf("success");
No curly braces are required in the above case, but
if we have more than one statement
inside if condition, then we must enclose them
inside curly braces.
 == must be used for comparison in the expression
of if condition, if you use = the expression will
always return true, because it performs
assignment not comparison.
 Nested if....else statement
The general form of a nested if...else statement is,
if( expression )
{
if( expression1 )
{
statement-block1;
}
else
{
statement-block 2;
}
}
else { statement-block 3; } 
if 'expression' is false the 'statement-
block3' will be executed, otherwise
it continues to perform the test for
'expression 1' . If the 'expression 1' is
true the 'statement-block1' is
executed otherwise 'statement-
block2' is executed
Example :
#include <stdio.h>
#include <conio.h>
void main( )
{
int a,b,c;
clrscr();
printf("enter 3 number");
scanf("%d%d%d",&a,&b,&c);
if(a>b)
{
if( a > c)
{
printf("a is greatest");
}
else
{
printf("c is greatest");
}
}
Else
{
if( b> c)
{
printf("b is greatest");
}
else
{
printf("c is greatest");
}
}
getch();
}
else-if ladder
The general form of else-if ladder is,
if(expression 1)
{
statement-block1;
}
else if(expression 2)
{
statement-block2;
}
else if(expression 3 )
{ statement-block3; }
else default-statement;
The expression is tested from the
top(of the ladder) downwards. As
soon as the true condition is found,
the statement associated with it is
executed.
Example :
#include <stdio.h>
#include <conio.h>
void main( )
{
int a;
printf("enter a number");
scanf("%d",&a);
if( a%5==0 && a%8==0)
{
printf("divisible by both 5 and 8");
}
else if( a%8==0 )
{
printf("divisible by 8");
}
else if(a%5==0)
{
printf("divisible by 5");
}
Else
{ printf("divisible by none"); }
getch();
}
getch();
}
05/28/18
 The general form of switch
statement is,
switch(expression)
{
case value-1:
block-1;
break;
case value-2:
block-2;
break;
case value-3:
block-3;
break;
default:
default-block;
break;
}
05/28/18
 1. We don't use those expressions to evaluate
switch case, which may return floating point
values or strings.
 2. It isn't necessary to use break after each
block, but if you do not use it, all the
consecutive block of codes will get executed
after the matching block.
05/28/18
Example
int i = 1;
switch(i)
{
case 1:
printf("A"); // No break
case 2:
printf("B"); // No break
case 3:
printf("C");
break;
}
05/28/18
 Output : A B C
 The output was supposed to be only A because
only the first case matches, but as there is no
break statement after the block, the next
blocks are executed, until the cursor
encounters a break.
 default case can be placed anywhere in the
switch case. Even if we don't include the
default case switch statement works.
05/28/18
Example of Switch Statement
#include <stdio.h>
void main()
{
int Grade = 'B';
switch( Grade )
{
case 'A' : printf( "Excellentn" );
break;
case 'B' : printf( "Goodn" );
break;
case 'C' : printf( "OKn" );
break;
case 'D' : printf( "Mmmmm....n" );
break;
case 'F' : printf( "You must do better than thisn" );
break;
default : printf( "What is your grade anyway?n" );
break;
}
}
This will produce following result:
Good
LOOPS
How to use Loops in C Lanugage
 In any programming language, loops are used to
execute a set of statements repeatedly until a
particular condition is satisfied.
 Depending on the position of the control
statement in the loop, a control structure can
be classified into two types; entry controlled
and exit controlled
 Entry controlled loop: The types of loop
where the test condition is stated before the
body of the loop, are known as the entry
controlled loop
 So in the case of an entry controlled loop, the
condition is tested before the execution of the
loop.
 If the test condition is true, then the loop gets
the execution, otherwise not.
 For example, the for loop is an entry
controlled loop
Exit controlled loop :
  The types of loop where the test condition
is stated at the end of the body of the loop,
are known as the exit controlled loops.
 So, in the case of the exit controlled loops,
the body of the loop gets execution without
testing the given condition for the first
time.
 Then the condition is tested. If it comes
true, then the loop gets another execution
and continues till the result of the test
condition is not false.
 For example, the do....while loop is an
exit controlled loop
 A sequence of statements are executed until a
specified condition is true.
 This sequence of statements to be executed is
kept inside the curly braces { } known as
the Loop body.
 After every execution of loop body, condition is
verified, and if it is found to be true the loop
body is executed again.
 When the condition check returns false, the loop
body is not executed.
 There are 3 type of Loops in C
language
1. while loop
2. for loop
3. do-while loop
while loop
 while loop can be addressed as an entry
control loop. It is completed in 3 steps.
 Variable initialization. // e.g int x=0;
 condition //e.g while( x<=10)
 Variable increment or
decrement // ( x++ or x-- or x=x+2
)
Syntax :
variable initialization ;
while (condition){ statements ; variable
increment or decrement ; }
 Example : Program to print first 10 natural
numbers
#include<stdio.h>
#include<conio.h>
void main( )
{
int x; x=1;
while(x<=10)
{
printf("%dt", x);
x++;
}
getch();
}
 Output 1 2 3 4 5 6 7 8 9 10
05/28/18
for loop
 for loop is used to execute a set of
statements repeatedly until a particular
condition is satisfied. we can say it an open
ended loop. General format is,
for(initialization; condition ;
increment/decrement)
{
statement-block;
}
05/28/18
 In for loop we have exactly two
semicolons, one after initialization and
second after condition.
 In this loop we can have more than
one initialization or
increment/decrement, separated using
comma operator. 
 for loop can have only one condition.
05/28/18
Example with for loop
#include<stdio.h>
#include<conio.h>
void main( )
{
int x;
for(x=1; x<=10; x++)
{
printf("%dt",x);
}
getch();
}
Output1 2 3 4 5 6 7 8 9 10
05/28/18
Nested for loop
 We can also have nested for loops, i.e one for loop
inside another for loop. Basic syntax is,
for(initialization;condition;increment/decrement)
{
for(initialization;condition;increment/decrement)
{
statement ;
}
}
#include <stdio.h>
void main()
{
int num,factorial;
printf("Enter a
number.n");
scanf("%d",&num);
factorial=1;
while (num>0)
{
factorial=factorial*num;
--num;
} printf("Factorial=
%d",factorial);
getch();
}
C program to to find factorial of a number
using while loop
C program to check whether a number
entered by user is Armstrong or not.
#include <stdio.h>
void main()
{
int n, n1, rem,
num=0;
printf("Enter a
positive integer: ");
scanf("%d", &n);
n1=n;
while(n1!=0)
{
rem=n1%10;
num=num+rem*rem*rem;
n1=n1/10;
}
if(num==n)
printf("%d is an Armstrong
number.",n);
else
printf("%d is not an Armstrong
number.",n);
05/28/18
/* Displaying Fibonacci sequence up to nth
term where n is entered by user. */
#include <stdio.h>
void main()
{
int count, n, t1=0, t2=1, display=0;
printf("Enter number of terms: ");
scanf("%d",&n);
printf("Fibonacci Series: %d %d+", t1, t2); /*
Displaying first two terms */
count=2;
05/28/18
while (count<n)
{
display=t1+t2;
t1=t2;
t2=display;
count ++;
printf("%d+",display);
}
getch();
}
05/28/18
/* C program to display character from A to Z
using for loops. */
#include <stdio.h>
void main()
{
char c;
for(c='A'; c<='Z'; ++c)
printf("%c ",c);
getch();
}
05/28/18
/* C to find and display all the factors of a
number entered by an user.. */
#include <stdio.h>
void main()
{
int n,i;
printf("Enter a positive integer: ");
scanf("%d",&n);
printf("Factors of %d are: ", n);
for(i=1;i<=n;++i)
{
if(n%i==0)
printf("%d ",i);
}
getch();
}
05/28/18
 C Program to Generate Odd Numbers up
to a Limit n
# include <stdio.h>
void main()
{
int n, i ;
clrscr() ;
printf("Enter the limit : ") ;
scanf("%d", &n) ;
printf("nThe odd numbers are :nn") ;
for(i = 1 ; i <= n ; i = i + 2)
{
printf("%dt", i) ;
}
getch() ;
}
05/28/18
printf("nnThe even numbers are
:nn") ;
for(i = 2 ; i <= n ; i = i + 2)
{
printf("%dt", i) ;
}
05/28/18
#include <stdio.h>
void main()
{
int n, i, flag=0;
printf("Enter a
positive integer:
");
scanf("%d",&n);
C program to check whether a
number is prime or not.
for(i=2;i<=n/2;+
+i)
{
if(n%i==0)
{
flag=1;
break;
}
05/28/18
if (flag==0)
printf("%d is a prime number.",n);
else
printf("%d is not a prime
number.",n);
getch();
}
05/28/18
Arrays
In C language, arrays are reffered to as
structured data types. An array is defined
as finite ordered collection of
homogenous data, stored in contiguous
memory locations.
 finite means data range must be defined.
 ordered means data must be stored in
continuous memory addresses.
 homogenous means data must be of similar
data type.
05/28/18
Example where arrays are used,
 to store list of Employee or Student names,
 to store marks of a students,
 or to store list of numbers or characters etc.
Since arrays provide an easy way to represent
data, it is classified amongst the data
structures in C.
Other data structures in c
are structure, lists, queues and trees. Array
can be used to represent not only simple list of
data but also table of data in two or three
dimensions.
05/28/18
Declaring an Array
Like any other variable, arrays must be
declared before they are used. General form
of array declaration is,
data-type variable-name[size];
for example :
int arr[10];
05/28/18
Here int is the data type, arr is the name
of the array and 10 is the size of array.
It means array arr can only contain 10
elements of int type. 
Index of an array starts from 0 to size-9
i.e first element of arr array will be
stored at arr[0] address and last element
will occupy arr[9].
05/28/18
Initialization of an Array
After an array is declared it must be
initialized. Otherwise, it will
contain garbage value(any random value).
An array can be initialized at
either compile time or at runtime.
Initialization of one-dimensional array:
Arrays can be initialized at declaration time in this
source code as:
int age[5]={2,4,34,3,4};
It is not necessary to define the size of arrays during
initialization.
int age[]={2,4,34,3,4};
In this case, the compiler determines the size of array
by calculating the number of elements of an array.
Accessing array elements
In C programming, arrays can be accessed and treated
like variables in C.
For example:
 scanf("%d",&age[2]);
/* statement to insert value in the third element of
array age[]. */
for(i=0;i<n;i++)
scanf("%d",&age[i]);
/* Statement to insert value in (i+1)th element of array
age[]. Because, the first element of array is age[0],
second is age[1], ith is age[i-1] and (i+1)th is age[i].
*/
 printf("%d",age[0]);
/* statement to print first element of an
array. */
for(i=0;i<n;i++)
printf("%d",age[i]);
/* statement to print (i+1)th element of
an array. */
 Sample program for compile time initialization
#include <stdio.h>
void main()
{
int age[5]={2,4,34,3,4};
printf(“The array elements are:n”);
for(i=0;i<5;i++)
{
printf("%dn",age[i]);
}
getch();
}
#include <stdio.h>
void main()
{
int marks[10],i,n;
printf("Enter number of
students: ");
scanf("%d",&n);
printf("Enter the marks:”);
for(i=0;i<n;i++)
{
scanf("%d",&marks[i]);
}
printf(“n RESULTn");
for(i=0;i<n;i++)
{
printf("%dn",marks[i]);
}
getch();
}
/* C program to read marks of n students and print
using arrays */
#include <stdio.h>
void main()
{
int marks[10],i,n,sum=0;
printf("Enter number of
students: ");
scanf("%d",&n);
for(i=0;i<n;++i)
{
printf("Enter marks of
student %d: ",i+1);
scanf("%d",&marks[i]);
sum=sum+marks[i];
}
printf("Sum= %d",sum);
getch();
}
/* C program to find the sum marks of n students
using arrays */
write a program to search for
an element in a given array.
If the array was found then
display its position otherwise
display appropriate message in
c language
#include <stdio.h>
void main()
{
int array[100], search, c, n;
printf("Enter the number of elements in arrayn");
scanf("%d",&n);
printf("Enter %d integer(s)n", n);
for (c = 0; c < n; c++)
scanf("%d", &array[c]);
printf("Enter the number to searchn");
scanf("%d", &search);
for (c = 0; c < n; c++)
{
if (array[c] == search) /* if required element
found */
{
printf("%d is present at location %d.n“
, search, c+1);
break;
}
}
if (c == n)
printf("%d is not present in array.n", search);
getch();
Program : Find Largest Element in Array in C
Programming
 #include<stdio.h>
 void main()
{
   int a[30], i, num, largest;
   printf("nEnter no of elements :");
   scanf("%d", &num);
     //Read n elements in an array
   for (i = 0; i < num; i++)
     {
  scanf("%d", &a[i]);
  }
  //Consider first element as largest
   largest = a[0];
    for (i = 0; i < num; i++)
{
      if (a[i] > largest)
{
         largest = a[i];
      }
   }
    // Print out the Result
   printf("nLargest Element : %d", largest);
    getch();
}
05/28/18
 Write a c program to sort an array of
numbers in ascending order
#include<stdio.h>
void main()
{
int i,j,n,temp,a[20];
printf("Enter total elements: ");
scanf("%d",&n);
printf("Enter %d elements: ",n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
05/28/18
for(i=1;i<n;i++)
{
temp=a[i];
j=i-1;
while((temp<a[j])&&(j>=0))
{
a[j+1]=a[j];
j=j-1;
}
a[j+1]=temp;
}
05/28/18
printf("After sorting:n ");
for(i=0;i<n;i++)
printf(" %dn",a[i]);
getch();
}
Multidimensional Arrays
 C programming language allows programmer
to create arrays of arrays known as
multidimensional arrays. For example:
 float a[2][6];
05/28/18
Write a C program to read and print matrix of order
2*2 using multidimensional arrays where, elements of
matrix are entered by user.
#include <stdio.h>int
main()
{  
int a[2][2],i,j;  
printf("Enter the
elements of matrixn");
for(i=0;i<2;++i)  
for(j=0;j<2;++j)  
scanf("%d",&a[i][j]);
printf(“nresult”);
for(i=0;i<2;++i)
for(j=0;j<2;++j)
printf("%d",a[i][j])
getch();
}
05/28/18
c program add two matrices
 compute the sum of two matrices
and then print it. Firstly user will
be asked to enter the order of
matrix (number of rows and
columns) and then two matrices
05/28/18
 if the user entered order as 2, 2 i.e. two
rows and two columns and matrices as
First Matrix :-
1 2
3 4
Second matrix :-
4 5
-1 5
then output of the program (sum of First
and Second matrix) will be
5 7
2 9
05/28/18
STRING
Strings are actually one-dimensional array
of characters terminated by a null
character '0'.
The following declaration and initialization
create a string consisting of the word
"Hello".
To hold the null character at the end of the
array, the size of the character array
containing the string is one more than the
number of characters in the word "Hello.“
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '0'};
you can also write the above statement as
follows −
char greeting[] = "Hello";
Actually, you do not place
the null character at the end of a
string constant.
The C compiler automatically places
the '0' at the end of the string when it
initializes the array.
Write a C program to illustrate how to
read string from terminal.
#include <stdio.h>
void main(){
char name[20];
printf("Enter name: ");
scanf("%s",name);
printf("Your name is %s.",name);
getch();
}
S.
N.
Function & Purpose
1 strcpy(s1, s2);
Copies string s2 into string s1.
2 strcat(s1, s2);
Concatenates string s2 onto the end of string
s1.
3 strlen(s1);
Returns the length of string s1.
C supports a wide range of function
that manipulate null-terminated string
−
4 strcmp(s1, s2);
Returns 0 if s1 and s2 are the
same; less than 0 if s1<s2; greater
than 0 if s1>s2.
5 strchr(s1, ch);
Returns a pointer to the first
occurrence of character ch in string
s1.
6 strstr(s1, s2);
Returns a pointer to the first
occurrence of string s2 in string s1.
#include <stdio.h>
#include <string.h>
void main ()
{
char str1[12] = "Hello"; char str2[12] = "World";
char str3[12];
int len ;
strcpy(str3, str1); /* copy str1 into str3 */
printf(“AfterCopying : %sn", str3 );
strcat( str1, str2); /* concatenates str1 and str2
*/
printf(“After Concatination: %sn", str1 );
/* total lenghth of str1 after concatenation */
len = strlen(str1);
printf(“Length of First String: %dn", len );
getch();
Function
A function is a group of statements that
together perform a task. Every C program
has at least one function, which is main(),
and all the most trivial programs can
define additional functions.
 You can divide up your code into separate
functions. How you divide up your code
among different functions is up to you,
but logically the division is such that each
function performs a specific task.
 A function declaration tells the compiler about a
function's name, return type, and parameters. A
function definition provides the actual body of
the function.
 The C standard library provides numerous built-
in functions that your program can call. For
example, strcat() to concatenate two
strings, memcpy() to copy one memory location
to another location, and many more functions.
 A function can also be referred as a method or a
sub-routine or a procedure, etc.
 C functions can be classified into two categories,
 Library functions are those functions which are
defined by C library,
example printf(), scanf(), strcat() etc. You just need
to include appropriate header files to use these
functions. These are already declared and defined in
C libraries.
 User-defined functions are those functions which
are defined by the user at the time of writing
program. Functions are made for code reusability and
for saving time and space.
Benefits of Using Functions
 It provides modularity to the program.
 Easy code Reuseability. You just have to call
the function by its name to use it.
 In case of large programs with thousands of
code lines, debugging and editing becomes
easier if you use functions.
Function Declarations
A function declaration tells the compiler about a function
name and how to call the function. The actual body of
the function can be defined separately.
A function declaration has the following parts −
return_type function_name( parameter list );
For the above defined function max(), the function
declaration is as follows −
int max(int num1, int num2);
Parameter names are not important in function
declaration only their type is required, so the
following is also a valid declaration −
int max(int, int);
Function declaration is required when you define a
function in one source file and you call that
function in another file. In such case, you should
declare the function at the top of the file calling
the function.
Defining a Function
The general form of a function definition in
C programming language is as follows −
return_type function_name( parameter
list )
{
body of the function
}
 A function definition in C programming
consists of a function header and
afunction body.
Here are all the parts of a function −
Return Type − A function may return a value.
The return_type is the data type of the value the
function returns. Some functions perform the
desired operations without returning a value. In this
case, the return_type is the keyword void.
Function Name − This is the actual name of the
function. The function name and the parameter list
together constitute the function signature.
Parameters − A parameter is like a placeholder. When
a function is invoked, you pass a value to the
parameter. This value is referred to as actual
parameter or argument. The parameter list refers
to the type, order, and number of the parameters
of a function. Parameters are optional; that is, a
function may contain no parameters.
Function Body − The function body contains a
collection of statements that define what the
function does.
Example
Given below is the source code for a function
called max(). This function takes two parameters
num1 and num2 and returns the maximum value
between the two −
/* function returning the max between two numbers
*/
int max(int num1, int num2)
{
/* local variable declaration */
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result; }
Calling a Function
 While creating a C function, you give a
definition of what the function has to do. To use
a function, you will have to call that function to
perform the defined task.
 When a program calls a function, the program
control is transferred to the called function. A
called function performs a defined task and
when its return statement is executed or when
its function-ending closing brace is reached, it
returns the program control back to the main
program.
 To call a function, you simply need to pass the
required parameters along with the function
name, and if the function returns a value, then
you can store the returned value.
Function Arguments
 If a function is to use arguments, it must declare
variables that accept the values of the arguments.
These variables are called the formal parameters of
the function.
 Formal parameters behave like other local variables
inside the function and are created upon entry into
the function and destroyed upon exit.
While calling a function, there are two ways in which
arguments can be passed to a function −
Call Type & Description
1 Call By Value
This method copies the actual value of an argument
into the formal parameter of the function. In this
case, changes made to the parameter inside the
function have no effect on the argument.
 2 Call By Reference
 This method copies the address of an argument into
the formal parameter. Inside the function, the
address is used to access the actual argument used in
the call. This means that changes made to the
parameter affect the argument.
 By default, C uses call by value to pass arguments. In
general, it means the code within a function cannot
alter the arguments used to call the function.
Example : Function that return some value
 #include<stdio.h>
int larger(int a,int b); // function declaration
 void main()
{
int i,j,k;
clrscr();
i=99;
j=112;
k=larger(i,j); // function call printf("%d",k); getch();
} 
int larger(int a,int b) // function declaration
{
if(a>b)
return a;
else return b;
}
#include <stdio.h>
/* function declaration
*/
int max(int num1, int
num2);
void main ()
{
/* local variable
definition */
int a = 100;
int b = 200;
int ret;
/* calling a function to
get max value */
ret = max(a, b);
printf( "Max value is :
%dn", ret );
getch();
/* function returning the max
between two numbers */
int max(int num1, int num2)
{
/* local variable
declaration*/
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
 Factorial program in c using
function
#include <stdio.h>
  long factorial(int);
  void main()
{
int number;
long fact = 1;
  printf("Enter a number to calculate
it's factorialn");
scanf("%d“,&number);
 
printf("%d! = %ldn",
number,
factorial(number));
getch();
}
 
long factorial(int n)
{
int c;
long result = 1;
 for (c = 1; c <= n; c++)
result = result * c;
return result;
}
#include<stdio.h>
void swap(int,int);
void main()
{
int a,b;
clrscr();
printf("enter value for a&b:
");
scanf("%d%d",&a,&b);
swap(a,b);
getch();
}
void swap(int a,int b)
{
int temp;
temp=a;
a=b;
b=temp;
printf("after swapping
the value for a & b
is : %d %d“,a,b);
}
Program to Swap two numbers Using Functions

Mais conteúdo relacionado

Mais procurados

Basics of c++ Programming Language
Basics of c++ Programming LanguageBasics of c++ Programming Language
Basics of c++ Programming LanguageAhmad Idrees
 
Programming in C Presentation upto FILE
Programming in C Presentation upto FILEProgramming in C Presentation upto FILE
Programming in C Presentation upto FILEDipta Saha
 
Basics of C programming
Basics of C programmingBasics of C programming
Basics of C programmingavikdhupar
 
Introduction to Basic C programming 01
Introduction to Basic C programming 01Introduction to Basic C programming 01
Introduction to Basic C programming 01Wingston
 
Introduction to C Programming
Introduction to C ProgrammingIntroduction to C Programming
Introduction to C ProgrammingAniket Patne
 
Presentation on C++ Programming Language
Presentation on C++ Programming LanguagePresentation on C++ Programming Language
Presentation on C++ Programming Languagesatvirsandhu9
 
Variables in C Programming
Variables in C ProgrammingVariables in C Programming
Variables in C Programmingprogramming9
 
Presentation on Function in C Programming
Presentation on Function in C ProgrammingPresentation on Function in C Programming
Presentation on Function in C ProgrammingShuvongkor Barman
 
Decision making and branching in c programming
Decision making and branching in c programmingDecision making and branching in c programming
Decision making and branching in c programmingPriyansh Thakar
 
Command line arguments
Command line argumentsCommand line arguments
Command line argumentsAshok Raj
 
Operators in c programming
Operators in c programmingOperators in c programming
Operators in c programmingsavitamhaske
 
Loops and conditional statements
Loops and conditional statementsLoops and conditional statements
Loops and conditional statementsSaad Sheikh
 
Dynamic memory allocation in c
Dynamic memory allocation in cDynamic memory allocation in c
Dynamic memory allocation in clavanya marichamy
 

Mais procurados (20)

Introduction to c programming
Introduction to c programmingIntroduction to c programming
Introduction to c programming
 
Basics of c++ Programming Language
Basics of c++ Programming LanguageBasics of c++ Programming Language
Basics of c++ Programming Language
 
Programming in C Presentation upto FILE
Programming in C Presentation upto FILEProgramming in C Presentation upto FILE
Programming in C Presentation upto FILE
 
Basics of C programming
Basics of C programmingBasics of C programming
Basics of C programming
 
Introduction to Basic C programming 01
Introduction to Basic C programming 01Introduction to Basic C programming 01
Introduction to Basic C programming 01
 
Introduction to C Programming
Introduction to C ProgrammingIntroduction to C Programming
Introduction to C Programming
 
Presentation on C++ Programming Language
Presentation on C++ Programming LanguagePresentation on C++ Programming Language
Presentation on C++ Programming Language
 
C language unit-1
C language unit-1C language unit-1
C language unit-1
 
Variables in C Programming
Variables in C ProgrammingVariables in C Programming
Variables in C Programming
 
C basics
C   basicsC   basics
C basics
 
Presentation on Function in C Programming
Presentation on Function in C ProgrammingPresentation on Function in C Programming
Presentation on Function in C Programming
 
Introduction to c++ ppt
Introduction to c++ pptIntroduction to c++ ppt
Introduction to c++ ppt
 
Function in C program
Function in C programFunction in C program
Function in C program
 
Decision making and branching in c programming
Decision making and branching in c programmingDecision making and branching in c programming
Decision making and branching in c programming
 
Command line arguments
Command line argumentsCommand line arguments
Command line arguments
 
History of c
History of cHistory of c
History of c
 
Operators in c programming
Operators in c programmingOperators in c programming
Operators in c programming
 
Loops and conditional statements
Loops and conditional statementsLoops and conditional statements
Loops and conditional statements
 
Dynamic memory allocation in c
Dynamic memory allocation in cDynamic memory allocation in c
Dynamic memory allocation in c
 
Introduction to c++ ppt 1
Introduction to c++ ppt 1Introduction to c++ ppt 1
Introduction to c++ ppt 1
 

Semelhante a C program

Fundamentals of c language
Fundamentals of c languageFundamentals of c language
Fundamentals of c languageAkshhayPatel
 
Programming presentation
Programming presentationProgramming presentation
Programming presentationFiaz Khokhar
 
C_Programming_Language_tutorial__Autosaved_.pptx
C_Programming_Language_tutorial__Autosaved_.pptxC_Programming_Language_tutorial__Autosaved_.pptx
C_Programming_Language_tutorial__Autosaved_.pptxLikhil181
 
component of c language.pptx
component of c language.pptxcomponent of c language.pptx
component of c language.pptxAnisZahirahAzman
 
C programming session 02
C programming session 02C programming session 02
C programming session 02Dushmanta Nath
 
c_programming.pdf
c_programming.pdfc_programming.pdf
c_programming.pdfHome
 
Ap Power Point Chpt2
Ap Power Point Chpt2Ap Power Point Chpt2
Ap Power Point Chpt2dplunkett
 
B.sc CSIT 2nd semester C++ Unit2
B.sc CSIT  2nd semester C++ Unit2B.sc CSIT  2nd semester C++ Unit2
B.sc CSIT 2nd semester C++ Unit2Tekendra Nath Yogi
 
2 EPT 162 Lecture 2
2 EPT 162 Lecture 22 EPT 162 Lecture 2
2 EPT 162 Lecture 2Don Dooley
 
C programming language
C programming languageC programming language
C programming languageAbin Rimal
 
M.Florence Dayana / Basics of C Language
M.Florence Dayana / Basics of C LanguageM.Florence Dayana / Basics of C Language
M.Florence Dayana / Basics of C LanguageDr.Florence Dayana
 

Semelhante a C program (20)

Fundamentals of c language
Fundamentals of c languageFundamentals of c language
Fundamentals of c language
 
#Code2 create c++ for beginners
#Code2 create  c++ for beginners #Code2 create  c++ for beginners
#Code2 create c++ for beginners
 
C basics
C basicsC basics
C basics
 
C basics
C basicsC basics
C basics
 
Programming presentation
Programming presentationProgramming presentation
Programming presentation
 
C_Programming_Language_tutorial__Autosaved_.pptx
C_Programming_Language_tutorial__Autosaved_.pptxC_Programming_Language_tutorial__Autosaved_.pptx
C_Programming_Language_tutorial__Autosaved_.pptx
 
component of c language.pptx
component of c language.pptxcomponent of c language.pptx
component of c language.pptx
 
C material
C materialC material
C material
 
C programming session 02
C programming session 02C programming session 02
C programming session 02
 
C programming
C programming C programming
C programming
 
C-PPT.pdf
C-PPT.pdfC-PPT.pdf
C-PPT.pdf
 
C Programming Unit-1
C Programming Unit-1C Programming Unit-1
C Programming Unit-1
 
c_programming.pdf
c_programming.pdfc_programming.pdf
c_programming.pdf
 
Ap Power Point Chpt2
Ap Power Point Chpt2Ap Power Point Chpt2
Ap Power Point Chpt2
 
C++ lecture 01
C++   lecture 01C++   lecture 01
C++ lecture 01
 
B.sc CSIT 2nd semester C++ Unit2
B.sc CSIT  2nd semester C++ Unit2B.sc CSIT  2nd semester C++ Unit2
B.sc CSIT 2nd semester C++ Unit2
 
Unit 1
Unit 1Unit 1
Unit 1
 
2 EPT 162 Lecture 2
2 EPT 162 Lecture 22 EPT 162 Lecture 2
2 EPT 162 Lecture 2
 
C programming language
C programming languageC programming language
C programming language
 
M.Florence Dayana / Basics of C Language
M.Florence Dayana / Basics of C LanguageM.Florence Dayana / Basics of C Language
M.Florence Dayana / Basics of C Language
 

Mais de AJAL A J

KEAM KERALA ENTRANCE EXAM
KEAM KERALA ENTRANCE EXAMKEAM KERALA ENTRANCE EXAM
KEAM KERALA ENTRANCE EXAMAJAL A J
 
Paleontology Career
Paleontology  CareerPaleontology  Career
Paleontology CareerAJAL A J
 
CHEMISTRY basic concepts of chemistry
CHEMISTRY  basic concepts of chemistryCHEMISTRY  basic concepts of chemistry
CHEMISTRY basic concepts of chemistryAJAL A J
 
Biogeochemical cycles
Biogeochemical cyclesBiogeochemical cycles
Biogeochemical cyclesAJAL A J
 
ac dc bridges
ac dc bridgesac dc bridges
ac dc bridgesAJAL A J
 
Hays bridge schering bridge wien bridge
Hays bridge  schering bridge  wien bridgeHays bridge  schering bridge  wien bridge
Hays bridge schering bridge wien bridgeAJAL A J
 
App Naming Tip
App Naming TipApp Naming Tip
App Naming Tip AJAL A J
 
flora and fauna of himachal pradesh and kerala
flora and fauna of himachal pradesh and keralaflora and fauna of himachal pradesh and kerala
flora and fauna of himachal pradesh and keralaAJAL A J
 
B.Sc Cardiovascular Technology(CVT)
 B.Sc Cardiovascular Technology(CVT)  B.Sc Cardiovascular Technology(CVT)
B.Sc Cardiovascular Technology(CVT) AJAL A J
 
11 business strategies to make profit
11 business strategies to make profit 11 business strategies to make profit
11 business strategies to make profit AJAL A J
 
PCOS Polycystic Ovary Syndrome
PCOS  Polycystic Ovary SyndromePCOS  Polycystic Ovary Syndrome
PCOS Polycystic Ovary SyndromeAJAL A J
 
Courses and Career Options after Class 12 in Humanities
Courses and Career Options after Class 12 in HumanitiesCourses and Career Options after Class 12 in Humanities
Courses and Career Options after Class 12 in HumanitiesAJAL A J
 
MANAGEMENT Stories
 MANAGEMENT Stories MANAGEMENT Stories
MANAGEMENT StoriesAJAL A J
 
NEET PREPRATION TIPS AND STRATEGY
NEET PREPRATION TIPS AND STRATEGYNEET PREPRATION TIPS AND STRATEGY
NEET PREPRATION TIPS AND STRATEGYAJAL A J
 
REVOLUTIONS IN AGRICULTURE
REVOLUTIONS IN AGRICULTUREREVOLUTIONS IN AGRICULTURE
REVOLUTIONS IN AGRICULTUREAJAL A J
 
NRI QUOTA IN NIT'S
NRI QUOTA IN NIT'S NRI QUOTA IN NIT'S
NRI QUOTA IN NIT'S AJAL A J
 
Subjects to study if you want to work for a charity
Subjects to study if you want to work for a charitySubjects to study if you want to work for a charity
Subjects to study if you want to work for a charityAJAL A J
 
IIT JEE A KERALA PERSPECTIVE
IIT JEE A KERALA PERSPECTIVE IIT JEE A KERALA PERSPECTIVE
IIT JEE A KERALA PERSPECTIVE AJAL A J
 
Clat 2020 exam COMPLETE DETAILS
Clat 2020 exam COMPLETE DETAILSClat 2020 exam COMPLETE DETAILS
Clat 2020 exam COMPLETE DETAILSAJAL A J
 

Mais de AJAL A J (20)

KEAM KERALA ENTRANCE EXAM
KEAM KERALA ENTRANCE EXAMKEAM KERALA ENTRANCE EXAM
KEAM KERALA ENTRANCE EXAM
 
Paleontology Career
Paleontology  CareerPaleontology  Career
Paleontology Career
 
CHEMISTRY basic concepts of chemistry
CHEMISTRY  basic concepts of chemistryCHEMISTRY  basic concepts of chemistry
CHEMISTRY basic concepts of chemistry
 
Ecology
EcologyEcology
Ecology
 
Biogeochemical cycles
Biogeochemical cyclesBiogeochemical cycles
Biogeochemical cycles
 
ac dc bridges
ac dc bridgesac dc bridges
ac dc bridges
 
Hays bridge schering bridge wien bridge
Hays bridge  schering bridge  wien bridgeHays bridge  schering bridge  wien bridge
Hays bridge schering bridge wien bridge
 
App Naming Tip
App Naming TipApp Naming Tip
App Naming Tip
 
flora and fauna of himachal pradesh and kerala
flora and fauna of himachal pradesh and keralaflora and fauna of himachal pradesh and kerala
flora and fauna of himachal pradesh and kerala
 
B.Sc Cardiovascular Technology(CVT)
 B.Sc Cardiovascular Technology(CVT)  B.Sc Cardiovascular Technology(CVT)
B.Sc Cardiovascular Technology(CVT)
 
11 business strategies to make profit
11 business strategies to make profit 11 business strategies to make profit
11 business strategies to make profit
 
PCOS Polycystic Ovary Syndrome
PCOS  Polycystic Ovary SyndromePCOS  Polycystic Ovary Syndrome
PCOS Polycystic Ovary Syndrome
 
Courses and Career Options after Class 12 in Humanities
Courses and Career Options after Class 12 in HumanitiesCourses and Career Options after Class 12 in Humanities
Courses and Career Options after Class 12 in Humanities
 
MANAGEMENT Stories
 MANAGEMENT Stories MANAGEMENT Stories
MANAGEMENT Stories
 
NEET PREPRATION TIPS AND STRATEGY
NEET PREPRATION TIPS AND STRATEGYNEET PREPRATION TIPS AND STRATEGY
NEET PREPRATION TIPS AND STRATEGY
 
REVOLUTIONS IN AGRICULTURE
REVOLUTIONS IN AGRICULTUREREVOLUTIONS IN AGRICULTURE
REVOLUTIONS IN AGRICULTURE
 
NRI QUOTA IN NIT'S
NRI QUOTA IN NIT'S NRI QUOTA IN NIT'S
NRI QUOTA IN NIT'S
 
Subjects to study if you want to work for a charity
Subjects to study if you want to work for a charitySubjects to study if you want to work for a charity
Subjects to study if you want to work for a charity
 
IIT JEE A KERALA PERSPECTIVE
IIT JEE A KERALA PERSPECTIVE IIT JEE A KERALA PERSPECTIVE
IIT JEE A KERALA PERSPECTIVE
 
Clat 2020 exam COMPLETE DETAILS
Clat 2020 exam COMPLETE DETAILSClat 2020 exam COMPLETE DETAILS
Clat 2020 exam COMPLETE DETAILS
 

Último

A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...PsychoTech Services
 
General AI for Medical Educators April 2024
General AI for Medical Educators April 2024General AI for Medical Educators April 2024
General AI for Medical Educators April 2024Janet Corral
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhikauryashika82
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingTeacherCyreneCayanan
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajanpragatimahajan3
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfAyushMahapatra5
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDThiyagu K
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 

Último (20)

A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
 
General AI for Medical Educators April 2024
General AI for Medical Educators April 2024General AI for Medical Educators April 2024
General AI for Medical Educators April 2024
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writing
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajan
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 

C program

  • 2.  Assembler is a translator software that translates assembly language program into equivalent binary language  Compiler converts the high level source program into machine readable form at once.compiler will check all statements for syntax error and after correcting errors ,it will convert source program to object code  Interpreter translates the source program statements one after another. Only after the successful completion of first instruction it will take next instruction.
  • 3. Source and object code  Programs written in high level languages are known as source program.  The source program which are translated into machine language is known as object program.  There are mainly 3 translator programs used to convert source program to object program 1. Assembler 2. Compiler 3. interpreter
  • 4. Algorithm  An algorithm is the steps to solve a problem  Written in simple English  Every instruction should be precise  First Understand the problem, i. e try to find out objective , available data and which process is suitable to get correct output
  • 5. Sample, Find total marks by adding internal and external marks Step 1: Start Step 2: Read/Input internal mark and external mark Step 3: Add internal with external to get total Step 4: Display total marks Step 5: Stop
  • 6. flowchart Flowchart is a pictorial representation of an algorithm Symbols Terminal (oval ) Indicate beginning (START) and ending (STOP) Input/Output( parallelogram ) Denote input and Output related functions START Display total
  • 7. Processing(Rectangle) Represents Arithmetic and logical operations e.g. Decision( Diamond ) Indicates a point which a decision has to be made E.g. Checks that value of a is t greater than value of b, if it is true , continued to f next task ,else it will go to false side total=a+b Is a>b
  • 8. Flow lines indicates flow of operation Connector If the chart becomes too long to fit in a single page , we can use connectors
  • 9.  Flowchart for finding total of internal and external marks START STOP Read Internal ,external Display total Total=internal+ external
  • 10. Step 1: Start Step 2: read length(l) and breadth(b) Step 3: A=l x b Step 4: Display Area,A Step 5: Stop START STOP Read l,b Display Area,A A=l x b
  • 11. Step 1: Start Step 2: read num1,num2 Step 3: check num1>num2 if true then Display num1 is largest Else Display num2 is largest Step 5: Stop START STOP Read num1,num2 Display num1 is largest Is num 1> num 2 Display num2 is largest true false
  • 12. C language  It is a high level language  Developed by Dennis Ritchie in 1970s  Used for system programming as well as application programming  Programs written in c are fast and efficient  Supports a variety of data types and powerful operations  There are 32 keywords which are easy to learn and use  It has many built in functions
  • 13. Features of C Language:- There are many features of c language are given below. 1) Simple 2) Machine Independent or Portable 3) Mid-level programming language 4) structured programming language 5) Rich Library 6) Memory Management 7) Fast Speed 8) Pointers 9) Recursion 10) Extensible
  • 14. C TOKENS:  C tokens are the basic buildings blocks in C language which are constructed together to write a C program.  Each and every smallest individual units in a C program are known as C tokens.  C tokens are of six types. They are,  Keywords               (eg: int, while),  Identifiers               (eg: main, total),  Constants              (eg: 10, 20),  Strings                    (eg: “total”, “hello”),  Special symbols  (eg: (), {}),  Operators              (eg: +, /,-,*)
  • 15. C TOKENS EXAMPLE PROGRAM:  int main() { int x, y, total; x = 10, y = 20; total = x + y; Printf (“Total = %d n”, total); }
  • 16.  where,  main – identifier  {,}, (,) – delimiter  int – keyword  x, y, total – identifier  + - Operators  main, {, }, (, ), int, x, y, total ,+ – tokens
  • 17.
  • 18. IDENTIFIERS IN C LANGUAGE:  Each program elements in a C program are given a name called identifiers.  Names given to identify Variables, functions and arrays are examples for identifiers. eg. x is a name given to integer variable in above program
  • 19. AUTO DOUB LE INT STRU CT CONS T FLOA T  SHOR T UNSIG NED BREA K ELSE LONG SWITCHCONTINUE FOR SIGNED VOID  CASE ENUM REGISTERTYPEDEFDEFAULTGOTO SIZEOF   VOLATI   CHAR EXTERNRETURNUNION DO   IF STATIC   WHILE AUTO DOUBLE INT STRUCTCONST FLOAT   SHORT UNSIGN BREAK ELSE LONG SWITC H CONTI NUE  FOR SIGNE D VOID  CASE ENUM REGIS TER TYPE DEF DEFA ULT GOTO SIZEO F  VOLA TILE  CHAR EXTE RN RETU RN UNION DO   IF STATI C  WHILE
  • 20. KEYWORDS IN C LANGUAGE:  Keywords are pre-defined words in a C compiler.  Each keyword is meant to perform a specific function in a C program.  Since keywords are referred names for compiler, they can’t be used as variable name.  C language supports 32 keywords which are given below
  • 21. C - VariablesC - Variables  A variable is nothing but a name given to a storage area that our programs can manipulate.  The name of a variable can be composed of letters, digits, and the underscore character.  It must begin with either a letter or an underscore.”first_name”  Upper and lowercase letters are distinct because C is case-sensitive. 
  • 22. C - Data Types  The type of a variable determines how much space it occupies in storage and how the bit pattern stored is interpreted.  Basic data types ------ char,int, float, double  Derived data type ----- pointer, array, structure, union  Void data type ----- void
  • 23. Integer data type  Integer data type allows a variable to store numeric values.  “int” keyword is used to refer integer data type.  The storage size of int data type is 2 byte or 4 or 8 byte.  int (2 byte) can store values from -32,768 to +32,767
  • 24. Character data type  Character data type allows a variable to store only one character.  Storage size of character data type is 1 byte. We can store only one character using character data type.  “char” keyword is used to refer character data type.  For example, ‘A’ can be stored using char datatype. You can’t store more than one character using char data type.
  • 25. Floating point data type  Floating point data type consists of 2 types. They are, Float & double 1. float:  Float data type allows a variable to store decimal values.  Storage size of float data type is 4 byte. This also varies depend upon the processor in the CPU as “int” data type.  We can use up-to 6 digits after decimal using float data type.  For example, 10.456789 can be stored in a variable using float data type
  • 26. 2.double:  Double data type is also same as float data type which allows up-to 10 digits after decimal point Void data type in C:  Void is an empty data type that has no value
  • 27. operators Two types of operators are there, 1. Arithmetic operators 2. Relational Operators 3. Logical Operators 4. Assignment Operators 5. Increment and decrement operator Assume variable A holds 10 and variable B holds 20, then −
  • 28.
  • 29.
  • 30. 30 Relational Operators •Relational and comparison operators are used for comparing two operands (Data). •These operators give the result as either true or false. •Actually in C, any non-zero value is treated as true and a zero is treated as false •Relational expressions are use in decision making statements
  • 31. Relational Operators used in C are Operator Meaning < Less than > Greater than <= Less than or equal to >= Greater thanor equal to == equal to != not equal to
  • 32. NOT(!) Chooses the value from false to true or from true to false. Truth table of NOT is !True False ! False True
  • 33. The logical operators are used to test more than one condition and make Decisions LOGICAL OPERATORS  Operator Meaning ! NOT && AND || OR
  • 34. AND(&) In the case of and , the final answer is true If both the condition on the left and on the right of && operator Otherwise False Truth table of AND is True && True True True && False False False && True False False && False False
  • 35. OR Operator(||) The result of an OR operator is true if at least anyone condition in the left side or the right side of the operator is true; otherwise is false Truth table of OR is True || True True True || False True False || True True False || False False
  • 36. Assignment Operators Assignment Operator is used to assign a value or result of an Expression Usual Assignment Operator is Equal to “=“ E. g a=b; means the value of b is assigned to a.
  • 37. = C = A + B will assign the value of A + B to C += C += A is equivalent to C = C + A -= C -= A is equivalent to C = C - A *= C *= A is equivalent to C = C * A /= C /= A is equivalent to C = C / A %= C %= A is equivalent to C = C % A
  • 38. Increment  and decrement operator  C provides Two Special operators, one for incrementing (++)and the other for decrementing (--) Increment operator add one with the operand. It is a unary operator. There are two forms of increment operators, Prefix(++operand) Postfix (operand++ ) If they are used with a single variable, both are same, However if they are used in expression prefix and postfix operations give different results
  • 39. In prefix operation,first variable is incremented then the expression is evaluated. In Postfix operation, First it evaluate the expression then the value of the variable is incremented
  • 40. Syntax The rules for forming instruction Comments Comments are non executable statements . Syntax for comment, /*this is comment*/ // also represents comment //this is comment
  • 41. Structure of c program Documentation section Preprocessor directives Global variable declaration main() function section { Declaration part Statement part } Subprogram section Function1 Function2
  • 42. Preprocessor directive Used to load built in functions and define formulas Start with # symbol #define directive – used to define constants , formulas E.g. #define Pi3.14 #include directive – used to include header files Syntax : #include<filename> E. g. #include<stdio.h>
  • 43. Header files  Used with pre-processor directive  Extension is “ .h ” stdio.h Standard input output functions , data types are in this header file. String.h String functions are included in this file. Math.h Mathematical functions are defined in this header file.
  • 44.  The first line of the c program #include<stdio.h>
  • 45. The main() function  Every c program have one main() function  () – indicates a function  Main() contains two parts, declaration part execution part All statements in these area must terminate with a semicolon “ ; ”
  • 46. printf ()   The usually used output statement is printf ().  It is one of the library functions. Syntax : printf (“format string”, argument list);  Format string may be a collection of escape sequence or/and conversion specification or/and string constant. The format string directs the printf function to display the entire text enclosed within the double quotes without any change.
  • 47. SCANF FUNCTION The usually used input statement is scanf () function. Syntax of scanf function is         scanf (“format string”, argument list);
  • 48.  The format string must be a text enclosed in double quotes. It contains the information for interpreting the entire data for connecting it into internal representation in memory. Example: integer (%d) , float (%f) , character (%c) or string (%s). format string
  • 49. Type specifier  %c –single character  %d – decimal character  %f – floating point value  %s – string  %x – hexadecimal value  %l –long integers/double
  • 50.   The argument list contains a list of variables each preceded by the address list and separated by comma. The number of argument is not fixed; however corresponding to each argument there should be a format specifier argument list
  • 51. Escape sequence:                  Escape sequence is a pair of character. The first letter is a slash followed by a character. Escape sequence help us to represent within the format string invisible and non-printed character although there are physically two characters in any escape sequence. Escape sequence Meaning n New line t Tab b Back space
  • 53. #include <stdio.h> Void main() { int a = 21; int b = 10; int c ; c = a + b; printf("Line 1 - Value of c is %dn", c ); c = a - b; printf("Line 2 - Value of c is %dn", c );
  • 54. c = a * b; printf("Line 3 - Value of c is %dn", c ); c = a / b; printf("Line 4 - Value of c is %dn", c ); c = a % b; printf("Line 5 - Value of c is %dn", c ); c = a++; printf("Line 6 - Value of c is %dn", c ); c = a--; printf("Line 7 - Value of c is %dn", c ); Getch(); }
  • 55. 55  Write a c program to read a number and print it . #include <stdio.h> void main() { int a;  printf("Enter an integern"); scanf("%d",&a);   printf("Integer that you have entered is %dn", a);   getch(); }
  • 56.  Write a C program to add two floating point numbers. #include<stdio.h> Void main() { float a, b, c; printf("Enter two numbers to addn"); scanf("%f%f",&a,&b); c = a + b; printf("Sum of entered numbers = %fn",c);   getch(); }
  • 57.  n – print in new line  t – provide a tab space
  • 58. Type casting  Type casting is simply a mechanism by which we can change the data type of a variable, no matter how it was originally defined.  When a variable is type casted into a different type, the compiler basically treats the variable as of the new data type. 
  • 59. EXAMPLE #include<stdio.h> void main() { int a=5, c = 0, b=8; float d = 0; c = a/b; printf("n Answer without type casting:%f n",c); d = (float)a/(float)b; printf("n Answer with type casting: %f n",d); getch(); }
  • 60.  Write a C program to perform basic arithmetic operations which are addition, subtraction, multiplication and division of two integer numbers #include <stdio.h> void main() { int first, second, add, subtract, multiply; float divide; printf("Enter two integersn"); scanf("%d%d", &first, &second); add = first + second; subtract = first - second; multiply = first * second; divide = first / (float)second; //typecasting  
  • 61. printf("Sum = %dn",add); printf("Difference = %dn",subtract); printf("Multiplication = %dn",multiply); printf("Division = %.2fn",divide);   getch(); }
  • 62. Decision making in C  Decision making is about deciding the order of execution of statements based on certain conditions  or repeat a group of statements until certain specified conditions are met.  C language handles decision-making by supporting the following statements, 1) if statement 2) switch statement
  • 63.  Simple if statement The general form of a simple if statement is, if( expression ) { statement-inside; } statement-outside; If the expression is true, then 'statement- inside' it will be executed, otherwise 'statement-inside' is skipped and only 'statement-outside' is executed
  • 64.
  • 65. Example : #include <stdio.h> void main( ) { int x,y; x=15; y=13; if (x > y ) { printf("x is greater than y"); } getch(); }
  • 66. if...else statement  The general form of a simple if...else statement is, if( expression ) { statement-block1; } else { statement-block2; } If the 'expression' is true, the 'statement-block1' is executed, else 'statement-block1' is skipped and 'statement-block2' is executed
  • 67.
  • 68. #include <stdio.h> void main( ) { int x,y; x=15; y=18; if (x > y ) { printf("x is greater than y"); } else { printf("y is greater than x"); } }
  • 69.  In if statement, a single statement can be included without enclosing it into curly braces { } int a = 5; if(a > 4) printf("success"); No curly braces are required in the above case, but if we have more than one statement inside if condition, then we must enclose them inside curly braces.  == must be used for comparison in the expression of if condition, if you use = the expression will always return true, because it performs assignment not comparison.
  • 70.  Nested if....else statement The general form of a nested if...else statement is, if( expression ) { if( expression1 ) { statement-block1; } else { statement-block 2; } } else { statement-block 3; } 
  • 71. if 'expression' is false the 'statement- block3' will be executed, otherwise it continues to perform the test for 'expression 1' . If the 'expression 1' is true the 'statement-block1' is executed otherwise 'statement- block2' is executed
  • 72.
  • 73. Example : #include <stdio.h> #include <conio.h> void main( ) { int a,b,c; clrscr(); printf("enter 3 number"); scanf("%d%d%d",&a,&b,&c);
  • 74. if(a>b) { if( a > c) { printf("a is greatest"); } else { printf("c is greatest"); } }
  • 75. Else { if( b> c) { printf("b is greatest"); } else { printf("c is greatest"); } } getch(); }
  • 76. else-if ladder The general form of else-if ladder is, if(expression 1) { statement-block1; } else if(expression 2) { statement-block2; } else if(expression 3 ) { statement-block3; } else default-statement;
  • 77. The expression is tested from the top(of the ladder) downwards. As soon as the true condition is found, the statement associated with it is executed.
  • 78. Example : #include <stdio.h> #include <conio.h> void main( ) { int a; printf("enter a number"); scanf("%d",&a);
  • 79. if( a%5==0 && a%8==0) { printf("divisible by both 5 and 8"); } else if( a%8==0 ) { printf("divisible by 8"); } else if(a%5==0) { printf("divisible by 5"); } Else { printf("divisible by none"); } getch(); }
  • 81. 05/28/18  The general form of switch statement is, switch(expression) { case value-1: block-1; break; case value-2: block-2; break; case value-3: block-3; break; default: default-block; break; }
  • 82. 05/28/18  1. We don't use those expressions to evaluate switch case, which may return floating point values or strings.  2. It isn't necessary to use break after each block, but if you do not use it, all the consecutive block of codes will get executed after the matching block.
  • 83. 05/28/18 Example int i = 1; switch(i) { case 1: printf("A"); // No break case 2: printf("B"); // No break case 3: printf("C"); break; }
  • 84. 05/28/18  Output : A B C  The output was supposed to be only A because only the first case matches, but as there is no break statement after the block, the next blocks are executed, until the cursor encounters a break.  default case can be placed anywhere in the switch case. Even if we don't include the default case switch statement works.
  • 85.
  • 86. 05/28/18 Example of Switch Statement #include <stdio.h> void main() { int Grade = 'B'; switch( Grade ) { case 'A' : printf( "Excellentn" ); break; case 'B' : printf( "Goodn" ); break;
  • 87. case 'C' : printf( "OKn" ); break; case 'D' : printf( "Mmmmm....n" ); break; case 'F' : printf( "You must do better than thisn" ); break; default : printf( "What is your grade anyway?n" ); break; } } This will produce following result: Good
  • 88. LOOPS
  • 89. How to use Loops in C Lanugage  In any programming language, loops are used to execute a set of statements repeatedly until a particular condition is satisfied.  Depending on the position of the control statement in the loop, a control structure can be classified into two types; entry controlled and exit controlled
  • 90.  Entry controlled loop: The types of loop where the test condition is stated before the body of the loop, are known as the entry controlled loop  So in the case of an entry controlled loop, the condition is tested before the execution of the loop.  If the test condition is true, then the loop gets the execution, otherwise not.  For example, the for loop is an entry controlled loop
  • 91. Exit controlled loop :   The types of loop where the test condition is stated at the end of the body of the loop, are known as the exit controlled loops.  So, in the case of the exit controlled loops, the body of the loop gets execution without testing the given condition for the first time.  Then the condition is tested. If it comes true, then the loop gets another execution and continues till the result of the test condition is not false.  For example, the do....while loop is an exit controlled loop
  • 92.
  • 93.  A sequence of statements are executed until a specified condition is true.  This sequence of statements to be executed is kept inside the curly braces { } known as the Loop body.  After every execution of loop body, condition is verified, and if it is found to be true the loop body is executed again.  When the condition check returns false, the loop body is not executed.
  • 94.  There are 3 type of Loops in C language 1. while loop 2. for loop 3. do-while loop
  • 95. while loop  while loop can be addressed as an entry control loop. It is completed in 3 steps.  Variable initialization. // e.g int x=0;  condition //e.g while( x<=10)  Variable increment or decrement // ( x++ or x-- or x=x+2 ) Syntax : variable initialization ; while (condition){ statements ; variable increment or decrement ; }
  • 96.  Example : Program to print first 10 natural numbers #include<stdio.h> #include<conio.h> void main( ) { int x; x=1; while(x<=10) { printf("%dt", x); x++; } getch(); }
  • 97.  Output 1 2 3 4 5 6 7 8 9 10
  • 98. 05/28/18 for loop  for loop is used to execute a set of statements repeatedly until a particular condition is satisfied. we can say it an open ended loop. General format is, for(initialization; condition ; increment/decrement) { statement-block; }
  • 99. 05/28/18  In for loop we have exactly two semicolons, one after initialization and second after condition.  In this loop we can have more than one initialization or increment/decrement, separated using comma operator.   for loop can have only one condition.
  • 100. 05/28/18 Example with for loop #include<stdio.h> #include<conio.h> void main( ) { int x; for(x=1; x<=10; x++) { printf("%dt",x); } getch(); } Output1 2 3 4 5 6 7 8 9 10
  • 101. 05/28/18 Nested for loop  We can also have nested for loops, i.e one for loop inside another for loop. Basic syntax is, for(initialization;condition;increment/decrement) { for(initialization;condition;increment/decrement) { statement ; } }
  • 102. #include <stdio.h> void main() { int num,factorial; printf("Enter a number.n"); scanf("%d",&num); factorial=1; while (num>0) { factorial=factorial*num; --num; } printf("Factorial= %d",factorial); getch(); } C program to to find factorial of a number using while loop
  • 103. C program to check whether a number entered by user is Armstrong or not. #include <stdio.h> void main() { int n, n1, rem, num=0; printf("Enter a positive integer: "); scanf("%d", &n); n1=n; while(n1!=0) { rem=n1%10; num=num+rem*rem*rem; n1=n1/10; } if(num==n) printf("%d is an Armstrong number.",n); else printf("%d is not an Armstrong number.",n);
  • 104. 05/28/18 /* Displaying Fibonacci sequence up to nth term where n is entered by user. */ #include <stdio.h> void main() { int count, n, t1=0, t2=1, display=0; printf("Enter number of terms: "); scanf("%d",&n); printf("Fibonacci Series: %d %d+", t1, t2); /* Displaying first two terms */ count=2;
  • 106. 05/28/18 /* C program to display character from A to Z using for loops. */ #include <stdio.h> void main() { char c; for(c='A'; c<='Z'; ++c) printf("%c ",c); getch(); }
  • 107. 05/28/18 /* C to find and display all the factors of a number entered by an user.. */ #include <stdio.h> void main() { int n,i; printf("Enter a positive integer: "); scanf("%d",&n); printf("Factors of %d are: ", n); for(i=1;i<=n;++i) { if(n%i==0) printf("%d ",i); } getch(); }
  • 108. 05/28/18  C Program to Generate Odd Numbers up to a Limit n # include <stdio.h> void main() { int n, i ; clrscr() ; printf("Enter the limit : ") ; scanf("%d", &n) ; printf("nThe odd numbers are :nn") ; for(i = 1 ; i <= n ; i = i + 2) { printf("%dt", i) ; } getch() ; }
  • 109. 05/28/18 printf("nnThe even numbers are :nn") ; for(i = 2 ; i <= n ; i = i + 2) { printf("%dt", i) ; }
  • 110. 05/28/18 #include <stdio.h> void main() { int n, i, flag=0; printf("Enter a positive integer: "); scanf("%d",&n); C program to check whether a number is prime or not. for(i=2;i<=n/2;+ +i) { if(n%i==0) { flag=1; break; }
  • 111. 05/28/18 if (flag==0) printf("%d is a prime number.",n); else printf("%d is not a prime number.",n); getch(); }
  • 112. 05/28/18 Arrays In C language, arrays are reffered to as structured data types. An array is defined as finite ordered collection of homogenous data, stored in contiguous memory locations.  finite means data range must be defined.  ordered means data must be stored in continuous memory addresses.  homogenous means data must be of similar data type.
  • 113. 05/28/18 Example where arrays are used,  to store list of Employee or Student names,  to store marks of a students,  or to store list of numbers or characters etc. Since arrays provide an easy way to represent data, it is classified amongst the data structures in C. Other data structures in c are structure, lists, queues and trees. Array can be used to represent not only simple list of data but also table of data in two or three dimensions.
  • 114. 05/28/18 Declaring an Array Like any other variable, arrays must be declared before they are used. General form of array declaration is, data-type variable-name[size]; for example : int arr[10];
  • 115. 05/28/18 Here int is the data type, arr is the name of the array and 10 is the size of array. It means array arr can only contain 10 elements of int type.  Index of an array starts from 0 to size-9 i.e first element of arr array will be stored at arr[0] address and last element will occupy arr[9].
  • 116. 05/28/18 Initialization of an Array After an array is declared it must be initialized. Otherwise, it will contain garbage value(any random value). An array can be initialized at either compile time or at runtime.
  • 117. Initialization of one-dimensional array: Arrays can be initialized at declaration time in this source code as: int age[5]={2,4,34,3,4}; It is not necessary to define the size of arrays during initialization. int age[]={2,4,34,3,4}; In this case, the compiler determines the size of array by calculating the number of elements of an array.
  • 118. Accessing array elements In C programming, arrays can be accessed and treated like variables in C. For example:  scanf("%d",&age[2]); /* statement to insert value in the third element of array age[]. */ for(i=0;i<n;i++) scanf("%d",&age[i]); /* Statement to insert value in (i+1)th element of array age[]. Because, the first element of array is age[0], second is age[1], ith is age[i-1] and (i+1)th is age[i]. */
  • 119.  printf("%d",age[0]); /* statement to print first element of an array. */ for(i=0;i<n;i++) printf("%d",age[i]); /* statement to print (i+1)th element of an array. */
  • 120.  Sample program for compile time initialization #include <stdio.h> void main() { int age[5]={2,4,34,3,4}; printf(“The array elements are:n”); for(i=0;i<5;i++) { printf("%dn",age[i]); } getch(); }
  • 121. #include <stdio.h> void main() { int marks[10],i,n; printf("Enter number of students: "); scanf("%d",&n); printf("Enter the marks:”); for(i=0;i<n;i++) { scanf("%d",&marks[i]); } printf(“n RESULTn"); for(i=0;i<n;i++) { printf("%dn",marks[i]); } getch(); } /* C program to read marks of n students and print using arrays */
  • 122. #include <stdio.h> void main() { int marks[10],i,n,sum=0; printf("Enter number of students: "); scanf("%d",&n); for(i=0;i<n;++i) { printf("Enter marks of student %d: ",i+1); scanf("%d",&marks[i]); sum=sum+marks[i]; } printf("Sum= %d",sum); getch(); } /* C program to find the sum marks of n students using arrays */
  • 123. write a program to search for an element in a given array. If the array was found then display its position otherwise display appropriate message in c language
  • 124. #include <stdio.h> void main() { int array[100], search, c, n; printf("Enter the number of elements in arrayn"); scanf("%d",&n); printf("Enter %d integer(s)n", n); for (c = 0; c < n; c++) scanf("%d", &array[c]); printf("Enter the number to searchn"); scanf("%d", &search);
  • 125. for (c = 0; c < n; c++) { if (array[c] == search) /* if required element found */ { printf("%d is present at location %d.n“ , search, c+1); break; } } if (c == n) printf("%d is not present in array.n", search); getch();
  • 126. Program : Find Largest Element in Array in C Programming  #include<stdio.h>  void main() {    int a[30], i, num, largest;    printf("nEnter no of elements :");    scanf("%d", &num);      //Read n elements in an array    for (i = 0; i < num; i++)      {   scanf("%d", &a[i]);   }
  • 127.   //Consider first element as largest    largest = a[0];     for (i = 0; i < num; i++) {       if (a[i] > largest) {          largest = a[i];       }    }     // Print out the Result    printf("nLargest Element : %d", largest);     getch(); }
  • 128. 05/28/18  Write a c program to sort an array of numbers in ascending order #include<stdio.h> void main() { int i,j,n,temp,a[20]; printf("Enter total elements: "); scanf("%d",&n); printf("Enter %d elements: ",n); for(i=0;i<n;i++) scanf("%d",&a[i]);
  • 131. Multidimensional Arrays  C programming language allows programmer to create arrays of arrays known as multidimensional arrays. For example:  float a[2][6]; 05/28/18
  • 132. Write a C program to read and print matrix of order 2*2 using multidimensional arrays where, elements of matrix are entered by user. #include <stdio.h>int main() {   int a[2][2],i,j;   printf("Enter the elements of matrixn"); for(i=0;i<2;++i)   for(j=0;j<2;++j)   scanf("%d",&a[i][j]); printf(“nresult”); for(i=0;i<2;++i) for(j=0;j<2;++j) printf("%d",a[i][j]) getch(); } 05/28/18
  • 133. c program add two matrices  compute the sum of two matrices and then print it. Firstly user will be asked to enter the order of matrix (number of rows and columns) and then two matrices 05/28/18
  • 134.  if the user entered order as 2, 2 i.e. two rows and two columns and matrices as First Matrix :- 1 2 3 4 Second matrix :- 4 5 -1 5 then output of the program (sum of First and Second matrix) will be 5 7 2 9 05/28/18
  • 135. STRING Strings are actually one-dimensional array of characters terminated by a null character '0'. The following declaration and initialization create a string consisting of the word "Hello". To hold the null character at the end of the array, the size of the character array containing the string is one more than the number of characters in the word "Hello.“ char greeting[6] = {'H', 'e', 'l', 'l', 'o', '0'};
  • 136. you can also write the above statement as follows − char greeting[] = "Hello";
  • 137. Actually, you do not place the null character at the end of a string constant. The C compiler automatically places the '0' at the end of the string when it initializes the array.
  • 138. Write a C program to illustrate how to read string from terminal. #include <stdio.h> void main(){ char name[20]; printf("Enter name: "); scanf("%s",name); printf("Your name is %s.",name); getch(); }
  • 139. S. N. Function & Purpose 1 strcpy(s1, s2); Copies string s2 into string s1. 2 strcat(s1, s2); Concatenates string s2 onto the end of string s1. 3 strlen(s1); Returns the length of string s1. C supports a wide range of function that manipulate null-terminated string −
  • 140. 4 strcmp(s1, s2); Returns 0 if s1 and s2 are the same; less than 0 if s1<s2; greater than 0 if s1>s2. 5 strchr(s1, ch); Returns a pointer to the first occurrence of character ch in string s1. 6 strstr(s1, s2); Returns a pointer to the first occurrence of string s2 in string s1.
  • 141. #include <stdio.h> #include <string.h> void main () { char str1[12] = "Hello"; char str2[12] = "World"; char str3[12]; int len ; strcpy(str3, str1); /* copy str1 into str3 */ printf(“AfterCopying : %sn", str3 ); strcat( str1, str2); /* concatenates str1 and str2 */ printf(“After Concatination: %sn", str1 ); /* total lenghth of str1 after concatenation */ len = strlen(str1); printf(“Length of First String: %dn", len ); getch();
  • 142. Function A function is a group of statements that together perform a task. Every C program has at least one function, which is main(), and all the most trivial programs can define additional functions.  You can divide up your code into separate functions. How you divide up your code among different functions is up to you, but logically the division is such that each function performs a specific task.
  • 143.  A function declaration tells the compiler about a function's name, return type, and parameters. A function definition provides the actual body of the function.  The C standard library provides numerous built- in functions that your program can call. For example, strcat() to concatenate two strings, memcpy() to copy one memory location to another location, and many more functions.  A function can also be referred as a method or a sub-routine or a procedure, etc.
  • 144.  C functions can be classified into two categories,  Library functions are those functions which are defined by C library, example printf(), scanf(), strcat() etc. You just need to include appropriate header files to use these functions. These are already declared and defined in C libraries.  User-defined functions are those functions which are defined by the user at the time of writing program. Functions are made for code reusability and for saving time and space.
  • 145.
  • 146. Benefits of Using Functions  It provides modularity to the program.  Easy code Reuseability. You just have to call the function by its name to use it.  In case of large programs with thousands of code lines, debugging and editing becomes easier if you use functions.
  • 147. Function Declarations A function declaration tells the compiler about a function name and how to call the function. The actual body of the function can be defined separately. A function declaration has the following parts − return_type function_name( parameter list ); For the above defined function max(), the function declaration is as follows − int max(int num1, int num2);
  • 148. Parameter names are not important in function declaration only their type is required, so the following is also a valid declaration − int max(int, int); Function declaration is required when you define a function in one source file and you call that function in another file. In such case, you should declare the function at the top of the file calling the function.
  • 149. Defining a Function The general form of a function definition in C programming language is as follows − return_type function_name( parameter list ) { body of the function }  A function definition in C programming consists of a function header and afunction body.
  • 150. Here are all the parts of a function − Return Type − A function may return a value. The return_type is the data type of the value the function returns. Some functions perform the desired operations without returning a value. In this case, the return_type is the keyword void. Function Name − This is the actual name of the function. The function name and the parameter list together constitute the function signature. Parameters − A parameter is like a placeholder. When a function is invoked, you pass a value to the parameter. This value is referred to as actual parameter or argument. The parameter list refers to the type, order, and number of the parameters of a function. Parameters are optional; that is, a function may contain no parameters. Function Body − The function body contains a collection of statements that define what the function does.
  • 151. Example Given below is the source code for a function called max(). This function takes two parameters num1 and num2 and returns the maximum value between the two − /* function returning the max between two numbers */ int max(int num1, int num2) { /* local variable declaration */ int result; if (num1 > num2) result = num1; else result = num2; return result; }
  • 152. Calling a Function  While creating a C function, you give a definition of what the function has to do. To use a function, you will have to call that function to perform the defined task.  When a program calls a function, the program control is transferred to the called function. A called function performs a defined task and when its return statement is executed or when its function-ending closing brace is reached, it returns the program control back to the main program.  To call a function, you simply need to pass the required parameters along with the function name, and if the function returns a value, then you can store the returned value.
  • 153. Function Arguments  If a function is to use arguments, it must declare variables that accept the values of the arguments. These variables are called the formal parameters of the function.  Formal parameters behave like other local variables inside the function and are created upon entry into the function and destroyed upon exit.
  • 154. While calling a function, there are two ways in which arguments can be passed to a function − Call Type & Description 1 Call By Value This method copies the actual value of an argument into the formal parameter of the function. In this case, changes made to the parameter inside the function have no effect on the argument.
  • 155.  2 Call By Reference  This method copies the address of an argument into the formal parameter. Inside the function, the address is used to access the actual argument used in the call. This means that changes made to the parameter affect the argument.  By default, C uses call by value to pass arguments. In general, it means the code within a function cannot alter the arguments used to call the function.
  • 156. Example : Function that return some value  #include<stdio.h> int larger(int a,int b); // function declaration  void main() { int i,j,k; clrscr(); i=99; j=112; k=larger(i,j); // function call printf("%d",k); getch(); } 
  • 157. int larger(int a,int b) // function declaration { if(a>b) return a; else return b; }
  • 158. #include <stdio.h> /* function declaration */ int max(int num1, int num2); void main () { /* local variable definition */ int a = 100; int b = 200; int ret; /* calling a function to get max value */ ret = max(a, b); printf( "Max value is : %dn", ret ); getch(); /* function returning the max between two numbers */ int max(int num1, int num2) { /* local variable declaration*/ int result; if (num1 > num2) result = num1; else result = num2; return result; }
  • 159.  Factorial program in c using function #include <stdio.h>   long factorial(int);   void main() { int number; long fact = 1;   printf("Enter a number to calculate it's factorialn"); scanf("%d“,&number);   printf("%d! = %ldn", number, factorial(number)); getch(); }  
  • 160. long factorial(int n) { int c; long result = 1;  for (c = 1; c <= n; c++) result = result * c; return result; }
  • 161. #include<stdio.h> void swap(int,int); void main() { int a,b; clrscr(); printf("enter value for a&b: "); scanf("%d%d",&a,&b); swap(a,b); getch(); } void swap(int a,int b) { int temp; temp=a; a=b; b=temp; printf("after swapping the value for a & b is : %d %d“,a,b); } Program to Swap two numbers Using Functions