C program

AJAL A J
AJAL A JASST PROF at FISAT em FISAT
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
C program
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 −
C program
C program
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
C program
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
C program
#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
C program
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.
C program
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
C program
 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.
C program
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
1 de 161

Recomendados

Constants in C Programming por
Constants in C ProgrammingConstants in C Programming
Constants in C Programmingprogramming9
6.3K visualizações11 slides
Looping statements in C por
Looping statements in CLooping statements in C
Looping statements in CJeya Lakshmi
9K visualizações16 slides
C language unit-1 por
C language unit-1C language unit-1
C language unit-1Malikireddy Bramhananda Reddy
5K visualizações125 slides
Strings in C language por
Strings in C languageStrings in C language
Strings in C languageP M Patil
197 visualizações14 slides
Unit 4 Foc por
Unit 4 FocUnit 4 Foc
Unit 4 FocJAYA
3.1K visualizações164 slides
Unit ii chapter 2 Decision making and Branching in C por
Unit ii chapter 2 Decision making and Branching in CUnit ii chapter 2 Decision making and Branching in C
Unit ii chapter 2 Decision making and Branching in CSowmya Jyothi
1.6K visualizações39 slides

Mais conteúdo relacionado

Mais procurados

Data types in C por
Data types in CData types in C
Data types in CAnsh Kashyap
158 visualizações12 slides
Introduction to c programming por
Introduction to c programmingIntroduction to c programming
Introduction to c programmingABHISHEK fulwadhwa
4.6K visualizações74 slides
History of c por
History of cHistory of c
History of cShipat Bhuiya
8.2K visualizações12 slides
Conditional Statement in C Language por
Conditional Statement in C LanguageConditional Statement in C Language
Conditional Statement in C LanguageShaina Arora
12K visualizações22 slides
Introduction to c programming por
Introduction to c programmingIntroduction to c programming
Introduction to c programmingManoj Tyagi
4.7K visualizações11 slides
Decision making statements in C programming por
Decision making statements in C programmingDecision making statements in C programming
Decision making statements in C programmingRabin BK
5.6K visualizações21 slides

Mais procurados(20)

Data types in C por Ansh Kashyap
Data types in CData types in C
Data types in C
Ansh Kashyap158 visualizações
Introduction to c programming por ABHISHEK fulwadhwa
Introduction to c programmingIntroduction to c programming
Introduction to c programming
ABHISHEK fulwadhwa4.6K visualizações
History of c por Shipat Bhuiya
History of cHistory of c
History of c
Shipat Bhuiya8.2K visualizações
Conditional Statement in C Language por Shaina Arora
Conditional Statement in C LanguageConditional Statement in C Language
Conditional Statement in C Language
Shaina Arora12K visualizações
Introduction to c programming por Manoj Tyagi
Introduction to c programmingIntroduction to c programming
Introduction to c programming
Manoj Tyagi4.7K visualizações
Decision making statements in C programming por Rabin BK
Decision making statements in C programmingDecision making statements in C programming
Decision making statements in C programming
Rabin BK5.6K visualizações
Introduction to Basic C programming 01 por Wingston
Introduction to Basic C programming 01Introduction to Basic C programming 01
Introduction to Basic C programming 01
Wingston6.5K visualizações
Unit 3. Input and Output por Ashim Lamichhane
Unit 3. Input and OutputUnit 3. Input and Output
Unit 3. Input and Output
Ashim Lamichhane11.4K visualizações
Strings por Mitali Chugh
StringsStrings
Strings
Mitali Chugh5.7K visualizações
Functions in c++ por Rokonuzzaman Rony
Functions in c++Functions in c++
Functions in c++
Rokonuzzaman Rony1.3K visualizações
Basic array in c programming por Sajid Hasan
Basic array in c programmingBasic array in c programming
Basic array in c programming
Sajid Hasan939 visualizações
C++ string por Dheenadayalan18
C++ stringC++ string
C++ string
Dheenadayalan18340 visualizações
Variables in C and C++ Language por Way2itech
Variables in C and C++ LanguageVariables in C and C++ Language
Variables in C and C++ Language
Way2itech5.1K visualizações
1. over view and history of c por Harish Kumawat
1. over view and history of c1. over view and history of c
1. over view and history of c
Harish Kumawat10.4K visualizações
Control Flow Statements por Tarun Sharma
Control Flow Statements Control Flow Statements
Control Flow Statements
Tarun Sharma8.4K visualizações
Control statements in c por Sathish Narayanan
Control statements in cControl statements in c
Control statements in c
Sathish Narayanan16.8K visualizações

Similar a C program

