0% found this document useful (0 votes)
36 views113 pages

Unit 2

Uploaded by

nehal.arora
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)
36 views113 pages

Unit 2

Uploaded by

nehal.arora
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/ 113

Unit 2

Pointers and Arrays


Pointers and structures
⚫ Pointers: Basic concepts, Pointer
declaration and initialization, Scale factor,
Pointer to a pointer, Pointers and arrays,
Structures in C: Concept, Comparison with
arrays as a data structure, Array of
Structures, Pointers and Structures,
Concept of ordered list and polynomial
representation using array of structures.
Functions: Type of functions and their
categories, Parameter passing by value,
Parameter passing by reference, Recursive
functions, Bitwise Operators.
Pointers
⚫ The Pointer in C, is a variable that stores address
of another variable.
⚫ A pointer can also be used to refer to another
pointer function.
⚫ A pointer can be incremented/decremented, i.e.,
to point to the next/ previous memory location.
⚫ The purpose of pointer is to save memory space
and achieve faster execution time.
Pointers
⚫ Pointers are nothing but memory addresses
⚫ A pointer is a variable that contains the
memory location of another variable.
⚫ Therefore pointer is a variable that represents
the location of a data item, such as a variable
or an array element
Pointers
.
Pointers are used in many
applications

.
Example
⚫ #include <stdio.h>
⚫ int main() {
⚫ int myAge = 43;
⚫ printf("%d\n", myAge);
⚫ printf("%p\n", &myAge);
⚫ return 0;
⚫ }
⚫ In the example above, &myAge is also known as
a pointer.
⚫ A pointer is a variable that stores the memory
address of another variable as its value.
⚫ A pointer variable points to a data
type (like int) of the same type, and is created
with the * operator. The address of the
variable you are working with is assigned to
.
#include <stdio.h>
int main() {
int myAge = 43; // An int variable
int* ptr = &myAge; // A pointer variable, with the name ptr,
that stores address of
myAge
// Output the value of myAge (43)
printf("%d\n", myAge);
// Output the memory address of myAge
(0x7ffe5367e044)
printf("%p\n", &myAge);
// Output the memory address of myAge with the pointer
(0x7ffe5367e044)
printf("%p\n", ptr);
return 0;
}
⚫ Create a pointer variable with the name ptr, that points
to an int variable (myAge). Note that the type of the pointer has
to match the type of the variable you're working with.
Example
⚫ #include <stdio.h>

