CS3353 Unit1
CS3353 Unit1
CS3353
C Programming and
Data Structures
(R-2021)
UNIT –I NOTES
III SEMESTER
B.E.(ECE) & B.E.(EEE)
S.no Topic
1 Structure of a C program
2 compilation and linking processes
3 Constants
4 Variables
5 Data Types
6 Expressions using operators in C
7 Managing Input and Output operations in C
8 Decision Making and Branching in C
9 Looping statements in C
10 Arrays
Initialization
Declaration
One dimensional array
Two-dimensional arrays
11 Strings
String operations
String Arrays
Link section:
The link section provides instruction to the compiler to link or include the
required in-built functions from the system library such as using the #include
directive.Eg #include<stdio.h>, #include<string.h>,#include<math.h>.
Definition section:
The definition section defines all symbolic constants using the #define
directive(optional). Having the constants being defined here, we can use them
elsewhere in code.
PROGRAM STATEMENT
A statement performs an action
when a program is executed.
Labeled statements: can be used to mark any statement so that control may be
transferred to the statement by switch statement
Case 1:
labelABC:
EXAMPLE C PROGRAM
//sample.c//
#include<stdio.h>
main()
{
printf(“welcome to C”);
return 0;
}
Compile and Link C Program
There are three basic phases occurred when we execute any C program.
Preprocessing
Compiling
(assembler)
Linking
Linking Phase:The link phase is implemented by the linker. The linker is a process that
accepts as input object files and libraries to produce the final executable program.
The process can be split into four separate stages: Preprocessing, compilation, assembly, and
linking.
/*
* "Hello, World!": A classic.
*/
#include <stdio.h>
int main(void)
{
puts("Hello, World!");
return 0;
}
Preprocessing
The first stage of compilation is called preprocessing. In this stage, lines starting with a #
character are interpreted by the preprocessor as preprocessor commands. These commands
form a simple macro language with its own syntax and semantics.
gcc -E hello_world.c
int main(void) {
puts("Hello, World!");
return 0;
}
Compilation
In this stage, the preprocessed code is translated to assembly instructions These form an
intermediate readable language.
Some compilers also supports the use of an integrated assembler, in which the
compilation stage generates machine code directly, avoiding the overhead of generating
the intermediate assembly instructions and invoking the assembler. object code is
directly produced by compiler.
to view the result of the compilation stage, pass the -S option to cc:
gcc -S hello_world.c
Assembly
During the assembly stage, an assembler is used to translate the assembly instructions to
machine code, or object code.
--The output consists of actual instructions to be run by the target processor.
Linking
The object code generated in the assembly stage is composed of machine instructions that the
processor understands but some pieces of the program are out of order or missing. To
produce an executable program, the existing pieces have to be rearranged and the missing
ones filled in. This process is called linking.
Finally to run
a.out hello_world.c
To compile:
gcc filename.c
./a.out
Constants/Literals
A constant is a value or an identifier whose value cannot be altered in a program.
1. By “const” keyword
2. By “#define” preprocessor directive
Eg-1
#include<stdio.h>
main()
{
const int SIDE = 10;
int area;
area = SIDE*SIDE;
printf("The area of the square %d is: %d sq. units" , SIDE, area);
}
Output
The area of the square 10 is: 100 sq. Units
C constant
Primary Constants
-integer constant
-floating point constant
-character Constant
-String Constant
-Backslash Constant
1. Integer constants
An integer constant is a numeric constant (associated with number) without any fractional or
exponential part. There are three types of integer constants in C programming:
decimal constant(base 10)
octal constant(base 8)
hexadecimal constant(base 16)
For example:
Decimal constants: 1,0, -9, 22 etc
Octal constants: 021, 077, 033 etc
Hexadecimal constants: 0x7f, 0x2a, 0x521 etc
In C programming, octal constant starts with a 0 and hexadecimal constant starts with a 0x.
55 /*int constant */
55l /*unsigned int constant*/
55 ul /*unsigned long constant*/
2. Floating-point constants
A floating point constant is a numeric constant that has either a fractional form or an
exponent form(decimal point). For example:
633E---illegal..incomplete exponent
-2.0 6.333 –correct 633f—illegal..no decimal or exponent
0.0000234 .e633—illegal..missing integer
633E-4L-correct
-0.22E-5
3. Character constants
A character constant is a constant which uses single quotation around characters.
For example:
'a'
'6',
'=',
'F'
Rules for defining character constants
OUTPUT OUTPUT
10 20 10 20
The Area of Triangle is: The Area of Triangle is:
100 100
Example program using const keyword in C:
#include <stdio.h>
void main()
{
const int height = 100; /*int constant*/
const float number = 3.14; /*Real constant*/
const char letter = 'A'; /*char constant*/
const char letter_sequence[10] = "ABC"; /*string constant*/
const char backslash_char = '\?'; /*special char cnst*/
printf("value of height :%d \n", height );
printf("value of number : %f \n", number );
printf("value of letter : %c \n", letter );
printf("value of letter_sequence : %s \n", letter_sequence);
printf("value of backslash_char : %c \n", backslash_char);
}
Output:
value of height : 100
value of number : 3.140000
value of letter : A
value of letter_sequence : ABC
value of backslash_char : ?
#include <stdio.h>
#define height 100 Output:
#define number 3.14
value of height : 100
#define letter 'A'
#define letter_sequence "ABC" value of number : 3.140000
#define backslash_char '\?' value of letter : A
void main() value of letter_sequence : ABC
{ value of backslash_char : ?
printf("value of height : %d \n", height );
printf("value of number : %f \n", number );
printf("value of letter : %c \n", letter );
printf("value of letter_sequence : %s \n",letter_sequence);
printf("value of backslash_char : %c \n",backslash_char);
}
The data type, of a variable determines a set of values that a variable might take and a set
of operations that can be applied to those values.
Data type refer to the type and size of data associated with the variable and functions.
Allows 15 digits
after decimal point.
long double 10 -1.7e-4932 to 1.7e4932 %LF
Allows 15 digits
after decimal point.
/*Program*/
#include<stdio.h>
int main()
{
char a;
unsigned char b;
int i;
unsigned int j;
long int k;
unsigned long int m;
float x;
double y
long double z;
return 0;
}
The specifiers and qualifiers for the data types can be broadly classified into
three types
Size qualifiers alter the size of the basic data types. There are two such qualifiers that can
be used with the data type int; these are short and long.
short, when placed in front of the data type int declaration, tells the C compiler that the
particular variable being declared is used to store fairly small integer values. Long specifies it
is a very big integer value.Long integers require twice the memory of than small ints.
Sign specifiers: for example fot int data type out of 2bytes(2*8=16bits) of its size the
highest bit(the sixtheenth bit) is used to store the sign of the integer value. The bit is 1 if
number is negative and 0 if the number is positive.
Bit Bit Bit Bit Bit Bit Bit Bit Bit Bit Bit Bit Bit Bit Bit Bit
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 Sign of number
(1 for –ve and 0
for +ve0
Type qualifiers : There are two type qualifiers, const and volatile;
Eg: const float pi = 3.14156; // specifies that the variable pi can never be changed by the
Program.
Table:Size and range in (16-bit machines)
Allowed combinations of basic data types and modifi ers in C for a 16-bit
computer
VARIABLES
Variable is the name of memory location which holds the data. Unlike constant, variables are
changeable, value of a variable can be changed during execution of a program. A
programmer must chose a meaningful variable name.
Variables are used for holding data values so that they can be utilized for various
computations in a program.A variable must be declaed and then used for coputation work in
program./A variable is an identifier used for storing and holding some data(value).
1.A data type: Like int, double, float. Once defined,the type of a C variable
cannot be changed.
2.A name of the variable.
3.A value that can be changed by assigning a new value to the variable. The
kind of values a variable can assume depends on its type.
Eg : for variable int salary,it can only take integer values can only take integer
values like 65000 and not 6500.0
Declaration of a variable must be done before it is used for any computation in the
program.
Declaration tells the compiler what the variable name is.
Declaration tells what type of data the variable will hold.
Until the variable is not defined/or/declared compiler will not allocate memory space to the
variables.
A variable can also be declared outside main() function.
A variable can also be declared in other program and declared using extern keyword.
int yearly_salary;
float monthly_salary;
int a;
double x;
int ECE1111;
Initializing a variable:=
Initializing a variable means to provide a value to variable
Variables are a way of reserving memory to hold some data and assign names to them so that
we don’t have to remember the numbers like REG46735 or memory address like FFFFoxFF
and instead we can use the memory location by simply referring to the variable.
Arithmetic Operators
Relational Operators
Logical Operators
Bitwise Operators
Assignment Operators
Misc Operators
Arithmetic Operators
The following table shows all the arithmetic operators supported by the C language.
Assume variable A holds 10 and variable B holds 20
Relational Operators
Following table shows all the logical operators supported by C language. Assume variable A
holds 1 and variable B holds 0, then −
Bitwise Operators
Bitwise operator works on bits and perform bit-by-bit operation. The truth tables for &, |, and ^ is as follows −
p q p&q p|q p^q
0 0 0 0 0
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1
Assume A = 60 and B = 13 in binary format, they will be as follows −
A = 0011 1100
B = 0000 1101
The following table lists the assignment operators supported by the C language
Misc Operators
For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has a higher precedence
than +, so it first gets multiplied with 3*2 and then adds into 7.
Expression
Eg : c+d
x/y+b+a*a*a
3.14 *r *r
#include<stdio.h>
int main()
{
int num1,num2,num3;
scanf("%d %d %d",&a,&b,&c);
if((a>b)&&(a>c))
printf("\n %d is greatest",a);
else if(b>c)
printf("\n %d is greatest",b ");
else
printf("\n %d is greatest",c);
return 0;
}
Example program –find odd or even number
Example of Arithmetic(% mod) and relational operators(==)
#include<stdio.h>
int main()
{ int num,result;
if(num%2==0)
printf(“even number \n”);
else
printf(“odd number \n”);
return 0;
}
Bitwise XOR
Explanation
Output = 21
complement = 220
OutputAND = 8
OutputOR = 29
Managing Input and Output operations
4) getche( )
5) fgets( ) 4)fputs( )
6)fscanf( ) 5)fprint( )
Input means to provide the program with some data to be used in the program
Output means to display data on screen or write the data to a printer or a file.
input- getchar()
output- putchar()
The int getchar(void) function reads the next available character from the screen and returns
it as an integer. This function reads only single character at a time.
The int putchar(int c) function puts the passed character on the screen and returns the same
character. This function puts only single character at a time.
program
#include <stdio.h>
int main( ) {
output
int c; $./a.out
Enter a value : this is DS class
printf( "Enter a value :"); You entered: t
c = getchar( );
return 0;
}
2. String input and output[gets() and puts()
The gets( ) function reads a line from stdin into the buffer pointed to by s until either a
terminating newline or EOF (End of File).
The puts( ) function writes the string 's' and 'a' trailing newline to stdout.
Program
return 0;
}
scanf()
scanf() is a predefined function in "stdio.h" header file. It can be used to read the input value
from the keyword.
Syntax of scanf() function
1. & ampersand symbol is the address operator specifying the address of the variable
2. control string holds the format of the data
3. variable1, variable2, ... are the names of the variables that will hold the input value.
Example
double d;
char c;
long int l;
scanf("%c%lf%ld",&c&d&l );
Printf
Printf is a predefined function in "stdio.h" header file, by using this function, we can print the
data or user defined message on console or monitor. While working with printf(), it can take
any number of arguments but first argument must be within the double cotes (" ") and every
argument should separated with comma ( , ) Within the double cotes, whatever we pass, it
prints same, if any format specifies are there, then value is copied in that place.
Program
#include <stdio.h> //This is needed to run printf() function.
int main()
{
printf("C Programming"); //displays the content inside quotation
return 0;
}
Output
C Programming
Program(integer and float)
#include <stdio.h>
#include <conio.h>
void main();
{
int a;
float b;
clrscr();
printf("Enter any two numbers: ");
scanf("%d %f",&a,&b);
printf("%d %f \n",a,b);
getch();
}
return 0; Output
}
4 digit integer right justified to 6 column: 9876
4 digit integer right justified to 3 column: 9876
Floating point number rounded to 2 digits: 987.65
Floating point number rounded to 0 digits: 988
Floating point number in exponential form: 9.876543e+02
The fgets() function takes three arguments, first is the string read from the file, second is size
of string(character array) and third is the file pointer from where the string will be read.
Example File*fp;
Str[80];
fgets(str,80,fp)
Example program
#include<stdio.h>
void main()
{
FILE *fp;
char str[80];
fp = fopen("file.txt","r"); // opens file in read mode (“r”)
while((fgets(str,80,fp))!=NULL)
printf("%s",str); //reads content from file
fclose(fp);
}
Data in file...
C is a general-purpose programming language.
It is developed by Dennis Ritchie.
The fputs() function takes two arguments, first is the string to be written to the file and
second is the file pointer where the string will be written.
Syntax:
fputs(char str[], FILE *fp);
#include < stdio.h >
int main ()
{
FILE *fp;
fp = fopen("proverb.txt", "w+"); //opening file in write mode
fputs("Cleanliness is next to godliness.", fp);
fputs("Better late than never.", fp);
fputs("The pen is mightier than the sword.", fp);
fclose(fp);
return(0);
}
Output
#include<stdio.h>
void main()
{
FILE *fp;
char ch;
int roll;
char name[25];
fp = fopen("file.txt","r");
printf("\n Reading from file...\n");
while((fscanf(fp,"%d%s",&rollno,&name))!=NULL)
printf("\n %d\t%s",rollno,name);//reading data
fclose(fp);
}
Output :
Example program
#include<stdio.h>
void main()
{ Output
FILE *fp;
int roll; 6666
char name[25]; john
fp = fopen("file.txt","w");
scanf("%d",&roll);
scanf("%s",name);
fprintf(fp,"%d%s%",roll,name);
close(fp);
}
EC8393 PREPARED BY CH.SRILAKSHMI,AP/IT R.M.D ENGG COLLEGE
if(test-expression)
It allows the computer to evaluate the expression first and them depending on whether
the value of the expression is "true" or "false", it transfer the control to a particular
statements. This point of program has two paths to flow, one for the true and the other
for the false condition.
if(test-expression)
{
statement-block
}
statement-x;
44
Nested if
Example:
#include <stdio.h>
int main ()
{
int a = 100;
int b = 200;
if( a == 100 ) {
/* if condition is true then check the following */
if( b == 200 ) {
/* if condition is true then print the following */
printf("Value of a is 100 and b is 200\n" );
}
}
printf("Exact value of a is : %d\n", a );
printf("Exact value of b is : %d\n", b );
return 0;
}
www.AUNewsBlog.net
www.AUNewsBlog.net
Syntax-1 Syntax-2
if(test-condition-1) If(test-condition-1)
{ {
(stmts) if(test-condition-2)
else {
{ statement-1;
if(condition 2) }
{ else
Statement-1; {
} statement-2;
else }
{ }
statement-2; else
} {
} statement-3;
} }
statement-x statement-x
If the test-condition-1 is false, the statement-3 will be executed; other wise it continues
the second test. If the condition-2 is true, the statement-2 will be evaluated and then the
control is transferred to the statement-x.
Example:Program to relate two integers using =, > or <
#include <stdio.h>
int main()
{
int number1, number2;
printf("Enter two integers: ");
scanf("%d %d", &number1, &number2);
www.AUNewsBlog.net
www.AUNewsBlog.net
www.AUNewsBlog.net
www.AUNewsBlog.net
www.AUNewsBlog.net
www.AUNewsBlog.net
BREAK is a keyword that allows us to jump out of a loop instantly, without waiting to
get back to the conditional test.
break;
Output
Example program value of a: 10
#include <stdio.h> value of a: 11
int main () value of a: 12
{ value of a: 13
int a = 10; value of a: 14
while( a < 20 ) value of a: 15
{
printf("value of a: %d\n", a);
a++;
if( a > 15)
{
break;
}
}
return 0;
}
www.AUNewsBlog.net
www.AUNewsBlog.net
The continue statement in C programming works somewhat like the break statement.
Instead of forcing termination, it forces the next iteration of the loop to take place,
skipping any code in between.
For the for loop, continue statement causes the conditional test and increment portions
of the loop to execute. For the while and do...while loops, continue statement causes the
program control to pass to the conditional tests.
Syntax: continue;
Example program
Output
#include <stdio.h> value of a: 10
int main () value of a: 11
value of a: 12
{ value of a: 13
int a = 10; value of a: 14
do { value of a: 16
value of a: 17
if( a == 15) value of a: 18
{ value of a: 19
/* skip the iteration */
a = a + 1;
continue;
}
printf("value of a: %d\n", a);
a++;
} while( a < 20 );
return 0;
}
www.AUNewsBlog.net
www.AUNewsBlog.net
Break Continue
The break statement can be used in both The continue statement can appear only in
switch and loop (for, while, do while) loops. You will get an error if this appears
statements. in switch statement.
A continue doesn't terminate the loop, it
A break causes the switch or loop
causes the loop to go to the next iteration.
statements to terminate the moment it is
The continue statement is used to skip
executed. Loop or switch ends abruptly
statements in the loop that appear after the
when break is encountered.
continue.
The continue statement can appear only in
The break statement can be used in both
loops. You will get an error if this appears
switch and loop statements.
in switch statement.
When a break statement is encountered, it When a continue statement is
terminates the block and gets the control encountered, it gets the control to the next
out of the switch or loop. iteration of the loop.
GOTO
GOTO STATEMENT
‘C’ supports goto statement to branch unconditionally from one point to another in the program.
A goto statement in C programming provides an unconditional jump from the 'goto' to a labeled
statement.
NOTE − Use of goto statement is highly discouraged in any programming language because it makes
difficult to trace the control flow of a program, making the program hard to understand and hard to
modify. Any program that uses a goto can be rewritten to avoid them.
Syntax
goto label;
..
.
label: statement;
Or
label: statement;
...
...
goto label;
www.AUNewsBlog.net
www.AUNewsBlog.net
Output
value of a: 10
value of a: 11
value of a: 12
Example program value of a: 13
#include <stdio.h> value of a: 14
value of a: 16
int main ()
value of a: 17
{
value of a: 18
int a = 10;
value of a: 19
ABCL:do
{
if( a == 15)
{
a = a + 1;
goto ABCL;
}
printf("value of a: %d\n", a);
a++;
}while( a < 20 );
return 0;
}
program to print ‘n’ natural number
#include<stdio.h>
void main( )
{
int n,i=1;
clrscr();
printf("enter number");
scanf("%d\t",n);
printf("natural numbers from 1 to %d", n);
lb: printf("%d\t",i);
i++;
if(i<=n)
goto lb;
getch();
}
www.AUNewsBlog.net
www.AUNewsBlog.net
LOOPING STATEMENTS
If the loop Test Condition is true, then the loop is executed, the
sequence of statements to be executed is kept inside the curly braces { } is
known as the Loop body. After every execution of the 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, and execution
breaks out of the loop.
Types of Loop
1. while loop
2. for loop
3. do while loop
while loop
www.AUNewsBlog.net
www.AUNewsBlog.net
5 10 15 20 25 30 35 40 45 50 55 60
www.AUNewsBlog.net
www.AUNewsBlog.net
1) break statement
www.AUNewsBlog.net
www.AUNewsBlog.net
It causes the control to go directly to the test-condition and then continue the
loop process. On encountering continue, cursor leave the current cycle of loop,
and starts with the next cycle.
For Loop
www.AUNewsBlog.net
www.AUNewsBlog.net
www.AUNewsBlog.net
www.AUNewsBlog.net
4. MULTIDIMENTIONAL ARRAYS
An array is a collection of similar data items, accessed using a common name. The collection of
element can all be integers or be all decimal value or be all characters or be all strings.
Array Declaration:
To declare an array in C, a programmer specifies the type of the elements and the number
of elements required. The arraySize must be an integer constant greater than zero and
datatype can be any valid C data type.
Example-1
int n=25; int n;
int number[20]; double x[n], y[n]; //array Scanf(“%d”,&n);//get size
int marks[44]; declaration int x[n]; //array declaration
float salary[10];
double value[25];
#include<stdio.h> #include<stdio.h>
#define N 100 int main( )
int main( ) {
{ int N=10,M=20;
int marks[N];//array dec int marks[N*M];//array dec
.... ....
return 0; return 0;
} }
Syntax-2
<storage class> datatype arrayName[ arraySize ];
www.AUNewsBlog.net
www.AUNewsBlog.net
mark[0] = 55
mark[1] = 66
mark[2] = 77
mark[3] = 88
mark[4] = 99
it means....
balance[0] = 1000.0;
balance[1] = 2.0;
balance[2] = 3.4;
balance[3] = 7.0;
balance[4] = 50.0;
Automatic sizing
int arr[] = {3,1,5,7,9};
Here, the C compiler will deduce the size of the array automatically based on the number of
elements. Array size is deduced to be 5
www.AUNewsBlog.net
www.AUNewsBlog.net
www.AUNewsBlog.net
www.AUNewsBlog.net
#include <stdio.h>
int main()
{
int i, n, arr[20], small, pos;
printf("\n Enter the number of elements in the array : ");
scanf("%d", &n);
printf("\n Enter the elements : ");
for(i=0;i<n;i++)
scanf("%d",&arr[i]);
small = arr[0] Output
for(i=1;i<n;i++) Enter the number of elements in the array : 5
{ Enter the elements : 7 6 5 14 3
if(arr[i]<small) The smallest element is : 3
{ The position of the smallest element in the
small = arr[i]; array is : 4
pos = i;
}
}
printf("\n The smallest element is : %d", small);
printf("\n The position of the smallest element in the array is:
%d", pos);
return 0;
}
Logic Here the remainders of the integer division of a decimal number by 2 are stored as
consecutive array elements.The division procedure is repeated until the number becomes 0.
www.AUNewsBlog.net
www.AUNewsBlog.net
www.AUNewsBlog.net
www.AUNewsBlog.net
www.AUNewsBlog.net
www.AUNewsBlog.net
Program:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n,i,key, FOUND=0, a[30]; // array declaration
printf(“\n How many numbers:”);
Output
scanf(“%d”,&n); // array size
printf(“\n Enter the array elements: \n”); How many numbers: 6
for(i=0 ; i<n; i++) Enter the array elements:
{ 21
scanf(“%d”, &a[i]); 33
} 46
52
printf(“\n Enter the key to be searched: ”); 27
scanf(“%d”,&key); Enter the key to be searched: 73
NOT FOUND
for(i=0 ; i<n; i++) // searching an element in an array
if(a[i] == key)
{
printf(“\n Found at %d”,i);
FOUND=1;
}
Output
if(FOUND = = 0)
printf(“\n NOT FOUND...”); How many numbers: 6
return 0; Enter the array elements:
} 21
33
46
52
27
Enter the key to be searched: 52
Found at 3
www.AUNewsBlog.net
BINARY SEARCHING
The binary search halves the size of the list to search in each Iteration
Logic : Binary search can be explained simply by the analogy of searching for a page in a
book. Suppose a reader is searching for page 90 in a book of 150 pages. The reader would
first open the book at random towards the latter half of the book. If the page number is less
than 90, the reader would open at a page to the right; if it is greater than 90, the reader would
open at a page to the left, repeating the process till page 90 was found.
The array is searched sequentially and unsorted items are moved and inserted into the sorted
sub-list (in the same array). This algorithm is not suitable for large data sets as its average and
worst case complexity are of Ο(n2), where n is the number of items.
It finds that both 14 and 33 are already in ascending order. For now, 14 is in sorted sub-list.
It swaps 33 with 27. It also checks with all the elements of sorted sub-list. Here we see that
the sorted sub-list has only one element 14, and 27 is greater than 14. Hence, the sorted sub-
list remains sorted after swapping.
By now we have 14 and 27 in the sorted sub-list. Next, it compares 33 with 10. ... and so on.
Algorithm
Now we have a bigger picture of how this sorting technique works, so we can derive simple
steps by which we can achieve insertion sort.
Program
#include<stdio.h>
int main()
{
int data[100],n,temp,i,j;
printf("Enter number of terms(should be less than 100): ");
scanf("%d",&n);
printf("Enter elements: "); Enter number of terms(should be less than 100):5
for(i=0;i<n;i++)
{
scanf("%d",&data[i]); Enter elements: 33 12 4 26 77
}
for(i=1;i<n;i++) In ascending order: 4 12 26 33 77
{
temp = data[i];
j=i-1;
while(temp<data[j] && j>=0)
/*To sort elements in descending order, change temp<data[j] to temp>data[j]
in above line.*/
{
data[j+1] = data[j];
--j;
}
data[j+1]=temp;
}
printf("In ascending order: ");
for(i=0; i<n; i++)
printf("%d\t",data[i]);
return 0;
}
Ascending order
Step by step descriptive logic to sort array in ascending order.
1. Input size of array and elements in array. Store it in some variable say size and arr.
2. To select each element from array, run an outer loop from 0 to size - 1. The loop structure
must look like for(i=0; i<size; i++).
3. Run another inner loop from i + 1 to size - 1 to place currently selected element at its correct
position. The loop structure should look like for(j = i + 1; j<size; j++).
4. Inside inner loop to compare currently selected element with subsequent element and swap
two array elements if not placed at its correct position.
Which is if(arr[i] > arr[j]) then swap arr[i] with arr[j].
Program
#include <stdio.h>
#define MAX_SIZE 100 // Maximum array size
int main()
{
int arr[MAX_SIZE];
int size;
int i, j, temp;
return 0;
}
OUTPUT
Enter size of array: 10
Enter elements in array: 20 2 10 6 52 31 0 45 79 40
Elements of array in ascending order:
0 2 6 10 20 31 40 45 52 79
/*C program to sort an one dimensional array in descending order.*/
#include <stdio.h>
#define MAX 100
int main()
{
int arr[MAX],n,i,j;
int temp;
//sort array
for(i=0;i< n;i++)
{
for(j=i+1;j< n;j++)
{
if(arr[i]< arr[j])
{
temp =arr[i];
arr[i] =arr[j];
arr[j] =temp;
}
}
}
Two dimentional arrays stores data in tabular column format represented as rows and columns
Array Declaration:
datatype arrayname[size][size];
Array Initialization:
int a[2][2]={ {1,4 },{2,3}}
int b[2][2]={1,4,2,3}
1 4
2 3
12.3 45.2
19.3 23.4
#include <stdio.h>
int main()
{
int i,j;
int a[3][2] = {{4,7},{1,0},{6,2}};
for(i = 0; i < 3; i++)
{
for(j = 0; j < 2; j++)
{
printf(“%d”, a[i][j]);
}
printf(“\n”);
}
return 0;
}
Row-1 4 7
Row -2 1 0
Row-3 6 2
1 2 3 4 5 6 7 8 9
Row 0 Row 1 Row 2
WORKING WITH TWO-DIMENSIONAL ARRAYS
Transpose of a matrix
Transpose of A is AT=(aji), where i is the row number and j is the column number.
Program
#include <stdio.h>
int main()
{
int a[10][10], transpose[10][10], r, c, i, j;
printf("Enter rows and columns of matrix: ");
scanf("%d %d", &r, &c);
Sample output
// getting elements of the matrix Enter rows and columns of
printf("\nEnter elements of matrix:\n"); matrix: 2
for(i=0; i<r; ++i) 3
for(j=0; j<c; ++j)
{ Enter element of matrix:
printf("Enter element a%d%d: ",i+1, j+1); Enter element a11: 2
scanf("%d", &a[i][j]); Enter element a12: 3
} Enter element a13: 4
Enter element a21: 5
// Displaying the matrix a[][] */ Enter element a22: 6
printf("\n Entered Matrix: \n"); Enter element a23: 4
for(i=0; i<r; ++i)
for(j=0; j<c; ++j) Entered Matrix:
{ 23 4
printf("%d ", a[i][j]);
if (j == c-1) 5 6 4
printf("\n\n");
}
Transpose of Matrix:
// Finding the transpose of matrix a 2 5
for(i=0; i<r; ++i)
for(j=0; j<c; ++j) 3 6
{
transpose[j][i] = a[i][j]; 4 4
}
return 0;
}
Program -2(Transpose)
#include <stdio.h>
void main()
{
int array[10][10];
int i, j, m, n;
$ cc pgm85.c
$ a.out
Enter the order of the matrix
3 3
Enter the coefiicients of the matrix
3 7 9
2 7 5
6 3 4
The given matrix is
3 7 9
2 7 5
6 3 4
Transpose of matrix is
3 2 6
7 7 3
9 5 4
Matrix addition and subtraction
#include <stdio.h>
int main(){
int r, c, a[100][100], b[100][100], sum[100][100], i, j;
#include <stdio.h>
#include <math.h>
#defi ne row 10
#defi ne col 10
int main()
{
fl oat mat[row][col], s;
int i,j,r,c;
printf(“\n Input number of rows:”);
scanf(“%d”, &r);
printf(“\n Input number of cols:”);
scanf(“%d”, &c);
for(i = 0 ; i< r; i++)
{
for(j = 0 ;j<c; j++)
{
scanf(“%f”, &mat[i][j]);
}
}
printf(“\n Entered 2D array is as follows:\n”);
for(i = 0; i < r; i++)
{
for(j = 0; j < c; j++)
{
printf(“%f”, mat[i][j]);
}
printf(“\n”);
}
s = 0.0;
for(i = 0; i < r; i++)
{
for(j = 0; j < c; j++)
{
s += mat[i][j] * mat[i][j];
}
}
printf(“\n Norm of above matrix is: %f”, sqrt(s));
return 0;
}
C Program to read a matrix and find sum, product of all elements of two dimensional (matrix)
array
include <stdio.h>
#define MAXROW 10 Enter number of Rows :3
#define MAXCOL 10 Enter number of Cols :3
int main()
{ Enter matrix elements :
int matrix[MAXROW][MAXCOL]; Enter element [1,1] : 1
int i,j,r,c; Enter element [1,2] : 1
int sum,product; Enter element [1,3] : 1
Enter element [2,1] : 2
printf("Enter number of Rows :");
Enter element [2,2] : 2
scanf("%d",&r);
printf("Enter number of Cols :");
Enter element [2,3] : 2
scanf("%d",&c); Enter element [3,1] : 3
Enter element [3,2] : 3
printf("\nEnter matrix elements :\n"); Enter element [3,3] : 3
for(i=0;i< r;i++)
{ SUM of all elements : 18
for(j=0;j< c;j++) Product of all elements :216
{
printf("Enter element [%d,%d] : ",i+1,j+1);
scanf("%d",&matrix[i][j]);
}
}
sum=0;
product=1;
for(i=0;i< r;i++)
{
for(j=0;j< c;j++)
{
sum+=matrix[i][j];
product*= matrix[i][j];
} }
printf("\nSUM of all elements : %d \nProduct of all elements :%d",sum,product);
return 0;
}
Find the sum of diagonal elements of a matrix 1 2 3
#include < stdio.h >
int main() 2 4 6
{ 3 5 8
int a[10][10],i,j,sum=0,r,c;
clrscr(); Sum of diagonal=13
printf("\n Enter the number of rows and column ");
scanf("%d%d",&r,&c);
printf("\nEnter the %dX%d matrix",r,c);
for(i=0;i < r;i++)
{
for(j=0;j < c;j++)
{
scanf("%d",&a[i][j]);
}//for
}//for
for(i=0;i < r;i++)
{ for(j=0;j < c;j++)
{ if(i==j)
{
sum+=a[i][j];
}
}//for
}//for
printf("\nThe sum of diagonal elements is %d",sum); return 0;
}//main
#include <stdio.h>
void main ()
{ static int array[10][10]; Enter the order of the matix
int i, j, m, n, a = 0, sum = 0; 22
printf("Enetr the order of the matix \n"); Enter the co-efficients of the matrix
scanf("%d %d", &m, &n); 40 30
if (m == n ) 38 90
{ The given matrix is
printf("Enter the co-efficients of the matrix\n"); 40 30
for (i = 0; i < m; ++i) 38 90
{
for (j = 0; j < n; ++j) The sum of the main diagonal elements is
{ = 130
scanf("%d", &array[i][j]); The sum of the off diagonal elements is
} = 68
}
printf("The given matrix is \n");
for (i = 0; i < m; ++i)
{
for (j = 0; j < n; ++j)
{
printf(" %d", array[i][j]);
}
printf("\n");
}
C Program to Find the Frequency of Odd & Even Numbers in the given Matrix
#include <stdio.h>
void main()
{
Strings in C are represented by arrays of characters. The end of the string is marked with a
special character, the null character
DECLARATION OF STRINGS
char str[30];
char text[80];
STRING INITIALIZATION
char arr[4]={‘s’,'h’,'b',’r‘,’\0’}
char *c = "abcd";
char str=“100”
char str=“3.4”
Char str=“111000”
STRING INPUT /OUTPUT #include <stdio.h>
#include <string.h>
– printf("%s",str), scanf("%s",str) int main()
{
– gets(str),puts(str) char nickname[20];
scanf("%s", nickname);
– fgets with stdin and fputs with stdout printf("%s",nickname);
return 0;
– fgets( ) and fputs( )…for files }
stdin,
stdout, and
stderr
--The input stream is called standard-input (stdin); the usual output stream is called standard-
output (stdout); and the side stream of output characters for errors is called standard error
(stderr).
Example program
#include <stdio.h>
int main()
{
int fi rst, second;
fprintf(stdout,“Enter two ints in this line: ”);
fscanf(stdin,“%d %d”, &fi rst, &second);
fprintf(stdout,“Their sum is: %d.\n”, fi rst + second);
return 0;
}
Character Manipulation
This program counts the number of words in a string converts a given text into a capital letter
#include <stdio.h>
#include <ctype.h> using toupper() function
int main() #include <stdio.h>
{ #include <string.h>
char s[30]; int main()
int i=0,count=0;
printf(“\n enter the string\n”);
{
scanf(“%[^\n]”,s); char a[30];
while(s[i]!=‘\0’) int i=0;
{ printf(“\n enter the string\n”);
while(isspace(s[i])) gets(a);
i++;
if(s[i]!=‘\0’) while(a[i]!=‘\0’)
{ {
++count; a[i]=toupper(a[i]);
while(!isspace(s[i]) && s[i] != ‘\0’) i++;
i++;
}
}
} a[i]=‘\0’;
printf(“\n NO. of words in the string is %d:”, count); puts(a);
return 0; return 0;
} }
Output: Output:
enter the string enter the string
how are you how
NO. of words in the string is HOW
3
Disadvantage : C has the weakest character string capability. Strictly speaking, there are no
character strings in C, just arrays of single characters.
A set of standard C library functions that are contained in <string.h> provides the following.
Function Description
strcpy(s1,s2) Copies s2 into s1
strncpy(s1,s2,n) It copies first n characters of str2 into str1.
strcat(s1,s2) Concatenates s2 to s1. That is, it appends the string contained by s2 to
the end of the string pointed to by s1. The terminating null character
strncat(s1,s2,n) First n characters of str2 is concatenated at the end of str1
strlen(s1) Returns the length of s1. That is, it returns the number of characters in
the string without the terminating null character.
strcmp(s1,s2) Returns 0 if s1 and s2 are the same
Returns less than 0 if s1<s2
Returns greater than 0 if s1>s2
strncmp(s1,s2,n) Returns 0 if s1 and s2 are the same for first n characters
strcmpi( ) Same as strcmp() function. But, this function negotiates case. “A”
and “a” are treated as same.
strchr(s1,ch) Returns pointer to first occurrence ch in s1
strrchr(s1,ch ) Returns pointer tolast occurrence ch in s1
strstr(s1,s2) Returns pointer to first occurrence s2 in s1
strlen( ) function in C gives the length of the given string
strdup( ) function in C duplicates the given string
strlwr( ) function converts a given string into lowercase
strupr( ) function converts a given string into uppercase
strrev( ) function reverses a given string in C language
strcat ( str1, str2 ) Source string = APPLE strncat ( str1, str2, n ) Source string = APPLEJUICE
#include <stdio.h> Target string = LIME #include <stdio.h> Target string = LIME
#include <string.h> Target string after strcat( ) = #include <string.h> Target string after strcat( ) =
int main( ) LIME APPLE int main( ) LIME APPL
• This conversion facility allows the programmer to specify the set of characters that are (or
are not) acceptable as part of the string.
Program-1 Program-2
#include<stdio.h> #include<stdio.h>
int main() int main()
{ {
char str[50]; char str[50];
printf(“Enter a string in lower case:”); printf(“Enter a string in lower case:”);
scanf(“%[a-z]”,str); scanf(“%[^a-z]”,str);
printf(“The string was : %s\n”,str); printf(“The string was : %s\n”,str);
return 0; return 0;
} }
Output
Output Enter a string in lower case: abcd1234
(a) Enter a string in lower case: hello world The string was : 1234
The string was: hello world
String Array
String Array = {“abc”, ”def”, “ghi”}
char s[5][30];
Initialization
which is equivalent to
Example program : Search a character in a string
#include<stdio.h>
int main() { Enter a string: apple lime juice
char str[20], ch;
Enter the character to be searched : i
int count = 0, i;
printf("\nEnter a string : ");
Character i is present
scanf("%s", &str);
#include <stdio.h>
int main()
{
char s[1000], i;
#include <stdio.h>
int main()
{
char s1[100], s2[100], i;
printf("Enter string s1: ");
scanf("%s",s1);
for(i = 0; s1[i] != '\0'; ++i)
{
s2[i] = s1[i];
}
s2[i] = '\0';
printf("String s2: %s", s2);
return 0;
}
Output
Enter String s1: apple
String s2: apple
program to convert the lower case characters of a string into upper case without using string
functions
#include <stdio.h>
int main()
{ Output
char str[100], upper_str[100]; Enter the string : Hello
The string converted into upper case is : HELLO
int i=0;
clrscr();
printf("\n Enter the string :");
gets(str);
while(str[i] != '\0')
{
if(str[i]>='a' && str[i]<='z')
upper_str[i] = str[i] – 32;
else
upper_str[i] = str[i];
i++;
}
upper_str[i] = '\0';
printf("\n The string converted into upper case is : ");
puts(upper_str);
return 0;
}
program to compare two strings without using string function
#include <stdio.h>
#include <string.h>
int main()
{
char str1[50], str2[50];
int i=0, len1=0, len2=0, same=0;
clrscr();
printf("\n Enter the first string : ");
gets(str1);
printf("\n Enter the second string : ");
gets(str2);
len1 = strlen(str1);
len2 = strlen(str2);
if(len1 == len2)
{
while(i<len1)
{
if(str1[i] == str2[i])
i++;
else break;
}
if(i==len1)
{
same=1;
printf("\n The two strings are equal");
}
}
if(len1!=len2)
printf("\n The two strings are not equal");
if(same == 0)
{
if(str1[i]>str2[i])
printf("\n String 1 is greater than string 2");
else if(str1[i]<str2[i])
printf("\n String 2 is greater than string 1");
}
return 0;
}
Write a program to reverse a given string without using string function
#include <stdio.h>
#include <conio.h>
#include <string.h>
int main() Output
{ Enter the string: Hi there
char str[100], reverse_str[100], temp; The reversed string is: ereht iH
int i=0, j=0;
clrscr();
printf("\n Enter the string : ");
gets(str);
j = strlen(str)–1;
while(i < j)
{
temp = str[j];
str[j] = str[i];
str[i] = temp;
i++;
j––;
}
printf("\n The reversed string is : ");
puts(str);
getch();
return 0;
}
C program to change case from upper to lower and lower to upper without using string function
#include <stdio.h>
int main ()
{ o/p
int i = 0; Input a string
char ch, s[1000]; file ABC
the string is
printf("Input a string\n"); FILEabc
gets(s);
printf("\nBefore Swapping\n");
printf("First string: %s\n", first);
printf("Second string: %s\n\n", second);
strcpy(temp, first);
strcpy(first, second);
strcpy(second, temp);
printf("After Swapping\n");
printf("First string: %s\n", first);
printf("Second string: %s\n", second);
return 0;
}
Write a program to extract a substring from the middle of a given string.
#include <stdio.h>
#include <conio.h>
int main()
{
char str[100], substr[100];
int i=0, j=0, n, m;
clrscr();
printf("\n Enter the main string : ");
gets(str);
printf("\n Enter the position from which to start the substring: ");
scanf("%d", &m);
printf("\n Enter the length of the substring: ");
scanf("%d", &n);
i=m;
while(str[i] != '\0' && n>0)
substr[j] = str[i];
i++;
j++;
n––;
}
substr[j] = '\0';
printf("\n The substring is : ");
puts(substr);
getch();
return 0;
}
Output
Enter the main string : Hi there
Enter the position from which to start the substring: 1
Enter the length of the substring: 4
The substring is : i th
Write a program to insert a string in the main text.
#include <stdio.h>
int main()
{
char text[100], str[20], ins_text[100];
int i=0, j=0, k=0,pos;
clrscr();
printf("\n Enter the main text : ");
gets(text);
printf("\n Enter the string to be inserted : ");
gets(str);
printf("\n Enter the position at which the string has to be inserted: ");
scanf("%d", &pos);
while(text[i]! = '\0')
{
if(i==pos) Output
{ Enter the main text : newsman
while(str[k] != '\0') Enter the string to be inserted : paper
{ Enter the position at which the string has to be
ins_text[j] = str[k]; inserted: 4
j++; The new string is: newspaperman
k++;
}
}
else
{
ins_text[j] = text[i];
j++;
}
i++;
}
ins_text[j] = '\0';
printf("\n The new string is : ");
puts(ins_text);
getch();
return0;
}
Write a program to delete a substring from a text.
#include <stdio.h>
int main()
{
char text[200], str[20], new_text[200]; Output
int i=0, j=0, found=0, k, n=0, copy_loop=0; Enter the main text : Hello, how are you?
clrscr(); Enter the string to be deleted : , how are
printf("\n Enter the main text : "); you?
gets(text); The new string is : Hello
printf("\n Enter the string to be deleted : ");
gets(str);
while(text[i]!='\0')
{
j=0, found=0, k=i;
while(text[k]==str[j] && str[j]!='\0')
{
k++;
j++;
}
if(str[j]=='\0')
copy_loop=k;
new_text[n] = text[copy_loop];
i++;
copy_loop++;
n++;
}
new_str[n]='\0';
printf("\n The new string is : ");
puts(new_str);
return 0;
}
Write a program to replace a pattern with another pattern in the text.
#include
<stdio.h>
#include
<conio.h>
main()
{
char str[200], pat[20], new_str[200],
rep_pat[100]; int i=0, j=0, k, n=0,
copy_loop=0, rep_index=0; clrscr();
printf("\n Enter the
string : "); gets(str);
printf("\n Enter the pattern to be
replaced: "); gets(pat);
printf("\n Enter the replacing
pattern: "); gets(rep_pat);
while(str[i]!='\0')
{
j=0,k=i;
while(str[k]==pat[j] && pat[j]!='\0')
k
+
+
;
j
+
+
;
}
if(pat[j]=='\0')
{
copy_loop=k;
while(rep_pat[rep_index]
!='\0')
{
new_str[n] =
rep_pat[rep_index];
rep_index++;
n++;
}
}
new_str[n] =
str[copy_loop]; i++;
copy
_loo
p++;
n++;
}
new_str[n]='\0';
printf("\n The new string
is : ");puts(new_str);
ge
tc
h(
);
re
tu
rn
0;
}
Output
Enter the string : How ARE you?
Enter the pattern to be
replaced : AREEnter the
replacing pattern : are
The new string is : How are you?
FUNCTION
A function is self contained program segment that carries out some specific,well defined task.
Need For Functions:
Many programs require a set of instructions to be executed repeatedly from several places in a
program, then the repeated code can be placed within a single function, which can be accessed
whenever it is required.
Dividing the program into separate well-defined functions facilitates each function to be written
and tested separately.
Understanding, coding, and testing multiple separate functions is easier than doing the same for one
big function main function.
A big program is broken into comparatively smaller functions.
Advantages of Functions
-Improves readability of code.
-Divides a complex problem into simpler ones
- Improves reuseability of code.
-Debugging errors is easier.
-modifying a program is easier.
Terms
A function f that uses another function g is known as the calling function, and
g is known as the called function.
The inputs that a function takes are known as arguments.
When a called function returns some result back to the calling function, it is
said to return
that result.
The calling function may or may not function,which can theot pass
parameters to the called function.
Function Declaration
Function Definition
Function Call
Function Definition
When a function is defined, space is allocated for that function in the memory. A function
definition comprises of two parts:
Function header
Function body
The syntax of a function definition can be given as:
void sum(int a,int b) int sum(int a,int b) Note that the number of
{ { arguments and the order of
Int c; Int c; arguments in the function
c=a+b; c=a+b; header must be
return(c); return(c); the same as that given in the
} } function declaration
statement.
Function Call
The function call statement invokes the function. When a function is invoked, the compiler
jumps to the called function to execute the statements that are a part of that function. Once
the called function is executed, the program control passes back to the calling function. A
function call statement has the following
Syntax-1:
function_name(variable1, variable2, ...);
If the return type of the function is not void then the following syntax can be used.
Syntax-2
Function Declaration
It is also called as function prototype. A function prototype consists of 4 parts
(1) Return type
(2) function name
(3) parameter list
(4) terminating (;) semicolin
data_type function_name(data_type1 variable1, ...,data_type n variable n);
A function prototype tells the compiler that the function may later be used in the
program. The function prototype is not needed if function is placed before
main function code.
Example program
#include <stdio.h>
void sum(int a ,int b); //FUNCTION DECLARATION
int main()
{ int a,b; o/p
scanf(“%d%d”,&a,&b); //get input values for a and b 2
sum(a,b); //FUNCTION CALL 3
} c=5
void sum(int x,int y) // FUNCTION DEFINITION
{
int c;
c=x+y;
printf(“c=%d”,c);
}
void data type indicates that the function is returning nothing .(i.e) if the function is not returning
anything then its datatype is as specified as void.
Example program without function prototype(function
declaration)
#include <stdio.h>
void sum(int x,int y) // FUNCTION DEFINITION o/p
{ int c; 2
c=x+y; 3
printf(“c=%d”,c); c=5
}
int main()
{ int a,b;
scanf(“%d%d”,&a,&b); //get input values for a and b
sum(a,b); //FUNCTION CALL
}
Eg-Write a program to find whether a number is even or odd using functions.
#include <stdio.h>
int evenodd(int); //FUNCTION DECLARATION
int main()
{
int num, flag;
printf("\n Enter the number : ");
scanf("%d", &num); Output
flag = evenodd(num); //FUNCTION CALL Enter the number : 78
if (flag == 1) 78 is EVEN
printf("\n %d is EVEN", num);
else
printf("\n %d is ODD", num);
return 0;
}
int evenodd(int a) // FUNCTION DEFINITION
{
if(a%2 == 0)
return 1;
else
retun 0;
TYPES OF FUNCTION IMPLEMENTATION
}
Not passing Not passing arguments passing arguments & passing arguments &
arguments & not & returning some value not returning returning some value
returning anything anything
CASE-1 NOT PASSING ARGUMENTS & NOT RETURNING SOME VALUE
#include <stdio.h>
int sum( ); //FUNCTION DECLARATION
int main( )
{ o/p
sum( ); //FUNCTION CALL 2
} 3
int sum( ) // FUNCTION DEFINITION c=5
{
int a,b,c;
scanf(“%d%d”,&a,&b); // get input values for a and b
c=x+y;
printf(“c=%d”,c);
}
CASE-2 NOT PASSING ARGUMENTS & RETURNING SOME VALUE
#include <stdio.h>
int sum( ); //FUNCTION DECLARATION o/p
int main( ) 2
{ sum( ); //FUNCTION CALL 3
printf(“c=%d”,c); c=5
}
int sum( ) // FUNCTION DEFINITION
{
int a,b,c;
scanf(“%d%d”,&a,&b); // get input values for a and b
c=x+y;
return c;
}
CASE-3 PASSING ARGUMENTS & NOT RETURNING ANYTHING
#include <stdio.h>
int sum( int a,int b); //FUNCTION DECLARATION o/p
int main( ) 2
{ int a,b; 3
scanf(“%d%d”,&a,&b); // get input values for a and b c=5
sum(int a,int b ); //FUNCTION CALL
}
int sum( int x,int y) // FUNCTION DEFINITION
{
int c;
c=x+y;
printf(“c=%d”,c);
}
CASE-4 NOT PASSING ARGUMENTS & RETURNING SOME VALUE
#include <stdio.h>
int sum( int a,int b); //FUNCTION DECLARATION o/p
int main( ) 2
{ int a,b,c; 3
scanf(“%d%d”,&a,&b); // get input values for a and b c=5
c=sum(int a,int b ); //FUNCTION CALL
printf(“c=%d”,c);
return 0;
}
int sum( int x,int y) // FUNCTION DEFINITION
{ int result
result=x+y;
return result; }
PASSING ARGUMENTS(PARAMETERS) TO FUNCTION
In programming function argument is commonly referred as actual parameter and function
parameter is referred as formal parameter.
Call by value
In Call by value, during function call actual parameter value is copied and
passed to formal parameter. Changes made to the formal parameters does not
affect the actual parameter.
Eg Program - C program to swap two numbers using call by value
#include<stdio.h>
int main()
{
int n1, n2;
printf("Enter two numbers: ");
scanf("%d%d", &n1, &n2);
printf("In Main values before swapping: %d %d\n\n", n1, n2);
swap(n1, n2);
printf("In Main values after swapping: %d %d", n1, n2);
return 0;
}
void swap(int num1, int num2)
{
int temp;
printf("In Function values before swapping: %d %d\n", num1, num2);
temp = num1;
num1 = num2;
num2 = temp;
printf("In Function values after swapping: %d %d\n\n", num1, num2);
}
Output -
Enter two numbers: 10 20
In Main values before swapping: 10 20
In Function values before swapping: 10 20
In Function values after swapping: 20 10
In Main values after swapping: 10 20
NOTE : In the above program swap() function does not alter actual parameter value. Before
passing the value of n1 and n2 to the swap() function, the C runtime copies the value of
actual parameter n1 and n2 to a temporary variable and passes copy of actual parameter.
Therefore inside the swap() function values has been swapped, however original value of n1
and n2 in main() function remains unchanged.
Call by reference
#include <stdio.h>
int main()
{ int n1, n2;
printf("Enter two numbers: ");
scanf("%d%d", &n1, &n2);
printf("In Main values before swapping: %d %d\n\n", n1, n2);
swap(&n1, &n2);
printf("In Main values after swapping: %d %d", n1, n2);
return 0;
}
void swap(int * num1, int * num2)
{
int temp;
printf("In Function values before swapping: %d %d\n", *num1, *num2);
temp = *num1;
*num1 = *num2;
*num2 = temp;
printf("In Function values after swapping: %d %d\n\n", *num1, *num2);
}
Output :-
Enter two numbers: 10 20
In Main values before swapping: 10 20
In Function values before swapping: 10 20
In Function values after swapping: 20 10
In Main values after swapping: 20 10
In above example instead of passing a copy of n1 and n2, to swap() function. Operations
performed on formal parameter is reflected to actual parameter (original value). Hence, actual
swapping is performed inside swap() as well as main() function.
WRITE THESE SWAP PROGRAM(S) FOR YOUR EXAMS
Call by value
#include<stdio.h>
Void swap(int x,int y);
int main( ) Before swapping x and y
{ 10 20
int a = 10, b = 20 ; After swapping x and y
swap (a,b) ; // calling by value 20 10
printf ( "\n Before swapping x and y) ;
printf ( "\na = %d b = %d", a, b ) ;
return 0;
}
void swap( int x, int y )
{
int t ;
t=x;
x=y;
y=t ;
printf ( "\n After swapping x and y) ;
printf( "\nx = %d y = %d", *x,*y);
}
Call by reference
#include<stdio.h>
Before swapping x and y
Void swap(int *x,int *y); 10 20
int main( ) After swapping x and y
{ 20 10
int a = 10, b = 20 ;
swap ( &a, &b ) ; // calling by reference
printf ( "\n Before swapping x and y) ;
printf ( "\na = %d b = %d", a, b ) ;
return 0;
}
void swap( int *x, int *y )
{
int t ;
t = *x ;
*x = *y ;
*y = t ;
printf ( "\n After swapping x and y) ;
printf( "\nx = %d y = %d", *x,*y);
}
Call by value Call by reference
When a function is called the actual values are When a function is called the address of
passed values(arguments) are passed
The parameters passed are normal variables The parameters passed are pointer variables
In call by value, actual arguments cannot be Modification to actual arguments is possible
modified. within from called function.
Actual arguments remain preserved and no Actual arguments will not be preserved.
chance of modification accidentally.
Calling Parameters: swap(a,b) Calling Parameters: swap(&a,&b)
Receiving parameters: void swap( int x, int y ) Receiving parameters: void swap( int *x, int *y )
PASSING ARRAYS TO A FUNCTION
Advantage of Recursion
Disadvantage of Recursion
It is a very slow process due to stack overlapping.
Recursive programs can create stack overflow.
Recursive functions can create as loops.
Example: Sum of Natural Numbers Using Recursion
#include <stdio.h>
int sum(int n);
int main()
{
int number, result;
printf("Enter a positive integer: ");
scanf("%d", &number);
result = sum(number);
printf("sum=%d", result);
}
int sum(int num)
{
if (num!=0)
return num + sum(num-1); // sum() function calls itself
else
return num;
}
Output
Enter a positive integer:3
6
FACTORIAL OF A NUMBER USING RECURSIVE FUNCTION
#include <stdio.h>
int factorial( int ) ;
void main( )
{
int fact, n ; Enter any positive integer: 3
printf(“Enter any positive integer: ”) ; Factorial of 3 is 6
scanf(“%d”, &n) ;
fact = factorial( n ) ;
printf(“Factorial of %d is %d”, n, fact) ;
}
int factorial( int n )
{
int temp ;
if( n == o)
return 1 ;
else
temp = n * factorial( n-1 ) ; // recursive function call
return temp ;
}
3*2 =6
2*1=2
1 * 1=1
Returns 1 as n value is 0
TOWER OF HANOI OF A NUMBER USING RECURSIVE FUNCTION
#include <stdio.h>
void hanoi(int n, char from, char to, char temp)
{
if (n == 1)
{
printf("\n Move Disk 1 from Peg %c to %c", from, to);
return;
}
hanoi(n-1, from, temp, to);
printf("\n Move disk %d from rod %c to rod %c",
n, fr, tr); hanoi(n-1, temp, to, from);
}
int main()
{
Printf(“ Towers of
Honoi”); int n;
printf(“\n Enter number of Disks”);
scanf(” %d ”,&n); // n implies the number of discs
hanoifun(n, 'A', 'C', 'B'); // A, B and C are the
name of Peg return 0;
}
To Transfer from disks from peg A to C taking help of B
Output
Move Disk 1 from Peg 1 to Peg 3.
Move Disk 2 from Peg 1 to Peg 2.
Move Disk 1 from Peg 3 to Peg 2.
Move Disk 3 from Peg 1 to Peg 3.
Move Disk 1 from Peg 2 to Peg 1.
Move Disk 2 from Peg 2 to Peg 3.
Move Disk 1 from Peg 1 to Peg 3.
Example: GCD of Two Numbers using Recursion
#include <stdio.h>
int hcf(int n1, int n2);
int main()
{
int n1, n2;
printf("Enter two positive integers: ");
scanf("%d %d", &n1, &n2);
Note :Here %u is a format specifier. It stands for unsigned, so it will only display positive values.
&-address of operator.
& is the “address of” operator. It is used to tell the C compiler to refer to the address of variables.
Address of any variable can’t be negative. This is the reason %u format specifier is used to print the
address of variables on the screen.
This is the second operator used for pointers. It is used to access the value present at some
address. And it is used to declare a pointer.
int x=10;
int *ptr; // Declaration of Pointer variable
ptr=&x; // Storing address of x variable in y pointer variable
Example program-1
#include<stdio.h>
void main()
{ 6 12
65524 65522
int a=6,b=12; 65524 65522
int *x,*y; 6 12
x=&a; 65524 65522
y=&b; 6 12
printf("%d t %d n",a,b);
printf("%u t %u n",&a,&b);
printf("%u t %u n",x,y);
printf("%d t %d n",*x,*y);
printf("%d t %d",(&a),(&b));
printf("%d t %d",*(&a),*(&b));
}
#include <stdio.h>
int main ()
{
int var = 20; /* actual variable declaration */
int *ip; /* pointer variable declaration */
ip = &var; /* store address of var in pointer variable*/
printf("Address of var variable: %x\n", &var );
/*address stored in pointer variable*/
printf("Address stored in ip variable: %x\n", ip );
/*access the value using the pointer */
printf("Value of *ip variable: %d\n", *ip );
return 0;
}
syntax
type *var-name;
Here, type is the pointer's base type; it must be a valid C data type and var-
name is the name of the pointer variable.
#include <stdio.h>
int main ()
{
int *ptr = NULL;
printf("The value of ptr is : %x\n", ptr);
return 0;
}
output
The value of ptr is 0
Incrementing a Pointer(32-bit )
#include <stdio.h>
const int MAX = 3;
int main () {
int var[] = {10, 100, 200};
int i, *ptr;
/* let us have array address in pointer */
ptr = var;
for ( i = 0; i < MAX; i++) {
printf("Address of var[%d] = %x\n", i, ptr );
printf("Value of var[%d] = %d\n", i, *ptr );
/* move to the next location */
ptr++;
}
return 0;
}
output
Address of var[0] = bf882b30
Value of var[0] = 10
Address of var[1] = bf882b34
Value of var[1] = 100
Address of var[2] = bf882b38
Value of var[2] = 200
Decrementing a Pointer(32-bit machine)
decreases its value by the number of bytes of its data type.
#include <stdio.h>
const int MAX = 3;
int main () {
int var[] = {10, 100, 200};
int i, *ptr;
/* let us have array address in pointer */
ptr = &var[MAX-1];
for ( i = MAX; i > 0; i--) {
printf("Address of var[%d] = %x\n", i-1, ptr );
printf("Value of var[%d] = %d\n", i-1, *ptr );
/* move to the previous location */
ptr--;
}
return 0;
}
output
Address of var[2] = bfedbcd8
Value of var[2] = 200
Address of var[1] = bfedbcd4
Value of var[1] = 100
Address of var[0] = bfedbcd0
Value of var[0] = 10
val = *p1+*p2;
printf("*p1+*p2 = %d\n", val);//point 1
p3 = p1-p2;
printf("p1 - p2 = %d\n", p3); //point 2
p1++;
printf("p1++ = %d\n", p1); //point 3
p2--;
printf("p2-- = %d\n", p2); //point 4
return 0;
}
OUTPUT
p1 = 2680016
p2 = 2680012
*p1=5;
*p2=10;
*p1+*p2 = 15
p1-p2 = 1
p1++ = 2680020
p2-- = 2680008