CPDS Unit 2
CPDS Unit 2
Advantags
Function Aspects
Types of Functions
Return Value
A function may or may not return a value from the function. If you don't
have to return any value from the function, use void for the return type.
Let's see a simple example of C function that doesn't return any value from the
function.
• If you want to return any value from the function, you need to use any
data type such as int, long, char, etc.
• The return type depends on the value to be returned from the function.
Let's see a simple example of C function that returns int value from the
function.
int get()
{
return 10;
}
float get()
{
return 10.2;
}
Now, you need to call the function, to get the value of the function.
Example :
#include<stdio.h>
void printName(); //Function declaration
void main ()
{
printf("Hello ");
printName(); //Function call
}
void printName() //Function Defination
{
printf("SIDDARTHA");
}
Example :
#include<stdio.h>
void sum();
void main()
{
printf("\ Calculate the sum of two numbers:");
sum();
}
void sum()
{
int a,b;
printf("\nEnter two numbers");
scanf("%d %d",&a,&b);
printf("The sum is %d",a+b);
}
Output:
Calculate the sum of two numbers:
Enter two numbers10
20
The sum is 30
Example:
#include<stdio.h>
int sum();
void main()
{
int result;
printf("\n Calculate the sum of two numbers:");
result = sum();
printf("%d",result);
}
int sum()
{
int a,b;
printf("\nEnter two numbers");
scanf("%d %d",&a,&b);
return a+b;
}
Output:
#include<stdio.h>
int square();
void main()
{
printf("Calculate the area of the square\n");
float area = square();
printf("The area of the square: %f\n",area);
}
int square()
{
float side;
printf("Enter the length of the side in meters: ");
scanf("%f",&side);
return side * side;
}
Output:
Example:
#include<stdio.h>
void sum(int, int);
void main()
{
int a,b,result;
printf("\n Calculate the sum of two numbers:");
printf("\nEnter two numbers:");
scanf("%d %d",&a,&b);
sum(a,b);
}
void sum(int a, int b)
{
printf("\nThe sum is %d",a+b);
}
Output:
#include<stdio.h>
void average(int, int, int, int, int);
void main()
{
int a,b,c,d,e;
printf("\n Calculate the average of five numbers:");
printf("\nEnter five numbers:");
scanf("%d %d %d %d %d",&a,&b,&c,&d,&e);
average(a,b,c,d,e);
}
void average(int a, int b, int c, int d, int e)
{
float avg;
avg = (a+b+c+d+e)/5;
printf("The average of given five numbers : %f",avg);
}
Output:
Example :
#include<stdio.h>
int sum(int, int);
void main()
{
int a,b,result;
printf("\n Calculate the sum of two numbers:");
printf("\nEnter two numbers:");
scanf("%d %d",&a,&b);
result = sum(a,b);
printf("\nThe sum is : %d",result);
}
int sum(int a, int b)
{
return a+b;
}
Output:
#include<stdio.h>
int even_odd(int);
void main()
{
int n,flag=0;
printf("\n To check whether a number is even or odd");
printf("\nEnter the number: ");
scanf("%d",&n);
flag = even_odd(n);
if(flag == 0)
{
printf("\nThe number is odd");
}
else
{
printf("\nThe number is even");
}
}
int even_odd(int n)
{
if(n%2 == 0)
{
return 1;
}
else
{
return 0;
}
}
SCOPE OF A VARIABLE
A scope in any programming is a region of the program where a defined variable
can have its existence and beyond that variable it cannot be accessed. There are
three places where variables can be declared in C programming language −
• Inside a function or a block which is called local variables.
• Outside of all functions which is called global variables.
• In the definition of function parameters which are
called formal parameters.
Let us understand what are local and global variables, and formal parameters.
Local Variables
Variables that are declared inside a function or block are called local variables.
They can be used only by statements that are inside that function or block of
code. Here all the variables a, b, and c are local to main() function.
#include <stdio.h>
int main ()
{
/* local variable declaration */
int a, b;
int c;
/* actual initialization */
a = 10;
b = 20;
c = a + b;
printf ("value of a = %d, b = %d and c = %d\n", a, b, c);
return 0;
}
Output: value of a = 10, b = 20 and c = 30
Global Variables
Global variables are defined outside a function, usually on top of the program.
Global variables hold their values throughout the lifetime of your program and
they can be accessed inside any of the functions defined for the program.
A global variable can be accessed by any function. That is, a global variable is
available for use throughout your entire program after its declaration. The
following program show how global variables are used in a program.
#include <stdio.h>
/* global variable declaration */
int g;
int main ()
{
/* local variable declaration */
int a, b;
/* actual initialization */
a = 10;
b = 20;
g = a + b;
printf ("value of a = %d, b = %d and g = %d\n", a, b, g);
return 0;
}
Output: value of a = 10, b = 20 and g = 30
Formal Parameters/arguments
Formal parameters, are treated as local variables with-in a function and they
take precedence over global variables.
Following is an example −
#include <stdio.h>
/* global variable declaration */
int a = 20;
int main () {
/* local variable declaration in main function */
int a = 10;
int b = 20;
int c = 0;
printf ("value of a in main() = %d\n", a);
c = sum( a, b);
printf ("value of c in main() = %d\n", c);
return 0;
}
/* function to add two integers */
int sum(int a, int b) {
printf ("value of a in sum() = %d\n", a);
printf ("value of b in sum() = %d\n", b);
return a + b;
}
Output:
value of a in main() = 10
value of a in sum() = 10
value of b in sum() = 20
value of c in main() = 30
RECURSION IN C
Recursion is the process of repeating items in a self-similar way. In
programming languages, if a program allows you to call a function inside the
same function, then it is called a recursive call of the function.
void recursion()
{
recursion(); /* function calls itself */
}
int main() {
recursion();
}
The C programming language supports recursion, i.e., a function to call
itself. But while using recursion, programmers need to be careful to define an
exit condition from the function, otherwise it will go into an infinite loop.
#include <stdio.h>
int fibonacci(int i)
{
if(i == 0)
{
return 0;
}
if(i == 1)
{
return 1;
}
return fibonacci(i-1) + fibonacci(i-2);
}
int main()
{
int i;
for (i = 0; i < 10; i++)
{
printf("%d\t\n", fibonacci(i));
}
return 0;
}
Output:
0
1
1
2
3
5
8
13
21
34
Structures
➢ Structure is a user-defined data type
➢ A structure is a collection of one are more variables of different data
types groped under a single name.
➢ Each element of a structure is called a member.
➢ The struct keyword is used to define the structure.
struct structure_name
{
data_type member1;
data_type member2;
…………………………….
data_type memeberN;
};
struct employee
{
int id;
char name[10];
float salary;
};
The following image shows the memory allocation of the structure employee
that is defined in the above example.
Here, struct is the keyword; employee is the name of the structure; id, name,
and salary are the members or fields of the structure. Let's understand it by the
diagram given below:
We can declare a variable for the structure so that we can access the member
of the structure easily. There are two ways to declare structure variable:
1st way:
Let's see the example to declare the structure variable by struct keyword. It
should be declared within the main function.
struct employee
{
int id;
char name[50];
float salary;
}; struct employee e1, e2;
The variables e1 and e2 can be used to access the values stored in the
structure.
2nd way:
Let's see another way to declare variable at the time of defining the structure.
struct employee
{ int id;
char name[50];
float salary;
}e1,e2;
If number of variables are not fixed, use the 1st approach. It provides you the
flexibility to declare the structure variable many times.
If no. of variables are fixed, use 2nd approach. It saves your code to declare a
variable in main() function.
Example:
#include<stdio.h>
#include <string.h>
struct employee
{
int id;
char name[50];
}e1; //declaring e1 variable for structure
int main( )
{
//store first employee information
e1.id=101;
strcpy(e1.name, "Siddartha");//copying string into char array
//printing first employee information
printf( "employee 1 id : %d\n", e1.id);
printf( "employee 1 name : %s\n", e1.name);
return 0;
}
Output:
employee 1 id : 101
employee 1 name : Siddartha
#include<stdio.h>
#include <string.h>
struct employee
{ int id;
char name[50];
float salary;
}e1,e2; //declaring e1 and e2 variables for structure
int main( )
{
//store first employee information
e1.id=101;
strcpy(e1.name, "abcde");//copying string into char array
e1.salary=56000;
Output:
employee 1 id : 101
employee 1 name : abcde
employee 1 salary : 56000.000000
employee 2 id : 102
employee 2 name : xyz
employee 2 salary : 126000.000000
Example:
#include <stdio.h>
#include <string.h>
struct Books
{
char title[50];
char author[50];
char subject[100];
int book_id;
};
int main( )
{
struct Books Book1; /* Declare Book1 of type Book */
struct Books Book2; /* Declare Book2 of type Book */
/* book 1 specification */
strcpy( Book1.title, "C Programming");
strcpy( Book1.author, "ant");
strcpy( Book1.subject, "C Programming Tutorial");
Book1.book_id = 6495407;
/* book 2 specification */
strcpy( Book2.title, "Telecom Billing");
strcpy( Book2.author, "abc");
strcpy( Book2.subject, "Telecom Billing Tutorial");
Book2.book_id = 6495700;
/* print Book1 info */
printf( "Book 1 title : %s\n", Book1.title);
printf( "Book 1 author : %s\n", Book1.author);
printf( "Book 1 subject : %s\n", Book1.subject);
printf( "Book 1 book_id : %d\n", Book1.book_id);
/* print Book2 info */
printf( "Book 2 title : %s\n", Book2.title);
printf( "Book 2 author : %s\n", Book2.author);
printf( "Book 2 subject : %s\n", Book2.subject);
printf( "Book 2 book_id : %d\n", Book2.book_id);
return 0;
}
Output:
Book 1 title : C Programming
Book 1 author : ant
Book 1 subject : C Programming Tutorial
Book 1 book_id : 6495407
Book 2 title : Telecom Billing
Book 2 author : abc
Book 2 subject : Telecom Billing Tutorial
Book 2 book_id : 6495700
Unions
➢ Unions are conceptually similar to structures.
➢ A Union is a collection of one are more variables of different data types
groped under a single name.
➢ The syntax to declare/define a union is also similar to that of a structure.
➢ The only differences is in terms of storage.
➢ In structure each member has its own storage location, whereas all
members of union uses a single shared memory location which is equal to
the size of its largest data member.
Example:
#include <stdio.h>
union unionJob
{
//defining a union
char name[32];
float salary;
int workerNo;
} uJob;
struct structJob
{
char name[32];
float salary;
int workerNo;
} sJob;
int main()
{
printf("size of union = %d bytes", sizeof(uJob));
printf("\nsize of structure = %d bytes", sizeof(sJob));
return 0;
}
Output:
size of union = 32 bytes
size of structure = 40 bytes
Pointers
➢ A pointer is a variable which stores the address of another variable.
➢ This variable can be of any type i.e. int, char, float…etc
➢ The size of the pointer depends on the architecture.
➢ However, in 32-bit architecture the size of a pointer is 2 byte.
There are a few important operations, which we will do with the help of pointers
very frequently.
(a) We define a pointer variable,
(b) assign the address of a variable to a pointer and
(c) finally access the value at the address available in the pointer variable.
This is done by using unary operator * that returns the value of the variable
located at the address specified by its operand.
int v=0;
However, each variable, apart from value, also has its address (or, simply put,
where it is located in the memory).
The address can be retrieved by putting an ampersand (&) before the variable
name.
&V
If you print the address of a variable on the screen, it will look like a totally
random number (moreover, it can be different from run to run).
Example:
#include <stdio.h>
int main()
{
int v=0;
printf("\n value of v variable v=%d",v);
printf("\n Address of v variable v=%d",&v);
return 0;
}
Output:
value of v variable v=0
Address of v variable v=1032003860
Declaring a pointer
Example:
#include <stdio.h>
int main ()
{
int v = 20; /* actual variable declaration */
int *a; /* pointer variable declaration */
a = &v; /* store address of v in pointer variable*/
printf("\n value of v variable: %d\n", v );
printf("Address of v variable: %d\n", &v );
/* address stored in pointer variable */
printf("\n value of a variable: %d\n", a );
/* access the value using the pointer */
printf("Address of a variable: %d\n", &a );
printf("Value of *a variable: %d\n", *a );
return 0;
}
Output:
value of v variable: 20
Address of v variable: 1569213420
value of a variable: 1569213420
Address of a variable: 1569213424
Value of *a variable: 20
Types of Pointers in C
Null Pointer
➢ We can create a null pointer by assigning null value during the pointer
declaration.
➢ This method is useful when you do not have any address assigned to the
pointer.
➢ A null pointer always contains value 0.
o Increment
o Decrement
o Addition
o Subtraction
Incrementing Pointer
Decrementing
#include <stdio.h>
void main()
{
int number=50;
int *p;//pointer to int
p=&number;//stores the address of number variable
printf("Address of p variable is %u \n",p);
p=--p;
printf("After decrement: Address of p variable is %u \n",p); // P will now point to
the immidiate previous location.
}
Output:
Address of p variable is 1783011372
After decrement: Address of p variable is 1783011368
Example: Subtraction
#include <stdio.h>
void main()
{
int number=50;
int *p;//pointer to int
p=&number;//stores the address of number variable
printf("Address of p variable is %u \n",p);
p=p-1;
printf("After Substraction: Address of p variable is %u \n",p); // P will now point
to the immidiate previous location.
}
Output
Address of p variable is 2924723068
After Substraction: Address of p variable is 2924723064
Pointer to Pointer
➢ A pointer to a pointer is a form of multiple indirection, or a chain of
pointers.
➢ Normally, a pointer contains the address of a variable.
➢ When we define a pointer to a pointer, the first pointer contains the
address of the second pointer, which points to the location that contains
the actual value as shown below.
The code of a function always resides in memory, which means that the
function has some address. We can get the address of memory by using the
function pointer.
Example:
#include<stdio.h>
void swap (int *a, int *b);
int main()
{
int m = 25;
int n = 100;
printf("m is %d, n is %d\n", m, n);
swap(&m, &n);
printf("m is %d, n is %d\n", m, n);
return 0;
}
void swap (int *a, int *b)
{
int temp;
temp = *a;
*a = *b;
*b = temp;
}
Output:
m is 25, n is 100
m is 100, n is 25
Pointers to Structures
We can define pointers to structures in the same way as you define pointer to
any other variable
struct Books *struct_pointer;
To access members of a structure using pointers, we use the -> operator.
Example:
#include <stdio.h>
struct person
{
int age;
float weight;
};
int main()
{
struct person *personPtr, person1;
personPtr = &person1;
printf("Enter age: ");
scanf("%d", &personPtr->age);
printf("Enter weight: ");
scanf("%f", &personPtr->weight);
printf("Displaying:\n");
printf("Age: %d\n", personPtr->age);
printf("weight: %f", personPtr->weight);
return 0;
}
Output:
Enter age: 36
Enter weight: 36
Displaying:
Age: 36
weight: 36.000000
Storage Classes
Storage classes are used to determine the lifetime, visibility, memory
location, and initial value of a variable.
o Automatic
o External
o Static
o Register
extern RAM Zero Global Till the end of the main program Maybe
declared anywhere in the program
static RAM Zero Local Till the end of the main program,Retains
between multiple functions call
➢ The variables defined using auto storage class are called as local
variables.
➢ Auto stands for automatic storage class.
➢ A variable is in auto storage class by default if it is not explicitly specified.
➢ The scope of an auto variable is limited with the particular block only.
➢ Once the control goes out of the block, the access is destroyed.
➢ This means only the block in which the auto variable is declared can
access it.
➢ A keyword auto is used to define an auto storage class.
➢ By default, an auto variable contains a garbage value.
Example:
#include <stdio.h>
int main()
{
auto int a; //auto
char b;
float c;
printf("a=%d \t b=%c \t c=%f",a,b,c);
return 0;
}
Output: a=0 b=. c=0.000000
Example:
#include <stdio.h>
extern int i;
int main()
{
printf("value of the external integer is = %d\n", i);
return 0;
}
Output:
/usr/bin/ld: cannot open output file a.out: Permission denied
collect2: error: ld returned 1 exit status
Example:
#include <stdio.h>
extern int i=9;
int main()
{
printf("value of the external integer is = %d\n", i);
return 0;
}
Output: value of the external integer is = 9
➢ Static variables are visible only to the function or the block in which they
are defined.
➢ A same static variable can be declared many times but can be assigned at
only one time.
➢ Default initial value of the static integral variable is 0 otherwise null.
➢ The visibility of the static variable is limited to the file in which it has
declared.
➢ The keyword used to define static variable is static.
Example:
#include<stdio.h>
static char c;
static int i;
static float f;
static char s[100];
void main ()
{
printf("%d %d %f %s",c,i,f,s);
}
Output: 0 0 0.000000
Example:
#include <stdio.h>
int main()
{
register int a;
printf("%d",a);
}
Output: 1059242368
Type qualifiers
Type qualifiers add special attributes to the existing datatypes.
There are three type qualifiers in C language there are Const, volatile and Restrict
Const
There are three types of constants, which are as follows −
• Literal constants
• Defined constants
• Memory constants
Literal constants: These are the unnamed constants that are used as
Example: a=b+7 //Here ‘7’ is literal constant.
Defined constants: These constants use the preprocessor command ‘define"
with #
Example: #define PI 3.1415
Memory constants : These constants use ‘C’ qualifier ‘const’, which indicates that
the data cannot be changed.
Example: const float pi = 3.1415
Example:
#include<stdio.h>
#define PI 3.1415
int main ( )
{
const float cpi = 3.14;
printf ("literal constant = %f",3.14);
printf ("\n defined constant = %f", PI);
printf ("\n memory constant = %f",cpi);
}
Output:
literal constant = 3.140000
defined constant = 3.141500
memory constant = 3.140000
Volatile
Example:
#include<stdio.h>
volatile int a ;
int main()
{
a=0;
if (a == 0)
{
printf ( " a = 0 \n " ) ;
}
else
{
printf ( " a ! = 0 \n " ) ;
}
return 0 ;
}
Output: a = 0
Restrict
Jumping Statements
Jump Statements in C
Jumping statements are used to interrupt the normal flow of program.
• Break
• Continue
• GoTo
Break Statement
The goto statement is a jump statement which jumps from one point to
another point within a function.
Example:
#include<stdio.h>
void main()
{
printf("\nStatement 1.");
printf("\nStatement 2.");
printf("\nStatement 3.");
goto last;
printf("\nStatement 4.");
printf("\nStatement 5.");
last:
printf("\nEnd of Program.");
}
Output:
Statement 1.
Statement 2.
Statement 3.
End of Program.
Example:
#include <stdio.h>
void main(int argc, char *argv[] )
{
printf("Program name is: %s\n", argv[0]);
if(argc < 2)
{
printf("No argument passed through command line.\n");
}
else
{
printf("First argument is: %s\n", argv[1]);
}
}
Output:
Program name is: /tmp/N4r8W0ynUH.o
No argument passed through command line.