⚫ int main()
⚫ {
⚫ int a=10; //variable declaration
⚫ int *p; //pointer variable declaration
⚫ p=&a; //store address of variable a in pointer p
⚫ printf("Address stored in a variable p
is:%x\n",p); //accessing the address
⚫ printf("Value stored in a variable p is:%d\n",*p);
//accessing the value return 0;
⚫ }
Note:

⚫ Note that the * sign can be confusing here, as


it does two different things in our code:
⚫ When used in declaration (int* ptr), it creates
a pointer variable.
⚫ When not used in declaration, it act as
a dereference operator.
Note:
⚫ There are three ways to declare pointer
variables, but the first way is mostly used:
⚫ int* myNum; // Most used
int *myNum;
int * myNum;
Declaring a Pointer
⚫ Pointers have to be declared before they can be
used in your program
⚫ data_type * pointer_variable_name;
⚫ data_type is the pointer’s base type of C’s
variable types and indicates the type of the
variable that the pointer points to.
⚫ The asterisk (*: the same asterisk used for
multiplication) which is indirection operator,
declares a pointer.
Declaring a pointer

⚫ In each of the statement ,a pointer variable is


declared to point to a variable of the specified
data type.
Pointer assignment

.
pointers
⚫ ptr=&x
⚫ It assigns the address of x to ptr and
⚫ y=*ptr assigns the value pointed to by the
pointer ptr to y
⚫ *ptr=25
⚫ This statement puts the value of 25 at the
memory location whose address is the
value of ptr.
⚫ We know that the value of ptr is the
address of x and therefore old value of x is
replaced by 25.
Pointer increment and Scale Factor
.
Pointers and arrays

.
Pointers and arrays
Dereference

⚫ We use the pointer variable to get the memory


address of a variable (used together with
the & reference operator).
⚫ However, you can also get the value of the variable
the pointer points to, by using the * operator
(the dereference operator).
⚫ Dereferencing is used to access or manipulate data
contained in memory location pointed to by a
pointer. *(asterisk) is used with pointer variable
when dereferencing the pointer variable, it refers
to variable being pointed, so this is called
dereferencing of pointers
Dereference
⚫ Let's observe the following steps to dereference a
pointer.
⚫ First, we declare the integer variable to which the
pointer points.
⚫ int x =9;
⚫ Now, we declare the integer pointer variable.
⚫ int *ptr;
⚫ After the declaration of an integer pointer
variable, we store the address of 'x' variable to the
pointer variable 'ptr'.
⚫ ptr=&x;
⚫ We can change the value of 'x' variable by
dereferencing a pointer 'ptr' as given below:
⚫ *ptr =8;
⚫ The above line changes the value of 'x' variable
from 9 to 8 because 'ptr' points to the 'x' location
Dereference

⚫ #include <stdio.h>
⚫ int main()
⚫ {
⚫ int x=9;
⚫ int *ptr;
⚫ ptr=&x;
⚫ *ptr=8;
⚫ printf("value of x is : %d", x);
⚫ return 0;
⚫ }
Dereference

⚫ #include <stdio.h>
⚫ int main() {
⚫ int myAge = 43; // Variable declaration
⚫ int* ptr = &myAge; // Pointer declaration
⚫ // Reference: Output the memory address of
myAge with the pointer (0x7ffe5367e044)
⚫ printf("%p\n", ptr);
⚫ // Dereference: Output the value of myAge
with the pointer (43)
⚫ printf("%d\n", *ptr);
⚫ return 0;
⚫ }
Pointer to Pointer

⚫ When a pointer holds the address of another


pointer then such type of pointer is known
as pointer-to-pointer or double pointer
⚫ How to declare a Pointer to Pointer
(Double Pointer) in C?
⚫ int **pr;
⚫ Here pr is a double pointer. There must
be two *’s in the declaration of double
pointer.
Pointer to Pointer (Double Pointer) in C?

⚫ Let’s understand the concept of double pointers with the help


of a diagram:
⚫ As per the diagram, pr2 is a normal pointer that
holds the address of an integer variable num. There
is another pointer pr1 in the diagram that holds the
address of another pointer pr2, the pointer pr1 here
is a pointer-to-pointer (or double pointer).
⚫ Values from above diagram:
⚫ Variable num has address: XX771230
⚫ Address of Pointer pr1 is: XX661111
⚫ Address of Pointer pr2 is: 66X123X1
Pointer to Pointer
The pointers in turn point to data or even to
other pointers.
To declare pointers to pointers, just add
asterisk * for each level of reference
Pointers and Arrays

.
Initialize a pointer
⚫ Initialize a pointer
⚫ After declaring a pointer, we initialize it like
standard variables with a variable address.
⚫ If pointers in C programming are not
uninitialized and used in the program, the results
are unpredictable and potentially disastrous.
⚫ To get the address of a variable, we use the and
(&)operator, placed before the name of a variable
whose address we need. Pointer initialization is
done with the following syntax.
⚫ Pointer Syntax
⚫ pointer = &variable;
Pointer operations
⚫ There are only a few operations that are
allowed to perform on Pointers in C
language.
⚫ The operations are:
⚫ Increment/Decrement of a Pointer
⚫ Addition of integer to a pointer
⚫ Subtraction of integer to a pointer
⚫ Subtracting two pointers of the same type
⚫ Comparison of pointers of the same type
Increment/Decrement of a Pointer

⚫ Increment: When a pointer is incremented, it


actually increments by the number equal to the
size of the data type for which it is a pointer.
⚫ For Example: If an integer pointer that
stores address 1000 is incremented, then it will
increment by 2(size of an int) and the new
address it will points to 1002. While if a float type
pointer is incremented then it will increment by
4(size of a float) and the new address will be 1004.
⚫ Decrement: It is a condition that also comes
under subtraction. When a pointer is
decremented, it actually decrements by the
number equal to the size of the data type for
which it is a pointer.
⚫ For Example: If an integer pointer that
Scale Factor
⚫ Scale Factor:
⚫ What will be happened if we increase or
decrease or add or subtract with pointer
variable?
⚫ Suppose if we do increment an integer
type pointer variable, the value of address
of pointer variable will be increased with 4
or 2 not 1. And this length of data type is
called scale factor.
⚫ Ex: p=a or p=&a[0];
⚫ Each value of 'a' is accessed by using p++
to move from one element to
another. When a pointer is incremented,
its value is increased by the size of the
Double Pointer (Pointer to Pointer) in
C
⚫ Pointer to Pointer:The first pointer is used to
store the address of the variable. And the
second pointer is used to store the address of
the first pointer. This is also known as double
pointers.
⚫ Syntax:
⚫ int **ptr; // declaring double pointers
Example
⚫ #include<stdio.h>
⚫ void main () {
⚫ int a = 10;
⚫ int *p;
⚫ int **pp;
⚫ p = &a; // pointer p is pointing to the address of a

⚫ pp = &p; // pointer pp is a double pointer pointin


g to address
of pointer p
⚫ printf("address of a: %x\n"
,p); // Address of a will be printed
⚫ printf("address of p: %x\n"
,pp); // Address of p will be printed
⚫ printf("value stored at p: %d\n",*p); // value store a
t the address
Pointers in array
int main()
{
int *p,sum=0,i;
int x[5]={5,9,6,3,7};
i=0; p=x;
sum=0;
printf("Element value address\n");
while(i<5)
{
printf(“x[%d] %d %u \n”,i,*p, p);
sum=sum+*p;
i++,p++;
}printf("\n sum =%d\n",sum);
printf("\n &x[0] =%d\n",&x[0]);
printf("\n p =%d\n\n",p);
return 0;
}
Example
⚫ int myAge = 43; // An int variable
int* ptr = &myAge; // A pointer variable, with the
name ptr, that stores the address of myAge
// Output the value of myAge (43)
printf("%d\n", myAge);
// Output the memory address of myAge
(0x7ffe5367e044)
printf("%p\n", &myAge);
// Output the memory address of myAge with the
pointer (0x7ffe5367e044)
printf("%p\n", ptr);
---------------------------------------------------------
---
⚫ Use the & operator to store the memory address of
the myAge variable, and assign it to the pointer.
⚫ Now, ptr holds the value of myAge's memory
Pointers and Structure:
⚫ Structure pointer in C is declared using
keyword struct followed by structure name to
which pointer will point to followed by pointer
name. A structure pointer can only hold the
address of a variable of the same structure type
used in its declaration

⚫ Initialization of Structure Pointer: After a


structure pointer is declared we need to initialize
it to a variable before using it. To initialize a
variable we need to provide address of the
structure variable using the & operator.

⚫ Also, the structure pointer can be initialized


during the time of declaration.
Pointers and Structure:
⚫ #include <stdio.h>
⚫ struct abc
⚫ {
⚫ int x;
⚫ int y;
⚫ };
⚫ int main()
⚫ {
⚫ struct abc a={0,1};
⚫ struct abc *ptr=&a;
⚫ printf("%d\n",ptr->x);
⚫ printf("%d",ptr->y);
⚫ return 0;
⚫ }
Structure pointers: A pointer which points to address of
memory block that stores the structure
⚫ #include <stdio.h>
⚫ struct student
⚫ {
⚫ int rollno;
⚫ char name[20];
⚫ float marks;
⚫ };
⚫ struct student s={1,"Rashi"};
⚫ int main()
⚫ {
⚫ struct student *ptr=&s;
⚫ printf("Rollno:%d\n",ptr->rollno);
⚫ printf("Name:%s\n",ptr->name);
⚫ printf("Marks:%f\n",ptr->marks);
⚫ return 0;}
Structure pointers
⚫ #include <stdio.h>
⚫ struct student
⚫ {
⚫ int rollno;
⚫ char name[20];
⚫ float marks;
⚫ };
⚫ struct student s={1,"Rashi"};
⚫ int main()
⚫ {
⚫ struct student *ptr=&s;
⚫ printf("Rollno:%d\n",(*ptr).rollno);
⚫ printf("Name:%s\n",(*ptr).name);
⚫ printf("Marks:%f\n",(*ptr).marks);
⚫ return 0;
⚫ }
Pointer structure:pointer_name -> operator
⚫ struct Student {
⚫ char name[30];
⚫ int age;
⚫ int roll_number;
⚫ };
⚫ int main() {
⚫ struct Student student_1;
⚫ struct Student *sp = &student_1;
⚫ printf ("Enter the details of the Student (student_1)\n");
⚫ printf ("\tName: ");
⚫ scanf ("%s", sp->name);
⚫ printf ("\tAge: ");
⚫ scanf ("%d", &sp->age);
⚫ printf ("\tRoll Number: ");
⚫ scanf ("%d", &sp->roll_number);
⚫ printf ("\n Display the details of the student_1 using Structure
Pointer\n");
⚫ printf ("\tName: %s\n", sp->name);
⚫ printf ("\tAge: %d\n", sp->age);
⚫ printf ("\tRoll Number: %d", sp->roll_number);
Structure Pointers
.
Structure : structure pointer and arrow (->) operator

⚫ #include <stdio.h>
⚫ struct Employee // create Employee structure
⚫ {
⚫ // define the member of the structure
⚫ char name[30];
⚫ int id;
⚫ int age;
⚫ char gender[30];
⚫ char city[40];
⚫ };
⚫ // define the variables of the Structure with pointers
⚫ struct Employee emp1, emp2, *ptr1, *ptr2;
⚫ int main()
⚫ {
⚫ ptr1 = &emp1; // store the address of the emp1 and emp2 structure
variable
⚫ ptr2 = &emp2;
⚫ printf (" Enter the name of the Employee
(emp1): ");
⚫ scanf (" %s", &ptr1->name);
⚫ printf (" Enter the id of the Employee (emp1): ");
⚫ scanf (" %d", &ptr1->id);
⚫ printf (" Enter the age of the Employee (emp1):
");
⚫ scanf (" %d", &ptr1->age);
⚫ printf (" Enter the gender of the Employee
(emp1): ");
⚫ scanf (" %s", &ptr1->gender);
⚫ printf (" Enter the city of the Employee (emp1):
");
⚫ scanf (" %s", &ptr1->city);
⚫ printf (" \n Second Employee: \n");
⚫ printf (" Enter the name of the Employee
(emp2): ");
⚫ scanf (" %s", &ptr2->name);
⚫ printf (" Enter the id of the Employee (emp2): ");
⚫ printf (" Enter the gender of the Employee (emp2): ");
⚫ scanf (" %s", &ptr2->gender);
⚫ printf (" Enter the city of the Employee (emp2): ");
⚫ scanf (" %s", &ptr2->city);
⚫ printf ("\n Display the Details of the Employee using Structure
Pointer");
⚫ printf ("\n Details of the Employee (emp1) \n");
⚫ printf(" Name: %s\n", ptr1->name);
⚫ printf(" Id: %d\n", ptr1->id);
⚫ printf(" Age: %d\n", ptr1->age);
⚫ printf(" Gender: %s\n", ptr1->gender);
⚫ printf(" City: %s\n", ptr1->city);
⚫ printf ("\n Details of the Employee (emp2) \n");
⚫ printf(" Name: %s\n", ptr2->name);
⚫ printf(" Id: %d\n", ptr2->id);
⚫ printf(" Age: %d\n", ptr2->age);
⚫ printf(" Gender: %s\n", ptr2->gender);
⚫ printf(" City: %s\n", ptr2->city);
⚫ return 0;
output

.
String
⚫ Strings are defined as an array of characters
⚫ The string can be defined as the one-dimensional array of
characters terminated by a null ('\0').
⚫ There are two ways to declare a string in c language.
⚫ 1.By char array
⚫ 2.By string literal
⚫ 1. string by char array :
⚫ char ch[10]={'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't', '\0'};
⚫ 2.string by the string literal :
⚫ char ch[]="javatpoint";
Strings

⚫ Strings are used for storing text/characters.


⚫ For example, "Hello World" is a string of
characters.
⚫ Unlike many other programming languages, C
does not have a String type to easily create
string variables.
⚫ However, you can use the char type and create
an array of characters to make a string in C.
Strings
⚫ Array of characters to make a string in C:
⚫ char greetings[] = "Hello ";
⚫ Note that you have to use double quotes.

⚫ int main ()
⚫ {
⚫ char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
⚫ printf("Greeting message: %s\n", greeting );
⚫ return 0;
⚫ }
Example
⚫ To output the string, you can use
the printf() function together with the format
specifier %s to tell C that we are now working
with strings:
⚫ #include <stdio.h>
⚫ int main() {
⚫ char greetings[] = "Hello World!";
⚫ printf("%s", greetings);
⚫ return 0;
⚫ }
Access Strings
⚫ Access Strings
⚫ Since strings are actually arrays in C, you can
access a string by referring to its index
number inside square brackets [].
⚫ This example prints the first character
(0) in greetings:
⚫ Example
⚫ #include <stdio.h>
⚫ int main() {
⚫ char greetings[] = "Hello World!";
⚫ printf("%c", greetings[0]);
⚫ return 0;
⚫ }
Initializing a String:
⚫ A string can be initialized in different
ways.
The difference between a character array
and a string is ,the string is terminated
with a special character ‘\0’
1.char str[] = "GeeksforGeeks";
2. char str[50] = "GeeksforGeeks";
3. char str[] =
{'G','e','e','k','s','f','o','r','G','e','e','k','s','\0'};
4. char str[14]
={'G','e','e','k','s','f','o','r','G','e','e','k','s','\0'};
.
// C program to illustrate strings
⚫ #include<stdio.h>
⚫ int main()
⚫ {
⚫ // declare and initialize string
⚫ char str[] = "Geeks";
⚫ // print string
⚫ printf("%s",str);
⚫ return 0;
⚫ }
Modify Strings:
Example

⚫ To change the value of a specific character in


a string, refer to the index number, and
use single quotes:
⚫ #include <stdio.h>
⚫ int main() {
⚫ char greetings[] = "Hello World!";
⚫ greetings[0] = 'J';
⚫ printf("%s", greetings);
⚫ return 0;
⚫ }
Example
⚫ #include <stdio.h>
⚫ #include <string.h>
⚫ int main () {
⚫ char str1[12] = "Hello";
⚫ char str2[12] = "World";
⚫ char str3[12];
⚫ int len ;
⚫ strcpy(str3, str1); /* copy str1 into str3 */
⚫ printf("strcpy( str3, str1) : %s\n", str3 );
⚫ strcat( str1, str2); /* concatenates str1 and str2 */
⚫ printf("strcat( str1, str2): %s\n", str1 );
⚫ len = strlen(str1); /* total length of str1 after
concatenation */
⚫ printf("strlen(str1) : %d\n", len );
String Library functions
⚫ The predefined functions which are designed
to handle strings are available in the library
“string.h”. They are −
⚫ strlen ()
⚫ strcmp ()
⚫ strcpy ()
⚫ strncmp ()
⚫ strncpy ()
⚫ strrev ()
⚫ strcat ()
⚫ strstr ()
⚫ strncat ()
The strlen () function
⚫ It returns the number of characters in a string.
⚫ Syntax
⚫ int strlen (string name)
⚫ Example
⚫ #include <string.h>
⚫ main (){
⚫ char a[30] = “Hello”;
⚫ int l;
⚫ l = strlen (a);
⚫ printf (“length of the string = %d”, l);
⚫ }
⚫ Output:length of the string = 5
The strcpy () function
⚫ The strcpy () function
⚫ It is for copying source string into destination string.
⚫ The length of the destination string >= source string.
⚫ Syntax
⚫ strcpy (Destination string, Source String);
⚫ #include <string.h>
⚫ main (){
⚫ char a[30], b[50];
⚫ printf ("enter a source string");
⚫ scanf("%s", a);
⚫ printf("enter destination string");
⚫ scanf("%s",b);
⚫ strcpy ( b,a);
⚫ printf ("copied string = %s",b);
The strcat () function
⚫ It combines two strings.
⚫ The length of the destination string must be >
than the source string.
⚫ Syntax: strcat (Destination String, Source string);
⚫ #include <string.h>
⚫ main(){
⚫ char a[50] = "Hello";
⚫ char b[20] = "Good Morning";
⚫ clrscr ();
⚫ strcat (a,b);
⚫ printf("concatenated string = %s", a);
⚫ }
String concate
⚫ #include <stdio.h>
⚫ #include<string.h>
⚫ int main()
⚫ {
⚫ #include <stdio.h>
⚫ int main()
⚫ {
⚫ char a [30] = "Hello";
⚫ char b [20] = "Good Morning";
⚫ strncat (a,b,8);
⚫ a [15] = '\0';
⚫ printf("concatenated string = %s", a);
⚫ return 0;
⚫ }
strcmp() function
⚫ The strcmp() function (String comparison)
⚫ This function compares 2 strings.
⚫ It returns the ASCII difference of the first two
non – matching characters in both the strings.
⚫ Syntax:int strcmp (string1, string2);
⚫ //If the difference is equal to zero, then string1
= string2
⚫ //If the difference is positive, then string1 >
string2
⚫ //If the difference is negative, then string1 <
string2
Example

⚫ #include<string.h>
⚫ int main (){
⚫ char a[50], b [50];
⚫ int d;
⚫ printf ("Enter 2 strings:");
⚫ scanf ("%s %s", a,b);
⚫ d = strcmp(a,b);
⚫ if (d==0){
⚫ printf("%s is (alphabetically) equal to %s", a,b);
⚫ }
⚫ else if (d>0){
⚫ printf("%s is (alphabetically) greater than %s",a,b); }
⚫ else if (d<0)
⚫ {
⚫ printf("%s is (alphabetically) less than %s", a,b);
⚫ }}
The strcmp () function

⚫ This function is used for comparing first ‘n’ characters


of 2 strings.
⚫ Syntax: strncmp ( string1, string2,) .It compares two
string and returns 0 if both strings are equal. Here, we
are using gets() function which reads string from the
console.
⚫ #include <string.h>
⚫ int main(){
⚫ char str1[20],str2[20];
⚫ printf("Enter 1st string: ");
⚫ gets(str1);//reads string from console
⚫ printf("Enter 2nd string: ");
⚫ gets(str2);
⚫ if(strcmp(str1,str2)==0)
⚫ printf("Strings are equal");
⚫ else
⚫ printf("Strings are not equal");
⚫ return 0;
The strrev() function
⚫ The function is used for reversing a string.
⚫ The reversed string will be stored in the
same string.
⚫ Syntax:strrev (string)
Example:string reverse
⚫ #include<stdio.h>
⚫ main ()
⚫ {
⚫ char a[50] ;
⚫ clrscr();
⚫ printf ("enter a string");
⚫ gets (a);
⚫ strrev (a);
⚫ printf("reversed string = %s",a)
⚫ }
strstr() function
⚫ The strstr() function
⚫ It is used to search whether a substring is
present in the main string or not.
⚫ It returns pointer to first occurrence of s2
in s1.
⚫ Syntax
⚫ strstr(mainsring,substring);
Example of strstr()

.
Example strstr() function
⚫ This function takes two strings s1 and s2 as an
argument and finds the first occurrence of the
sub-string s2 in the string s1. The process of
matching does not include the terminating
null-characters(‘\0’), but function stops there.
⚫ Syntax:
⚫ char *strstr (const char *s1, const char *s2);
⚫ Parameters: s1: This is the main string to be
examined. s2: This is the sub-string to be
searched in s1 string.
⚫ Return Value: This function returns a pointer
points to the first character of the
found s2 in s1 otherwise a null pointer if s2 is
not present in s1. If s2 points to an empty
string, s1 is returned.
C String Uppercase: strupr()
⚫ The strupr(string) function returns string
characters in uppercase.
⚫ #include<stdio.h>
⚫ #include <string.h>
⚫ int main(){
⚫ char str[20];
⚫ printf("Enter string: ");
⚫ gets(str);//reads string from console
⚫ printf("String is: %s",str);
⚫ printf("\nUpper String is: %s",strupr(str));
⚫ return 0;
⚫ }
String Lowercase: strlwr()
⚫ The strlwr(string) function returns string
characters in lowercase. Let's see a simple
example of strlwr() function.
⚫ #include <string.h>
⚫ int main(){
⚫ char str[20];
⚫ printf("Enter string: ");
⚫ gets(str);//reads string from console
⚫ printf("String is: %s",str);
⚫ printf("\nLower String is: %s",strlwr(str));
⚫ return 0;
⚫ }
C String Functions
⚫ There are many important string functions defined
in "string.h" library.
Structure
⚫ C Structures (structs)
⚫ Structures (also called structs) are a way to group
several related variables into one place. Each
variable in the structure is known as a member of
the structure.
⚫ Unlike an array, a structure can contain many
different data types
(int, float, char, etc.).
Structure in C
⚫ Structure in c is a user-defined data type
that enables us to store the collection of
different data types. Each element of a
structure is called a member.
⚫ The struct keyword is used to define the
structure.
Create a Structure

⚫ You can create a structure by using


the struct keyword and declare each of its
members inside curly braces:
⚫ struct MyStructure { // Structure declaration
int myNum; // Member (int variable)
char myLetter; // Member (char variable)
}; // End the structure with a semicolon
Access the structure
⚫ To access the structure, you must create a
variable of it.
⚫ Use the struct keyword inside
the main() method, followed by the name of
the structure and then the name of the
structure variable:
⚫ Create a struct variable with the name "s1":
⚫ struct myStructure {
int myNum;
char myLetter;
};
int main() {
struct myStructure s1;
return 0;
}
Accessing members of the structure
⚫ Accessing members of the structure
⚫ There are two ways to access structure
members:
⚫ By . (member or dot operator)
⚫ By -> (structure pointer operator)
Example : To access members of a structure, use the dot
syntax (.)
⚫ #include <stdio.h>
⚫ // Create a structure called myStructure
⚫ struct myStructure {
⚫ int myNum;
⚫ char myLetter;
⚫ };
⚫ int main() {
⚫ // Create a structure variable of myStructure called s1
⚫ struct myStructure s1;
⚫ // Assign values to members of s1
⚫ s1.myNum = 13;
⚫ s1.myLetter = 'B';
⚫ // Print values
⚫ printf("My number: %d\n", s1.myNum);
⚫ printf("My letter: %c\n", s1.myLetter);
⚫ return 0;
⚫ }
Structure
Structure
Initialization of Structure
The Structure can be initialized in same way as
the other data types. Initializing structures
means assigning some constants to the
members of the structure
Example:

.
Example continued
Need of Structures
⚫ Heterogeneous collection of data
items: structure allows us to create user
defined data-type which can store items with
different data types.
⚫ Maintainability of code: using structure, we
represent complex records by using a single
name, which makes code maintainability
easy.
⚫ Enhanced code readability: code readability
is crucial for larger projects. Using structure
code looks user friendly which in turn helps
to maintain the project.
Example on Structure
⚫ #include <stdio.h>
⚫ struct Car {
⚫ char brand[50];
⚫ char model[50];
⚫ int year;
⚫ };
⚫ int main() {
⚫ struct Car car1 = {"BMW", "X5", 1999};
⚫ struct Car car2 = {"Ford", "Mustang", 1969};
⚫ struct Car car3 = {"Toyota", "Corolla", 2011};
⚫ printf("%s %s %d\n", car1.brand, car1.model, car1.year);
⚫ printf("%s %s %d\n", car2.brand, car2.model,
car2.year);
⚫ printf("%s %s %d\n", car3.brand, car3.model,
car3.year);
⚫ return 0;
⚫ }
Array of Structure
⚫ An array of structure is declared in same way
as we declare array of built in data type.
Example:
.
Array of structures
⚫ we can create an array of structures.
#include<stdio.h>
⚫ struct Point
⚫ {
⚫ int x, y;
⚫ };
⚫ int main()
⚫ {
⚫ // Create an array of structures
⚫ struct Point arr[10];
⚫ // Access array members
⚫ arr[0].x = 10;
⚫ arr[0].y = 20;
⚫ printf("%d %d", arr[0].x, arr[0].y);
⚫ return 0;
⚫ }
⚫ Output: 10 20
What is a structure pointer?

⚫ If we have a pointer to structure, members are accessed


using arrow ( -> ) operator.
⚫ #include<stdio.h>
⚫ struct Point
⚫ {
⚫ int x, y;
⚫ };
⚫ int main()
⚫ {
⚫ struct Point p1 = {1, 2};
⚫ // p2 is a pointer to structure p1
⚫ struct Point *p2 = &p1;
⚫ // Accessing structure members using structure pointer
⚫ printf("%d %d", p2->x, p2->y);
⚫ return 0;
⚫ }
Pointers and array
Functions
⚫ In c, we can divide a large program into the
basic building blocks known as function.
⚫ A function is a block of code which only
runs when it is called.
⚫ The function contains the set of
programming statements enclosed by {}.
⚫ A function can be called multiple times to
provide reusability and modularity to the
C program
⚫ By using functions, we can avoid rewriting
same logic/code again and again in a
program.
⚫ We can call C functions any number of
times in a program and from any place in a
program.
Create a Function
⚫ Syntax
⚫ void myFunction()
{
// code to be executed
}
Explaination:
⚫ myFunction() is the name of the function
⚫ void means that the function does not have
a return value.
⚫ Inside the function (the body), add code
that defines what the function should do.
Function example

⚫ #include <stdio.h>
⚫ // Create a function
⚫ void myFunction() {
⚫ printf("I just got executed!");
⚫ }
⚫ int main() {
⚫ myFunction(); // call the function
⚫ return 0;
⚫ }
Function example

⚫ A function can be called multiple times:


⚫ #include <stdio.h>
⚫ // Create a function
⚫ void myFunction() {
⚫ printf("I just got executed!\n");
⚫ }
⚫ int main() {
⚫ myFunction(); // call the function
⚫ myFunction(); // call the function
⚫ myFunction(); // call the function
⚫ return 0;
⚫ }
C Function Parameters

⚫ Information can be passed to functions as a


parameter. Parameters act as variables
inside the function.
⚫ Parameters are specified after the function
name, inside the parentheses.
⚫ Syntax
⚫ returnType functionName(parameter1, paramet
er2, parameter3) {
// code to be executed
}
Function Parameters
⚫ The following function that takes a string of
characters with name as parameter. When the
function is called, we pass along a name, which
is used inside the function to print "Hello" and
the name of each person.
⚫ #include <stdio.h>
⚫ void myFunction(char name[]) {
⚫ printf("Hello %s\n", name);
⚫ }
⚫ int main() {
⚫ myFunction("Liam");
⚫ myFunction("Jenny");
⚫ myFunction("Anja");
⚫ return 0;
⚫ }
Functions can be invoked in two ways: Call by
Value or Call by Reference
⚫ The parameters passed to function are
called actual parameters whereas the parameters
received by function are called formal
parameters.
⚫ Call By Value: In this parameter passing
method, values of actual parameters are copied
to function’s formal parameters and the two
types of parameters are stored in different
memory locations. So any changes made inside
functions are not reflected in actual parameters
of the caller.
⚫ Call by Reference: Both the actual and formal
parameters refer to the same locations, so any
changes made inside the function are actually
Call by Value or Call by Reference
Call by Value Call by Reference
While calling a function, we While calling a function,
pass values of variables to it. instead of passing the values
Such functions are known as of variables, we pass address
“Call By Values”. of variables(location of
variables) to the function
known as “Call By References.

In call-by-values, we cannot In call by reference we can


alter the values of actual alter the values of variables
variables through function through function calls.
calls.

Values of variables are passed Pointer variables are necessary


by the Simple technique. to define to store the address
values of variables.
Example on call by value
⚫ #include <stdio.h>
⚫ void swap(int x, int y); // Function Prototype
⚫ int main() // Main function
⚫ {
⚫ int a = 10, b = 20;
⚫ // Pass by Values
⚫ swap(a, b);
⚫ printf("a=%d b=%d\n", a, b);
⚫ return 0;
⚫ }
⚫ void swap(int x, int y){
⚫ int temp;
⚫ temp = x;
⚫ x = y;
⚫ y = temp;
⚫ printf("x=%d y=%d\n", x, y);}
Example on call by reference
⚫ #include <stdio.h>
⚫ void swap(int*, int*);// Function Prototype
⚫ int main() // Main function
⚫ {
⚫ int a = 10, b = 20; // Pass reference
⚫ swap(&a, &b);
⚫ printf("a=%d b=%d\n", a, b);
⚫ return 0;
⚫ }
⚫ void swap(int* x, int* y) // Function to swap two variables
⚫ { // by references
⚫ int temp;
⚫ temp = *x;
⚫ *x = *y;
⚫ *y = temp;
⚫ printf("x=%d y=%d\n", *x, *y);
⚫ }
Parameter Pass By Value
⚫ // C program to illustrate // call by value
⚫ #include <stdio.h>
⚫ void func(int a, int b)
⚫ {
⚫ a += b;
⚫ printf("In func, a = %d b = %d\n", a, b);
⚫ }
⚫ int main(void)
⚫ {
⚫ int x = 5, y = 7;
⚫ // Passing parameters
⚫ func(x, y);
⚫ printf("In main, x = %d y = %d\n", x, y);
⚫ return 0;}
⚫ Output: In func, a = 12 b = 7
In main, x = 5 y = 7
Parameter Pass by reference
⚫ // C program to illustrate// call by reference
⚫ #include <stdio.h>
⚫ void swapnum(int* i, int* j)
⚫ {
⚫ int temp = *i;
⚫ *i = *j;
⚫ *j = temp;
⚫ }
⚫ int main(void)
⚫ {
⚫ int a = 10, b = 20;
⚫ // passing parameters
⚫ swapnum(&a, &b);
⚫ printf("a is %d and b is %d\n", a, b);
⚫ return 0;
⚫ }
⚫ Output: a is 20 and b is 10
Recursive function

⚫ Recursion is the technique of making a


function call itself.
Recursion

⚫ 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
⚫ #include <stdio.h> //calculate the factorial of a number.
⚫ int fact (int);
⚫ int main()
⚫ {
⚫ int n,f;
⚫ printf("Enter the number whose factorial you want to calculate?");
⚫ scanf("%d",&n);
⚫ f = fact(n);
⚫ printf("factorial = %d",f);
⚫ }
⚫ int fact(int n)
⚫ {
⚫ if (n==0)
⚫ { return 0;
⚫ }
⚫ else if ( n == 1)
⚫ {
⚫ return 1;
⚫ }
⚫ else
⚫ {
⚫ return n*fact(n-1);
⚫ } }
Operators in c
Bitwise Operators in C
⚫ The & (bitwise AND) in C takes two numbers as
operands and does AND on every bit of two
numbers. The result of AND is 1 only if both bits
are 1.
⚫ The | (bitwise OR) in C takes two numbers as
operands and does OR on every bit of two
numbers. The result of OR is 1 if any of the two
bits is 1.
⚫ The ^ (bitwise XOR) in C takes two numbers as
operands and does XOR on every bit of two
numbers. The result of XOR is 1 if the two bits are
different.
⚫ The << (left shift) in C takes two numbers, left
shifts the bits of the first operand, the second
operand decides the number of places to shift.
⚫ The >> (right shift) in C takes two numbers, right
shifts the bits of the first operand, the second
operand decides the number of places to shift.
⚫ The ~ (bitwise NOT) in C takes one number and
Bitwise Operators in C
Operators Meaning of operators

& Bitwise AND

| Bitwise OR

^ Bitwise XOR

Bitwise
~
complement

Shift left

>> Shift right


Bitwise AND Operator &
⚫ The output of bitwise AND is 1 if the corresponding bits of two
operands is 1. If either bit of an operand is 0, the result of
corresponding bit is evaluated to 0.
⚫ In C Programming, the bitwise AND operator is denoted by &.
⚫ Let us suppose the bitwise AND operation of two
integers 12 and 25.
⚫ 12 = 00001100 (In Binary)
⚫ 25 = 00011001 (In Binary)
⚫ Bit Operation of 12 and 25
⚫ 00001100
⚫ & 00011001
⚫ ________
⚫ 00001000 = 8 (In decimal)
⚫ Example 1: Bitwise AND
⚫ #include <stdio.h>
⚫ int main() {
⚫ int a = 12, b = 25;
⚫ printf("Output = %d", a & b);
⚫ return 0;
⚫ }
⚫ Output
⚫ Output = 8
Bitwise OR Operator |
⚫ The output of bitwise OR is 1 if at least one corresponding
bit of two operands is 1. In C Programming, bitwise OR
operator is denoted by |.
⚫ 12 = 00001100 (In Binary)
⚫ 25 = 00011001 (In Binary)
⚫ Bitwise OR Operation of 12 and 25
⚫ 00001100
⚫ | 00011001
⚫ ________
⚫ 00011101 = 29 (In decimal)
⚫ Example 2: Bitwise OR
⚫ #include <stdio.h>
⚫ int main() {
⚫ int a = 12, b = 25;
⚫ printf("Output = %d", a | b);
⚫ return 0;
⚫ }
⚫ Output
⚫ Output = 29
Bitwise XOR (exclusive OR) Operator ^
⚫ The result of bitwise XOR operator is 1 if the corresponding
bits of two operands are opposite. It is denoted by ^.
⚫ 12 = 00001100 (In Binary)
⚫ 25 = 00011001 (In Binary)
⚫ Bitwise XOR Operation of 12 and 25
⚫ 00001100
⚫ ^ 00011001
________
⚫ 00010101 = 21 (In decimal)
⚫ Example 3: Bitwise XOR
⚫ #include <stdio.h>
⚫ int main() {
⚫ int a = 12, b = 25;
⚫ printf("Output = %d", a ^ b);
⚫ return 0;
⚫ }
⚫ Output
⚫ Output = 21
Bitwise Complement Operator ~

⚫ Bitwise complement operator is a unary


operator (works on only one operand). It
changes 1 to 0 and 0 to 1. It is denoted by ~.
⚫ 35 = 00100011 (In Binary)
⚫ Bitwise complement Operation of 35
⚫ ~ 00100011
⚫ ________
⚫ 11011100 = 220 (In decimal)
⚫ For any integer n, bitwise complement
of n will be -(n + 1). To understand this, you
should have the knowledge of 2's complement.
Bitwise Complement Operator ~:2's Complement
⚫ Two's complement is an operation on binary numbers.
The 2's complement of a number is equal to the
complement of that number plus 1. For example:
⚫ The bitwise complement of 35 is 220 (in decimal). The
2's complement of 220 is -36. Hence, the output
is -36 instead of 220.
⚫ Bitwise Complement of Any Number N is -(N+1). Here's
how:
⚫ bitwise complement of N = ~N (represented in 2's
complement form)
⚫ 2'complement of ~N= -(~(~N)+1) = -(N+1)
⚫ Eg 4: Bitwise complement
⚫ #include <stdio.h>
⚫ int main() {
printf("Output = %d\n", ~35);
printf("Output = %d\n", ~-12);
⚫ return 0;
⚫ }
⚫ Output
Shift Operators in C programming

⚫ There are two shift operators in C


programming:
⚫ Right shift operator
⚫ Left shift operator.
⚫ Right Shift Operator
⚫ Right shift operator shifts all bits towards right
by certain number of specified bits. It is
denoted by >>.
⚫ 212 = 11010100 (In binary)
⚫ 212 >> 2 = 00110101 (In binary) [Right shift by
two bits]
⚫ 212 >> 7 = 00000001 (In binary)
⚫ 212 >> 8 = 00000000
⚫ 212 >> 0 = 11010100 (No Shift)
Left Shift Operator

⚫ Left shift operator shifts all bits towards left by


a certain number of specified bits. The bit
positions that have been vacated by the left
shift operator are filled with 0. The symbol of
the left shift operator is <<.
⚫ 212 = 11010100 (In binary)
⚫ 212<<1 = 110101000 (In binary) [Left shift by
one bit]
⚫ 212<<0 = 11010100 (Shift by 0)
⚫ 212<<4 = 110101000000 (In binary) =3392(In
decimal)
Example #5: Shift Operators
⚫ #include <stdio.h>
⚫ int main() {
⚫ int num=212, i;
⚫ for (i = 0; i <= 2; ++i) {
⚫ printf("Right shift by %d: %d\n", i, num >> i);
⚫ }
⚫ printf("\n");
⚫ for (i = 0; i <= 2; ++i) {
⚫ printf("Left shift by %d: %d\n", i, num << i);
⚫ }
⚫ return 0;}
⚫ Output: Right Shift by 0: 212
⚫ Right Shift by 1: 106
⚫ Right Shift by 2: 53
⚫ Left Shift by 0: 212
⚫ Left Shift by 1: 424
⚫ Left Shift by 2: 848

You might also like