0% found this document useful (0 votes)
32 views159 pages

C Important Notes

Uploaded by

hitepi6086
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
32 views159 pages

C Important Notes

Uploaded by

hitepi6086
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 159

• Storage Classes-

• Scope
• Block
• Function
• Program
• Life time of variables.
• Every variable in C programming has two properties: type and storage
class.
• Type refers to the data type of a variable. And, storage class
determines the scope, visibility and lifetime of a variable.
• There are 4 types of storage class:
• automatic
• external
• static
• register
Local Variable
• The variables declared inside a block are automatic or local variables. The local
variables exist only inside the block in which it is declared.
#include <stdio.h>

int main() {

for (int i = 0; i < 5; i++) {


printf("C programming");
}

// Error: i is not declared at this point


printf("%d", i);
return 0;
}
• When you run the above program, you will get an error undeclared
identifier i. It's because i is declared inside the for loop block. Outside
of the block, it's undeclared.
Global Variable

• Variables that are declared outside of all functions are known as


global variables. They are accessible from any function inside the
program.
Example 1: Global Variable
#include <stdio.h>
void display();
int n = 5; // global variable
int main()
{
++n;
display();
return 0;
}
void display()
{
++n;
printf("n = %d", n);
}
Output
n=7
Extern example
#include <stdio.h>
int main() {
extern int x;
printf("The value of auto variable : %d", x);
return 0;
}
int x=10;
Difference from previous example??
#include <stdio.h>
int main() {
//int x;
printf("The value of auto variable : %d", x);
return 0;
}
int x=10;
Output- Error
Static Variable

• A static variable is declared by using the static keyword.


• The value of a static variable persists until the end of the program.
• Initialization happens only once and the value of the static variable
will be retained.
Example 2: Static Variable
#include <stdio.h>
void display();
int main()
{
display();
display();
}
void display()
{
static int c = 1;
c += 5;
printf("%d ",c);
}
Output

6 11
• During the first function call, the value of c is initialized to 1. Its value
is increased by 5. Now, the value of c is 6, which is printed on the
screen.

• During the second function call, c is not initialized to 1 again. It's


because c is a static variable. The value c is increased by 5. Now, its
value will be 11, which is printed on the screen.
Register Variable

• The register keyword is used to declare register variables. Register


variables were supposed to be faster than local variables.

• However, modern compilers are very good at code optimization, and


there is a rare chance that using register variables will make your
program faster.
Function Exercises
• WAP in C to perform arithmetic operations using function
• WAP in C to find the square of any number using function
• WAP in C to find the number is even or odd using function
• Declaration and Access of pointer Variables,
• Pointer arithmetic-
• Pointers and arrays –
• Pointers (pointer variables) are special variables that are used to store
addresses rather than values.
• Pointer Syntax
• Here is how we can declare pointers.

• int *p;
• Here, we have declared a pointer p of int type.
Assigning addresses to Pointers

• Let's take an example.

int *pc, c;
c = 5;
pc = &c;
• Here, 5 is assigned to the c variable. And, the address of c is assigned
to the pc pointer.
Get Value of Thing Pointed by Pointers
• To get the value of the thing pointed by the pointers, we use the *
operator. For example:

• int *pc, c;
• c = 5;
• pc = &c;
• printf("%d", *pc); // Output: 5
• Here, the address of c is assigned to the pc pointer. To get the value
stored in that address, we used *pc.
• By the way, * is called the dereference operator (when working with
pointers). It operates on a pointer and gives the value stored in that
pointer.
Changing Value Pointed by Pointers
• Let's take an example.

int* pc, c;
c = 5;
pc = &c;
c = 1;
printf("%d", c); // Output: 1
printf("%d", *pc); // Ouptut: 1
• We have assigned the address of c to the pc pointer.

• Then, we changed the value of c to 1. Since pc and the address of c is the