Fundamentals of c language por
Fundamentals of c languageFundamentals of c language
Fundamentals of c languageAkshhayPatel
123 visualizações35 slides
#Code2 create c++ for beginners por
#Code2 create  c++ for beginners #Code2 create  c++ for beginners
#Code2 create c++ for beginners GDGKuwaitGoogleDevel
158 visualizações34 slides
C basics por
C basicsC basics
C basicssridevi5983
74 visualizações74 slides
C basics por
C basicsC basics
C basicssridevi5983
59 visualizações74 slides
Programming presentation por
Programming presentationProgramming presentation
Programming presentationFiaz Khokhar
184 visualizações60 slides
C_Programming_Language_tutorial__Autosaved_.pptx por
C_Programming_Language_tutorial__Autosaved_.pptxC_Programming_Language_tutorial__Autosaved_.pptx
C_Programming_Language_tutorial__Autosaved_.pptxLikhil181
4 visualizações30 slides

Similar a C program(20)

Fundamentals of c language por AkshhayPatel
Fundamentals of c languageFundamentals of c language
Fundamentals of c language
AkshhayPatel123 visualizações
#Code2 create c++ for beginners por GDGKuwaitGoogleDevel
#Code2 create  c++ for beginners #Code2 create  c++ for beginners
#Code2 create c++ for beginners
GDGKuwaitGoogleDevel158 visualizações
C basics por sridevi5983
C basicsC basics
C basics
sridevi598374 visualizações
C basics por sridevi5983
C basicsC basics
C basics
sridevi598359 visualizações
Programming presentation por Fiaz Khokhar
Programming presentationProgramming presentation
Programming presentation
Fiaz Khokhar184 visualizações
C_Programming_Language_tutorial__Autosaved_.pptx por Likhil181
C_Programming_Language_tutorial__Autosaved_.pptxC_Programming_Language_tutorial__Autosaved_.pptx
C_Programming_Language_tutorial__Autosaved_.pptx
Likhil1814 visualizações
component of c language.pptx por AnisZahirahAzman
component of c language.pptxcomponent of c language.pptx
component of c language.pptx
AnisZahirahAzman4 visualizações
C material por tarique472
C materialC material
C material
tarique4725.8K visualizações
C programming session 02 por Dushmanta Nath
C programming session 02C programming session 02
C programming session 02
Dushmanta Nath1.5K visualizações
C programming por DipjualGiri1
C programming C programming
C programming
DipjualGiri12 visualizações
C-PPT.pdf por chaithracs3
C-PPT.pdfC-PPT.pdf
C-PPT.pdf
chaithracs36 visualizações
C Programming Unit-1 por Vikram Nandini
C Programming Unit-1C Programming Unit-1
C Programming Unit-1
Vikram Nandini503 visualizações
c_programming.pdf por Home
c_programming.pdfc_programming.pdf
c_programming.pdf
Home22 visualizações
Ap Power Point Chpt2 por dplunkett
Ap Power Point Chpt2Ap Power Point Chpt2
Ap Power Point Chpt2
dplunkett566 visualizações
B.sc CSIT 2nd semester C++ Unit2 por Tekendra Nath Yogi
B.sc CSIT  2nd semester C++ Unit2B.sc CSIT  2nd semester C++ Unit2
B.sc CSIT 2nd semester C++ Unit2
Tekendra Nath Yogi418 visualizações
Unit 1 por Sowri Rajan
Unit 1Unit 1
Unit 1
Sowri Rajan15 visualizações
2 EPT 162 Lecture 2 por Don Dooley
2 EPT 162 Lecture 22 EPT 162 Lecture 2
2 EPT 162 Lecture 2
Don Dooley2 visualizações
C programming language por Abin Rimal
C programming languageC programming language
C programming language
Abin Rimal1K visualizações
M.Florence Dayana / Basics of C Language por Dr.Florence Dayana
M.Florence Dayana / Basics of C LanguageM.Florence Dayana / Basics of C Language
M.Florence Dayana / Basics of C Language
Dr.Florence Dayana107 visualizações

Mais de AJAL A J

KEAM KERALA ENTRANCE EXAM por
KEAM KERALA ENTRANCE EXAMKEAM KERALA ENTRANCE EXAM
KEAM KERALA ENTRANCE EXAMAJAL A J
711 visualizações60 slides
Paleontology Career por
Paleontology  CareerPaleontology  Career
Paleontology CareerAJAL A J
177 visualizações15 slides
CHEMISTRY basic concepts of chemistry por
CHEMISTRY  basic concepts of chemistryCHEMISTRY  basic concepts of chemistry
CHEMISTRY basic concepts of chemistryAJAL A J
4.3K visualizações28 slides
Ecology por
EcologyEcology
EcologyAJAL A J
266 visualizações39 slides
Biogeochemical cycles por
Biogeochemical cyclesBiogeochemical cycles
Biogeochemical cyclesAJAL A J
283 visualizações10 slides
ac dc bridges por
ac dc bridgesac dc bridges
ac dc bridgesAJAL A J
743 visualizações45 slides

