C Important Notes
C Important Notes
• 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() {
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.
• int *p;
• Here, we have declared a pointer p of int type.
Assigning addresses to Pointers
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.
• 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
#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
#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.
• 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
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
#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
• 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?
• 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.
#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
• 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));
free(ptr);
return 0;
}
Output
Enter size: 2
Addresses of previously allocated memory:
26855472
26855476
• 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.
• 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..
• 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:
• ptr p1, p2 ;
• Const pointer
• Double pointer
• https://www.jdoodle.com/c-online-compiler/