same, *pc gives us 1.
#include <stdio.h>
int main()
{
int *pc, c;
c = 22;
printf("Address of c: %d\n", &c);
printf("Value of c: %d\n\n", c); // 22
pc = &c;
printf(“value of pointer pc: %d\n", pc);
printf("Content of the address pointed by pointer pc: %d\n\n", *pc); // 22
return 0;
}
• Pointer variables always point to the corresponding type of data
• float a,b;
• int x, *p;
• p=&a; //wrong

• Because, try to assign address of float variable to an integer pointer


• It is possible to combine the declaration of data variable, declaration of
pointer variable and initialization of pointer variable.
• Eg-
• int x, *p=&x;
Pointer Expressions
• Like other variables, pointer variables can be used in expressions
• If p1 and p2 are properly declared and initialized, the following
statements are valid.
• y=*p1 * *p2;
• sum=sum+ *p1;
• z=(*p2)/ (*p1)
• *p2=*p2+10;
Pointer Arithmetic
Example
#include <stdio.h>
int main()
{
int *p1, *p2,*p3,c,d;
c = 22,d=10;
p1 = &c;
p2=&d;
printf("Address of c: %d\n", &c);
printf("Address of c: %d\n", p1);
printf("Value of c: %d\n\n", c); // 22
printf("Address of d: %d\n", &d);
printf("Address of d: %d\n", p2);
printf("Value of d: %d\n\n", d); // 10
p3=p1+1;
printf(“P3 : %d\n", p3);
return 0;
}
Pointers and arrays
• An array is a block of sequential data. Let's write a program to print addresses of array
element
#include <stdio.h>
int main() {
int x[4];
int i;
for(i = 0; i < 4; i++) {
printf("&x[%d] = %d\n", i, &x[i]);
}
printf("Address of array x: %d", x);
return 0;
}
• Output
• &x[0] = 1450734448
• &x[1] = 1450734452
• &x[2] = 1450734456
• &x[3] = 1450734460
• Address of array x: 1450734448
• Notice that, the address of &x[0] and x is the same. It's because the
variable name x points to the first element of the array.

• From the above example, it is clear that &x[0] is equivalent to x. And,


x[0] is equivalent to *x.
• Similarly,

• &x[1] is equivalent to x+1 and x[1] is equivalent to *(x+1).


• &x[2] is equivalent to x+2 and x[2] is equivalent to *(x+2).
• ...
• Basically, &x[i] is equivalent to x+i and x[i] is equivalent to *(x+i).
Example 1:WAP to find the number of elements in the array
#include <stdio.h>
int main() {
int i, x[6], count = 0;
printf("Enter numbers: ");
for(i = 0; i < 6; i++) {
// Equivalent to scanf("%d", &x[i]);
scanf("%d", x+i);
count++;
}
printf(“count = %d", count);
return 0;
}
• When you run the program, the output will be:

• Enter numbers: 2
3
4
4
12
4
Count=6
Use pointer to access the array elements. For
example,
#include<stdio.h>
int main()
{
int a[3] = {1, 2, 3};
int *p = a;
for (int i = 0; i < 3; i++)
{
printf("%d", *p);
p++;
}
return 0;
}
• Output
•123
Exercise
• WAP to find the sum of elements present in the array using pointers
• Methods to pass the data into the function in C language
• Arrays and functions
• Pointers and functions
There are two methods to pass the data into the function in C language
• Call by value
• Call by reference
Call by value in C

• In call by value method, the value of the actual parameters is copied into
the formal parameters. In other words, we can say that the value of the
variable is used in the function call in the call by value method.
• In call by value method, we can not modify the value of the actual
parameter by the formal parameter.
• In call by value, different memory is allocated for actual and formal
parameters since the value of the actual parameter is copied into the
formal parameter.
• The actual parameter is the argument which is used in the function call
whereas formal parameter is the argument which is used in the function
definition.
Example 1
Update the input value using function (call by value)

#include<stdio.h>
void change(int num) {
printf("Before adding value inside function num=%d \n",num);
num=num+100;
printf("After adding value inside function num=%d \n", num);
}
int main() {
int x=100;
printf("Before function call x=%d \n", x);
change(x);//passing value in function
printf("After function call x=%d \n", x);
return 0;
}
Output
• Before function call x=100
• Before adding value inside function num=100
• After adding value inside function num=200
• After function call x=100
Call by reference in C

• In call by reference, the address of the variable is passed into the


function call as the actual parameter.
• The value of the actual parameters can be modified by changing the
formal parameters since the address of the actual parameters is
passed.
• In call by reference, the memory allocation is similar for both formal
parameters and actual parameters. All the operations in the function
are performed on the value stored at the address of the actual
parameters, and the modified value gets stored at the same address.
Example 2
Update the input value using function (call by reference)

#include<stdio.h>
void change(int *num) {
printf("Before adding value inside function num=%d \n",*num);
(*num) += 100;
printf("After adding value inside function num=%d \n", *num);
}
int main() {
int x=100;
printf("Before function call x=%d \n", x);
change(&x);//passing reference in function
printf("After function call x=%d \n", x);
return 0;
}
Output
• Before function call x=100
• Before adding value inside function num=100
• After adding value inside function num=200
• After function call x=200
Pass arrays to a function in C

• We will see how to pass arrays to a function in C programming with


the help of examples.
Pass Individual Array Elements
• Passing array elements to a function is similar to passing variables to a function.
Example 1: Pass Individual Array Elements

#include <stdio.h>
void display(int age1, int age2) {
printf("%d\n", age1);
printf("%d\n", age2);
}
int main() {
int ageArray[] = {2, 8, 4, 12};
// pass second and third elements to display()
display(ageArray[1], ageArray[2]);
return 0;
}
Output

•8
•4
Example- Program to calculate the sum of array elements by passing to a function

#include <stdio.h>
float calculateSum(float num[]);
int main() {
float result, num[] = {23.4, 55, 22.6, 3, 40.5, 18};
// num array is passed to calculateSum()
result = calculateSum(num);
printf("Result = %.2f", result);
return 0;
}
float calculateSum(float num[]) {
float sum = 0.0;
for (int i = 0; i < 6; i++) {
sum += num[i];
}
return sum;
}
Usage of sizeof()
#include <stdio.h>
float calculateSum(float num[],int);
int main() {
float result, num[] = {23.4, 55, 22.6, 3, 40.5, 18};
int size;
size=sizeof(num)/sizeof(num[0]);
// num array is passed to calculateSum()
result = calculateSum(num,size);
printf("Result = %.2f", result);
return 0;
}
float calculateSum(float num[],int size) {
float sum = 0.0;
for (int i = 0; i < size; i++) {
sum += num[i];
}
return sum;
}
• Output
• Result = 162.50

• To pass an entire array to a function, only the name of the array is passed as an
argument.
• result = calculateSum(num);
• However, notice the use of [] in the function definition.
• float calculateSum(float num[]) {
• ... ..
• }
• This informs the compiler that you are passing a one-dimensional array to the
function.
Pass string as an argument
Example
#include <stdio.h>
void lengt(char[]);
void main()
{
char str1[]="good";
lengt(str1);
}
void lengt(char str1[])
{
int i, length=0;
for(i=0; str1[i]!='\0';i++)
length=length+1;
printf("length=%d\n", length);
}
Example : Passing Pointers to Functions
#include <stdio.h>
void addOne(int* ptr) {
(*ptr)++; // adding 1 to *ptr
}
int main()
{
int* p, i = 10;
p = &i;
addOne(p);
printf("%d", *p); // 11
return 0;
}
• Here, the value stored at p, *p, is 10 initially.

• We then passed the pointer p to the addOne() function. The ptr


pointer gets this address in the addOne() function.

• Inside the function, we increased the value stored at ptr by 1 using


(*ptr)++;. Since ptr and p pointers both have the same address, *p
inside main() is also 11.
Return pointer from function
Example
#include <stdio.h>
int* returnp(int []);
int main() {
int a[]={1,2,3,4,5};
int *p;
p=returnp(a);
printf("%d", *p);
return 0;
}
int* returnp(int a[])
{
a=a+1;
return a;
}
Structure
• Collection of elements with different datatype
• Define a structure
• Declare structure variables using that structure
• Initialization
• Access the members of structure
• Nested Structure
• Array of Structures
Define a structure
• Syntax:
struct tagname
{
Datatype variable name;
Datatype variable name;
..
..
};
Note-If we are not using tag name, then all the structure variables should mention
in the structure definition itself.
Example 1
struct student
{
int id;
char name[20];
float perc;
};
struct student s1; \\ declaration of structure variables
Example 2
struct
{
int id;
char name[20];
float perc;
} s1; \\ declaration of structure variables
Initialization
• Compile time initialization
• Eg- struct student s1={20,”Anu”, 75.5};
• struct student s2={24,”Abc”, 70.7};
Access the members of the structures
• Access the members of the structures using dot operator
• Eg- s1.id
• s1.name
Run time initialization

• Example
• scanf(“%d %s%f”,&s1.id,s1.name,&s1.perc);
Example
#include<stdio.h>
void main()
{
struct student
{
int id;
char name[20];
float perc;
};
struct student s1={20,"Anu",75.5};
struct student s2;
printf("enter details of s2");
scanf("%d %s %f",&s2.id,s2.name,&s2.perc);
printf("Details of student1");
printf("student id=%d\n student name=%s\n student percentage=%f\n",s1.id,s1.name,s1.perc);
printf("Details of student2");
printf("student id=%d\n student name=%s\n student percentage=%f\n",s2.id,s2.name,s2.perc);
}
Nested Structure
• A structure variable as a member of another structure
Example
#include<stdio.h>
struct dob
{
int day;
int month;
int year;
};
struct student
{
int id;
char name[20];
struct dob d1;
};
struct student s1;
void main()
{
printf("enter id of s1");
scanf("%d",&s1.id);
printf("enter name of s1");
scanf("%s",s1.name);
printf("enter dob of s1");
scanf("%d %d %d",&s1.d1.day,&s1.d1.month,&s1.d1.year);
printf("Details of student1\n");
printf("student id=%d\n student name=%s\n student dob=%d-%d-
%d\n",s1.id,s1.name,s1.d1.day,s1.d1.month,s1.d1.year);
}
Output
Or write the nested structure example like
this..
struct student
{
int id;
char name[20];
struct dob
{
int day;
int month;
int year;
}d1;
};
Array of Structures
• To declare an array of structure, first the structure must be defined and then an array
variable of that type should be defined.
• For Example − struct book b[10]; //10 elements in an array of structures of type ‘book’
Example
struct employee{
char name[20];
int eid;
int salary;
};
void main()
{
struct employee emp[10];
Example
#include <stdio.h>
#include <string.h>
struct student{
int id;
char name[30];
float percentage;
};
int main(){
int i;
struct student record[2];
// 1st student's record
record[0].id=1;
strcpy(record[0].name, "Bhanu");
record[0].percentage = 86.5;
// 2nd student's record
record[1].id=2;
strcpy(record[1].name, "Priya");
record[1].percentage = 90.5;
// 3rd student's record
record[2].id=3;
strcpy(record[2].name, "Hari");
record[2].percentage = 81.5;
for(i=0; i<3; i++){
printf(" Records of STUDENT : %d \n", i+1);
printf(" Id is: %d \n", record[i].id);
printf(" Name is: %s \n", record[i].name);
printf(" Percentage is: %f\n\n",record[i].percentage);
}
return 0;
}
Output
Records of STUDENT : 1
Id is: 1
Name is: Bhanu
Percentage is: 86.500000
Records of STUDENT : 2
Id is: 2
Name is: Priya
Percentage is: 90.500000
Records of STUDENT : 3
Id is: 3
Name is: Hari
Percentage is: 81.500000
Exercises
• WAP in C to store information of a student(id, age, name) using
structure
• WAP in C to store information of 10 employees(eid, name, salary)
using structure
• Pointer to Structure
• Structures and Functions
Pointer to Structure

• How to access the members of a structure using pointers


• Define a structure
• Declare structure variables
• Declare pointer variables
• Initialize the pointer variables
• Access the members through pointers
Define a structure
Declare structure variables

struct student
{
int id;
char name[20];
float perc;
};
struct student s1; \\ declaration of structure variables
Declare pointer variables
Initialize the pointer variables

• Example
struct student *ptr;
ptr=&s1; \\ Initialize the pointer variables
Access the members through pointers

• Example

• ptr-> id;
• ptr-> name;
• ptr-> perc;
Example
#include<stdio.h>
struct student
{
int id;
char name[20];
float perc;
};
void main()
{
struct student s1, *ptr; \\ declaration of structure variable and pointer variable\\
ptr=&s1;
printf("enter student id");
scanf("%d", &ptr->id);
printf("enter student name");
scanf("%s", ptr->name);
printf("enter student percentage");
scanf("%f", &ptr->perc);
printf("student id=%d\n", ptr->id);
printf("student name=%s\n", ptr->name);
printf("student percentage=%f", ptr->perc);
}
Output
Structures and Functions

• How a structure variable can be passed as a parameter to the


function
• This can be done in three ways:
• Passing individual members of a structure
• Passing entire structure
• Passing the address of a structure
Passing individual members of a structure

#include<stdio.h>
void display(int, float);
struct student
{
int id;
float perc;
};
int main()
{
struct student s1;
printf("enter student id");
scanf("%d", &s1.id);
printf("enter student percentage");
scanf("%f", &s1.perc);
display(s1.id,s1.perc);
return 0;
}
void display(int a, float b)
{
printf("student id=%d\n", a);
printf("student percentage=%f",b);
}
Passing entire structure

#include<stdio.h>
struct student
{
int id;
float perc;
};
void display(struct student s2);
int main()
{
struct student s1;
printf("enter student id");
scanf("%d", &s1.id);
printf("enter student percentage");
scanf("%f", &s1.perc);
display(s1);
return 0;
}
void display(struct student s2)
{
printf("student id=%d\n", s2.id);
printf("student percentage=%f",s2.perc);
}
Passing the address of a structure
#include<stdio.h>
struct student
{
int id;
float perc;
};
void display(struct student *s2);
int main()
{
struct student s1;
printf("enter student id");
scanf("%d", &s1.id);
printf("enter student percentage");
scanf("%f", &s1.perc);
display(&s1);
return 0;
}
void display(struct student *s2)
{
printf("student id=%d\n", s2->id);
printf("student percentage=%f",s2->perc);
}
Output
Practice Exercise

• WAP in C to store information of an employee(eid, age, name) using


structure
• Passing individual members of a structure
• Passing entire structure
• Passing the address of a structure
• WAP in C to store the marks of three subjects(subject1, subject2,
subject3) using structure and find the subject wise total marks of
three students.
User defined Functions –
• Declarations –
• Definition-
• Types of functions-
• Recursive functions
Function
• A function is a block of code that performs a specific task.

• Dividing a complex problem into smaller chunks makes our program


easy to understand and reuse.
Types of function

• There are two types of function in C programming:

• Standard library functions


• User-defined functions
User-defined function
• You can also create functions as per your need. Such functions created by the
user are known as user-defined functions.
• How user-defined function works?
#include <stdio.h>
void functionName()
{
... .. ...
... .. ...
}
int main()
{
... .. ...
... .. ...
functionName();
... .. ...
... .. ...
}
Explanation-

• The execution of a C program begins from the main() function.


• When the compiler encounters functionName();, control of the
program jumps to void functionName()
• And, the compiler starts executing the codes inside functionName().
• The control of the program jumps back to the main() function once
code inside the function definition is executed.
User-defined functions in C programming
• A function is a block of code that performs a specific task.
• C allows you to define functions according to your need. These
functions are known as user-defined functions. For example:
#include <stdio.h>
int addNumbers(int a, int b); // function prototype
int main()
{
int n1,n2,sum;
printf("Enters two numbers: ");
scanf("%d %d",&n1,&n2);
sum = addNumbers(n1, n2); // function call
printf("sum = %d",sum);
return 0;
}
int addNumbers(int a, int b) // function definition
{
int result;
result = a+b;
return result; // return statement
}
Function prototype(1/2)

• A function prototype is simply the declaration of a function that


specifies function's name, parameters and return type. It doesn't
contain function body.
• A function prototype gives information to the compiler that the
function may later be used in the program.
• Syntax of function prototype
• returnType functionName(type1 argument1, type2 argument2, ...);
Function prototype(2/2)

• In the above example, int addNumbers(int a, int b); is the function


prototype which provides the following information to the compiler:

• name of the function is addNumbers()


• return type of the function is int
• two arguments of type int are passed to the function
• The function prototype is not needed if the user-defined function is
defined before the main() function.
Calling a function

• Control of the program is transferred to the user-defined function by


calling it.
• Syntax of function call
• functionName(argument1, argument2, ...);
• In the above example, the function call is made using
addNumbers(n1, n2); statement inside the main() function.
Function definition

• Function definition contains the block of code to perform a specific task. In


our example, adding two numbers and returning it.
• Syntax of function definition
returnType functionName(type1 argument1, type2 argument2, ...)
{
//body of the function
}
• When a function is called, the control of the program is transferred to the
function definition. And, the compiler starts executing the codes inside the
body of a function.
• Passing arguments to a function
Passing arguments to a function

• In programming, argument refers to the variable passed to the


function. In the above example, two variables n1 and n2 are passed
during the function call.
• The parameters a and b accepts the passed arguments in the function
definition. These arguments are called formal parameters of the
function.
• The type of arguments passed to a function and the formal
parameters must match, otherwise, the compiler will throw an error.
Return Statement

• The return statement terminates the execution of a function and


returns a value to the calling function. The program control is
transferred to the calling function after the return statement.
• In the above example, the value of the result variable is returned to
the main function. The sum variable in the main() function is assigned
this value.
Types of User-defined Functions in C Programming

• No Argument Passed and No Return Value


• No Arguments Passed But Returns a Value
• Argument Passed But No Return Value
• Argument Passed and Returns a Value
No Argument Passed and No Return Value
#include <stdio.h>
void checkPrimeNumber();
int main() {
checkPrimeNumber(); // argument is not passed
return 0;
}
// return type is void meaning doesn't return any value
void checkPrimeNumber() {
int n, i, flag = 0;
printf("Enter a positive integer: ");
scanf("%d",&n);
// 0 and 1 are not prime numbers
if (n == 0 || n == 1)
flag = 1;
for(i = 2; i <= n/2; ++i) {
if(n%i == 0) {
flag = 1;
break;
}
}
if (flag == 1)
printf("%d is not a prime number.", n);
else
printf("%d is a prime number.", n);
}
Explanation
• The checkPrimeNumber() function takes input from the user, checks
whether it is a prime number or not, and displays it on the screen.
• The empty parentheses in checkPrimeNumber(); inside the main()
function indicates that no argument is passed to the function.
• The return type of the function is void. Hence, no value is returned
from the function.
No Arguments Passed But Returns a Value
#include <stdio.h>
int getInteger();
int main() {
int n, i, flag = 0;
// no argument is passed
n = getInteger();
// 0 and 1 are not prime numbers
if (n == 0 || n == 1)
flag = 1;
for(i = 2; i <= n/2; ++i) {
if(n%i == 0){
flag = 1;
break;
}
}
if (flag == 1)
printf("%d is not a prime number.", n);
else
printf("%d is a prime number.", n);
return 0;
}
// returns integer entered by the user
int getInteger() {
int n;
printf("Enter a positive integer: ");
scanf("%d",&n);
return n;
}
Explanation
• The empty parentheses in the n = getInteger(); statement indicates
that no argument is passed to the function. And, the value returned
from the function is assigned to n.
• Here, the getInteger() function takes input from the user and returns
it. The code to check whether a number is prime or not is inside the
main() function.
Argument Passed But No Return Value
#include <stdio.h>
void checkPrimeAndDisplay(int n);
int main() {
int n;
printf("Enter a positive integer: ");
scanf("%d",&n);
// n is passed to the function
checkPrimeAndDisplay(n);
return 0;
}
// return type is void meaning doesn't return any value
void checkPrimeAndDisplay(int n) {
int i, flag = 0;
// 0 and 1 are not prime numbers
if (n == 0 || n == 1)
flag = 1;
for(i = 2; i <= n/2; ++i) {
if(n%i == 0){
flag = 1;
break;
}
}
if(flag == 1)
printf("%d is not a prime number.",n);
else
printf("%d is a prime number.", n);
}
Explanation
• The integer value entered by the user is passed to the
checkPrimeAndDisplay() function.
• Here, the checkPrimeAndDisplay() function checks whether the
argument passed is a prime number or not and displays the
appropriate message.
Argument Passed and Returns a Value
#include <stdio.h>
int checkPrimeNumber(int n);
int main() {
int n, flag;
printf("Enter a positive integer: ");
scanf("%d",&n);
// n is passed to the checkPrimeNumber() function
// the returned value is assigned to the flag variable
flag = checkPrimeNumber(n);
if(flag == 1)
printf("%d is not a prime number",n);
else
printf("%d is a prime number",n);
return 0;
}
// int is returned from the function
int checkPrimeNumber(int n) {

// 0 and 1 are not prime numbers


if (n == 0 || n == 1)
return 1;
for(int i=2; i <= n/2; ++i) {
if(n%i == 0)
return 1;
}
return 0;
}
Explanation
• The input from the user is passed to the checkPrimeNumber()
function.
• The checkPrimeNumber() function checks whether the passed
argument is prime or not.
• If the passed argument is a prime number, the function returns 0. If
the passed argument is a non-prime number, the function returns 1.
The return value is assigned to the flag variable.
• Depending on whether flag is 0 or 1, an appropriate message is
printed from the main() function.
Recursion
• Recursive functions
• Functions that call themselves
• Two cases
• Base case
• Recursive case
Factorial using Recursion
Exercises
• Write a program in C to check whether the number is odd or even
using the function(Try with all user defined functions)
• Write a program in C to find the smallest of three numbers using
function
Exercises
• WAP to find the sum of natural numbers using recursion
Structure and Union
• Structure is defined as group of elements with different data types
• A union is a user-defined type similar to structs in C except for one
key difference.

• Structures allocate enough space to store all their members, whereas


unions can only hold one member value at a time
• Difference is in the allocation of memory location
How to define a union?

• We use the union keyword to define unions. Here's an example:

• union car
•{
• char name[50];
• int price;
• };
• The above code defines a derived type union car.
Create union variables
• When a union is defined, it creates a user-defined type. However, no
memory is allocated. To allocate memory for a given union type and work
with it, we need to create variables.
• Here's how we create union variables.

union car
{
char name[50];
int price;
};
int main()
{
union car car1, car2;
return 0;
}
Difference between unions and structures
#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
• size of structure = 40
Why this difference in the size of union and
structure variables?

• Here, the size of sJob is 40 bytes because

• the size of name[32] is 32 bytes


• the size of salary is 4 bytes
• the size of workerNo is 4 bytes
• However, the size of uJob is 32 bytes. It's because the size of a union
variable will always be the size of its largest element. In the above
example, the size of its largest element, (name[32]), is 32 bytes.
#include <stdio.h>
union Job {
float salary;
int workerNo;
} j;
int main() {
j.salary = 12.3;
// when j.workerNo is assigned a value,
// j.salary will no longer hold 12.3
j.workerNo = 100;
printf("Salary = %.1f\n", j.salary);
printf("Number of workers = %d", j.workerNo);
return 0;
}
• Output

• Salary = 0.0
• Number of workers = 100
Dynamic Memory Allocation
• An array is a collection of a fixed number of values. Once the size of
an array is declared, you cannot change it.

• Sometimes the size of the array you declared may be insufficient. To


solve this issue, you can allocate memory manually during run-time.
This is known as dynamic memory allocation in C programming.

• To allocate memory dynamically, library functions are malloc(),


calloc(), realloc() and free() are used. These functions are defined in
the <stdlib.h> header file.
malloc()
• The name "malloc" stands for memory allocation.
• The malloc() function reserves a block of memory of the specified number
of bytes. And, it returns a pointer which can be casted into pointers of any
form.
• Syntax of malloc()
• ptr = (castType*) malloc(size);
• Example
• ptr = (float*) malloc(100 * sizeof(float));
• The above statement allocates 400 bytes of memory. It's because the size
of float is 4 bytes. And, the pointer ptr holds the address of the first byte in
the allocated memory.
• The expression results in a NULL pointer if the memory cannot be
allocated.
free()

• Dynamically allocated memory created with either calloc() or malloc()


doesn't get freed on their own. You must explicitly use free() to
release the space.
• Syntax of free()
• free(ptr);
• This statement frees the space allocated in the memory pointed by
ptr.
// Program to calculate the sum of n numbers entered by the user-(use malloc() and free()

#include <stdio.h>
#include <stdlib.h>
int main() {
int n, i, *ptr, sum = 0;
printf("Enter number of elements: ");
scanf("%d", &n);
ptr = (int*) malloc(n * sizeof(int));
// if memory cannot be allocated
if(ptr == NULL) {
printf("Error! memory not allocated.");
}
else
{
printf("Enter elements: ");
for(i = 0; i < n; i++) {
scanf("%d", ptr + i);
sum += *(ptr + i);
}
printf("Sum = %d", sum);
// deallocating the memory
free(ptr);
return 0;
}
}
Output

Enter number of elements: 3


Enter elements: 100
20
36
Sum = 156
calloc()
• calloc() is a method in C which is also used to allocate memory blocks,
but it is generally used to allocate a sequence of memory blocks
(contiguous memory) like an array of elements. It is also present
in <stdlib.h> header file.
• Syntax of calloc()
• ptr = (castType*)calloc(n, size);
• Example:
• ptr = (float*) calloc(25, sizeof(float));
• The above statement allocates contiguous space in memory for 25
elements of type float.
// Program to calculate the sum of n numbers entered by the user (use calloc() and free()
#include <stdio.h>
#include <stdlib.h>
int main() {
int n, i, *ptr, sum = 0;
printf("Enter number of elements: ");
scanf("%d", &n);
ptr = (int*) calloc(n, sizeof(int));
if(ptr == NULL) {
printf("Error! memory not allocated.");
exit(0);
}
printf("Enter elements: ");
for(i = 0; i < n; ++i) {
scanf("%d", ptr + i);
sum += *(ptr + i);
}
printf("Sum = %d", sum);
free(ptr);
return 0;
}
Output

Enter number of elements: 3


Enter elements: 100
20
36
Sum = 156
realloc()

• If the dynamically allocated memory is insufficient or more than


required, you can change the size of previously allocated memory
using the realloc() function.

• Syntax of realloc()
• ptr = realloc(ptr, x);
• Here, ptr is reallocated with a new size x.
realloc()-Example
#include <stdio.h>
#include <stdlib.h>
int main() {
int *ptr, i , n1, n2;
printf("Enter size: ");
scanf("%d", &n1);
ptr = (int*) malloc(n1 * sizeof(int));
printf("Addresses of previously allocated memory:\n");
for(i = 0; i < n1; ++i)
printf("%d\n",ptr + i);
printf("\nEnter the new size: ");
scanf("%d", &n2);
// rellocating the memory
ptr = realloc(ptr, n2 * sizeof(int));

printf("Addresses of newly allocated memory:\n");


for(i = 0; i < n2; ++i)
printf("%d\n", ptr + i);

free(ptr);

return 0;
}
Output

Enter size: 2
Addresses of previously allocated memory:
26855472
26855476

Enter the new size: 4


Addresses of newly allocated memory:
26855472
26855476
26855480
26855484
Exercise
• WAP in C to display the following details using Dynamic Memory
Allocation for Structure
• Enter the number of records: 2
• Enter subject and marks:
• Science 82
• Enter subject and marks:
• DSA 73

• Displaying Information:
• Science 82
• DSA 73
#include <stdio.h>
#include <stdlib.h>
struct course {
int marks;
char subject[30];
};
int main() {
struct course *ptr;
int noOfRecords;
printf("Enter the number of records: ");
scanf("%d", &noOfRecords);
// Memory allocation for noOfRecords structures
ptr = (struct course *)malloc(noOfRecords * sizeof(struct course));
for (int i = 0; i < noOfRecords; i++) {
printf("Enter subject and marks:\n");
scanf("%s %d", (ptr + i)->subject, &(ptr + i)->marks);
}

printf("Displaying Information:\n");
for (int i = 0; i < noOfRecords; i++) {
printf("%s\t%d\n", (ptr + i)->subject, (ptr + i)->marks);
}

free(ptr);

return 0;
}
Enumeration
• In C programming, an enumeration type (also called enum) is a data
type that consists of integral constants. To define enums, the enum
keyword is used.

enum flag {const1, const2, ..., constN};


• By default, const1 is 0, const2 is 1 and so on. You can change default
values of enum elements during declaration (if necessary).
// Changing default values of enum constants
enum suit {
club = 0,
diamonds = 10,
hearts = 20,
spades = 3,
};
Enumerated Type Declaration

• enum boolean {false, true};


• enum boolean check; // declaring an enum variable
• Here, a variable check of the type enum boolean is created.
Example: Enumeration Type
#include <stdio.h>
enum week {Sunday, Monday, Tuesday, Wednesday, Thursday, Friday,
Saturday};
int main()
{
// creating today variable of enum week type
enum week today;
today = Wednesday;
printf("Day %d",today+1);
return 0;
}
Output
• Day 4
Difference
• Macros having global scope only but enum has both
• Automatically compiler can assign values in enum
• List of values are possible in enum
Command Line Arguments in C
• The arguments passed from command line are called command line
arguments. These arguments are handled by main() function.
• To support command line argument, you need to change the
structure of main() function as given below.

• int main(int argc, char *argv[] )

• Here, argc counts the number of arguments. It counts the file name
as the first argument.
• The argv[] means the value of the argumes. contains the total number
of arguments. The first argument is the file name always.
Example
Let's see the example of command line arguments where we are passing one argument with file
name.

#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]);
}
}
typedef in C
• typedef is a keyword used in C language to assign alternative names
to existing datatypes.Syntax of typedef
• typedef <existing_name> <alias_name>
• In the above syntax, 'existing_name' is the name of an already
existing variable while 'alias name' is another name given to the
existing variable.
For example..

• typedef unsigned int unit;


• Now, we can create the variables of type unsigned int by writing the
following statement:

• unit a, b;
• instead of writing:

• unsigned int a, b;
Example
#include <stdio.h>
int main()
{
typedef unsigned int unit;
unit i,j;
i=10;
j=20;
printf("Value of i is :%d",i);
printf("\nValue of j is :%d",j);
return 0;
}
• Output

• Value of i is :10
• Value of j is :20
Using typedef with structures
• Consider the below structure declaration:

• struct student
• {
• char name[20];
• int age;
• };
• struct student s1;
• In the above structure declaration, we have created the variable of student
type by writing the following statement:

• struct student s1;


Usage of typedef in structure
• struct student
• {
• char name[20];
• int age;
• };
• typedef struct student stud;
• stud s1, s2;
• In the above statement, we have declared the variable stud of type struct
student. Now, we can use the stud variable in a program to create the
variables of type struct student.
Example
#include <stdio.h>
typedef struct student
{
char name[20];
int age;
}stud;
int main()
{
stud s1;
printf("Enter the details of student s1: ");
printf("\nEnter the name of the student:");
scanf("%s",&s1.name);
printf("\nEnter the age of student:");
scanf("%d",&s1.age);
printf("\n Name of the student is : %s", s1.name);
printf("\n Age of the student is : %d", s1.age);
return 0;
}
Using typedef with pointers
• We can also provide another name or alias name to the pointer
variables with the help of the typedef.
• For example, we normally declare a pointer, as shown below:
• int* ptr;
• We can rename the above pointer variable as given below:
• typedef int* ptr;
• In the above statement, we have declared the variable of type int*.
Now, we can create the variable of type int* by simply using the 'ptr'
variable as shown in the below statement:

• ptr p1, p2 ;
• Const pointer
• Double pointer
• https://www.jdoodle.com/c-online-compiler/

You might also like