Mais de AJAL A J(20)

KEAM KERALA ENTRANCE EXAM por AJAL A J
KEAM KERALA ENTRANCE EXAMKEAM KERALA ENTRANCE EXAM
KEAM KERALA ENTRANCE EXAM
AJAL A J711 visualizações
Paleontology Career por AJAL A J
Paleontology  CareerPaleontology  Career
Paleontology Career
AJAL A J177 visualizações
CHEMISTRY basic concepts of chemistry por AJAL A J
CHEMISTRY  basic concepts of chemistryCHEMISTRY  basic concepts of chemistry
CHEMISTRY basic concepts of chemistry
AJAL A J4.3K visualizações
Ecology por AJAL A J
EcologyEcology
Ecology
AJAL A J266 visualizações
Biogeochemical cycles por AJAL A J
Biogeochemical cyclesBiogeochemical cycles
Biogeochemical cycles
AJAL A J283 visualizações
ac dc bridges por AJAL A J
ac dc bridgesac dc bridges
ac dc bridges
AJAL A J743 visualizações
Hays bridge schering bridge wien bridge por AJAL A J
Hays bridge  schering bridge  wien bridgeHays bridge  schering bridge  wien bridge
Hays bridge schering bridge wien bridge
AJAL A J254 visualizações
App Naming Tip por AJAL A J
App Naming TipApp Naming Tip
App Naming Tip
AJAL A J165 visualizações
flora and fauna of himachal pradesh and kerala por AJAL A J
flora and fauna of himachal pradesh and keralaflora and fauna of himachal pradesh and kerala
flora and fauna of himachal pradesh and kerala
AJAL A J9.8K visualizações
B.Sc Cardiovascular Technology(CVT) por AJAL A J
 B.Sc Cardiovascular Technology(CVT)  B.Sc Cardiovascular Technology(CVT)
B.Sc Cardiovascular Technology(CVT)
AJAL A J708 visualizações
11 business strategies to make profit por AJAL A J
11 business strategies to make profit 11 business strategies to make profit
11 business strategies to make profit
AJAL A J260 visualizações
PCOS Polycystic Ovary Syndrome por AJAL A J
PCOS  Polycystic Ovary SyndromePCOS  Polycystic Ovary Syndrome
PCOS Polycystic Ovary Syndrome
AJAL A J863 visualizações
Courses and Career Options after Class 12 in Humanities por AJAL A J
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
AJAL A J1.1K visualizações
MANAGEMENT Stories por AJAL A J
 MANAGEMENT Stories MANAGEMENT Stories
MANAGEMENT Stories
AJAL A J133 visualizações
NEET PREPRATION TIPS AND STRATEGY por AJAL A J
NEET PREPRATION TIPS AND STRATEGYNEET PREPRATION TIPS AND STRATEGY
NEET PREPRATION TIPS AND STRATEGY
AJAL A J907 visualizações
REVOLUTIONS IN AGRICULTURE por AJAL A J
REVOLUTIONS IN AGRICULTUREREVOLUTIONS IN AGRICULTURE
REVOLUTIONS IN AGRICULTURE
AJAL A J156 visualizações
NRI QUOTA IN NIT'S por AJAL A J
NRI QUOTA IN NIT'S NRI QUOTA IN NIT'S
NRI QUOTA IN NIT'S
AJAL A J377 visualizações
Subjects to study if you want to work for a charity por AJAL A J
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
AJAL A J167 visualizações
IIT JEE A KERALA PERSPECTIVE por AJAL A J
IIT JEE A KERALA PERSPECTIVE IIT JEE A KERALA PERSPECTIVE
IIT JEE A KERALA PERSPECTIVE
AJAL A J77 visualizações
Clat 2020 exam COMPLETE DETAILS por AJAL A J
Clat 2020 exam COMPLETE DETAILSClat 2020 exam COMPLETE DETAILS
Clat 2020 exam COMPLETE DETAILS
AJAL A J149 visualizações

Último

BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (FRIE... por
BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (FRIE...BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (FRIE...
BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (FRIE...Nguyen Thanh Tu Collection
89 visualizações91 slides
MUET Newsletter Vol-IX, Issue-III, 2023 por
MUET Newsletter Vol-IX, Issue-III, 2023MUET Newsletter Vol-IX, Issue-III, 2023
MUET Newsletter Vol-IX, Issue-III, 2023Mehran University of Engineering & Technology, Jamshoro
139 visualizações16 slides
Thanksgiving!.pdf por
Thanksgiving!.pdfThanksgiving!.pdf
Thanksgiving!.pdfEnglishCEIPdeSigeiro
500 visualizações17 slides
DISTILLATION.pptx por
DISTILLATION.pptxDISTILLATION.pptx
DISTILLATION.pptxAnupkumar Sharma
65 visualizações47 slides
Monthly Information Session for MV Asterix (November) por
Monthly Information Session for MV Asterix (November)Monthly Information Session for MV Asterix (November)
Monthly Information Session for MV Asterix (November)Esquimalt MFRC
107 visualizações26 slides
Education of marginalized and socially disadvantages segments.pptx por
Education of marginalized and socially disadvantages segments.pptxEducation of marginalized and socially disadvantages segments.pptx
Education of marginalized and socially disadvantages segments.pptxGarimaBhati5
43 visualizações36 slides

Último(20)

BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (FRIE... por Nguyen Thanh Tu Collection
BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (FRIE...BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (FRIE...
BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (FRIE...
Nguyen Thanh Tu Collection89 visualizações
DISTILLATION.pptx por Anupkumar Sharma
DISTILLATION.pptxDISTILLATION.pptx
DISTILLATION.pptx
Anupkumar Sharma65 visualizações
Monthly Information Session for MV Asterix (November) por Esquimalt MFRC
Monthly Information Session for MV Asterix (November)Monthly Information Session for MV Asterix (November)
Monthly Information Session for MV Asterix (November)
Esquimalt MFRC107 visualizações
Education of marginalized and socially disadvantages segments.pptx por GarimaBhati5
Education of marginalized and socially disadvantages segments.pptxEducation of marginalized and socially disadvantages segments.pptx
Education of marginalized and socially disadvantages segments.pptx
GarimaBhati543 visualizações
Payment Integration using Braintree Connector | MuleSoft Mysore Meetup #37 por MysoreMuleSoftMeetup
Payment Integration using Braintree Connector | MuleSoft Mysore Meetup #37Payment Integration using Braintree Connector | MuleSoft Mysore Meetup #37
Payment Integration using Braintree Connector | MuleSoft Mysore Meetup #37
MysoreMuleSoftMeetup50 visualizações
NodeJS and ExpressJS.pdf por ArthyR3
NodeJS and ExpressJS.pdfNodeJS and ExpressJS.pdf
NodeJS and ExpressJS.pdf
ArthyR348 visualizações
UNIDAD 3 6º C.MEDIO.pptx por MarcosRodriguezUcedo
UNIDAD 3 6º C.MEDIO.pptxUNIDAD 3 6º C.MEDIO.pptx
UNIDAD 3 6º C.MEDIO.pptx
MarcosRodriguezUcedo146 visualizações
JQUERY.pdf por ArthyR3
JQUERY.pdfJQUERY.pdf
JQUERY.pdf
ArthyR3105 visualizações
Creative Restart 2023: Leonard Savage - The Permanent Brief: Unearthing unobv... por Taste
Creative Restart 2023: Leonard Savage - The Permanent Brief: Unearthing unobv...Creative Restart 2023: Leonard Savage - The Permanent Brief: Unearthing unobv...
Creative Restart 2023: Leonard Savage - The Permanent Brief: Unearthing unobv...
Taste55 visualizações
Meet the Bible por Steve Thomason
Meet the BibleMeet the Bible
Meet the Bible
Steve Thomason78 visualizações
The Accursed House by Émile Gaboriau por DivyaSheta
The Accursed House  by Émile GaboriauThe Accursed House  by Émile Gaboriau
The Accursed House by Émile Gaboriau
DivyaSheta251 visualizações
EILO EXCURSION PROGRAMME 2023 por info33492
EILO EXCURSION PROGRAMME 2023EILO EXCURSION PROGRAMME 2023
EILO EXCURSION PROGRAMME 2023
info33492202 visualizações
Parts of Speech (1).pptx por mhkpreet001
Parts of Speech (1).pptxParts of Speech (1).pptx
Parts of Speech (1).pptx
mhkpreet00146 visualizações
Narration lesson plan por TARIQ KHAN
Narration lesson planNarration lesson plan
Narration lesson plan
TARIQ KHAN75 visualizações
Guess Papers ADC 1, Karachi University por Khalid Aziz
Guess Papers ADC 1, Karachi UniversityGuess Papers ADC 1, Karachi University
Guess Papers ADC 1, Karachi University
Khalid Aziz99 visualizações
Jibachha publishing Textbook.docx por DrJibachhaSahVetphys
Jibachha publishing Textbook.docxJibachha publishing Textbook.docx
Jibachha publishing Textbook.docx
DrJibachhaSahVetphys54 visualizações
Create a Structure in VBNet.pptx por Breach_P
Create a Structure in VBNet.pptxCreate a Structure in VBNet.pptx
Create a Structure in VBNet.pptx
Breach_P86 visualizações

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
  • 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 −
  • 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
  • 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
  • 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
  • 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.
  • 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
  • 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.
  • 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