DS Unit I
DS Unit I
Dept. of E&TC
PICT Pune
Prepared By:
Dr. S. S. Vasekar
Introduction to C Programming
In C programming, data types are used to specify the type of a variable, which determines
the amount of memory the variable takes up and the range of values that can be stored in
that memory. The data types in C can be classified into the following categories:
Data Types
⚫ The data type specifies the size and type of information
the variable will store.
Type Storage size Value range
Output:
Format specifier for float
Output:
Format specifier for Double
Output:
Format specifier for Char
Output:
Format specifier for String
Output:
Set Decimal Precision
Output:
Output:
OPERATORS
o An operator is a symbol that tells the compiler
to perform specific mathematical or logical
functions.
o C language is rich in built-in operators and
provides the following types of operators:
• Arithmetic Operators
• Assignment Operators
• Logical Operators
• Relational Operators
• Bitwise Operators
Arithmetic Operators
⚫ Arithmetic operators are used to perform common mathematical
operations.
+ Operator
(Adds two values together)
Output:
* Operator
(Multiplies two values)
Output:
/ Operator
(Divides one value by another)
Output:
% Modulus Operator
(Returns the division remainder)
Output:
++ Increment Operator
(Increases the value of a variable by one)
Output:
-- Increment Operator
(Decreases the value of a variable by one)
Output:
Assignment Operators
Assignment operators are used to assign values to variables.
(Example: int x=5)
Relational/Comparison Operators
Comparison operators are used to compare two values (or variables).
The return value of a comparison is either 1 or 0, which means true (1) or false (0).
Relational/Comparison Operators
Output:
Relational/Comparison Operators
Output:
Logical Operators
Logical operators are used to determine the logic between variables or values:
Logical && (and) Operator
Output:
Logical II (or) Operator
Output:
Logical ! (not)Operator
Output:
Sizeof Operator
The memory size (in bytes) of a data type or a variable can be found
with the sizeof operator:
• Note that we use the %lu format specifier to print the result, instead of %d.
• On some computers it might work with %d, but it is safer to use %lu
Sizeof Operator
Output:
Bitwise Operators
Bitwise operator works on bits and perform bit-by-bit operation. The
truth tables for &, |, and ^ is as follows :
& Binary AND Operator copies a bit to the result (A & B) = 12, i.e., 0000 1100
if it exists in both operands.
^ Binary XOR Operator copies the bit if it is set (A ^ B) = 49, i.e., 0011 0001
in one operand but not both.
You can use these conditions to perform different actions for different decisions.
C has the following conditional statements:
switch (day) {
case 1:
printf("Monday");
break;
case 2:
printf("Tuesday");
break;
case 3:
printf("Wednesday");
break;
case 4:
printf("Thursday");
break;
case 5:
printf("Friday");
break;
case 6:
printf("Saturday");
break;
case 7:
printf("Sunday");
break;
}
While Loop
The Do/While Loop
For Loop
For Loop
Nested Loops
o To create an array, define the data type (like int) and specify the name of the
array followed by square brackets [ ].
Note: Using this method, you should know the size of the array, in order for the program
to store enough memory.
You are not able to change the size of the array after creation.
C Multidimensional Arrays
o If you want to store data as a tabular form, like a table with rows and
columns, you need to get familiar with multidimensional arrays.
The first dimension represents the number of rows [2], while the second
dimension represents the number of columns [3]. The values are placed
in row-order, and can be visualized like this:
Access the Elements of a 2D Array
To access an element of a two-dimensional array, you must
specify the index number of both the row and column.
The following example will change the value of the element in the
first row (0) and first column (0):
Loop Through a 2D Array
To loop through a multi-dimensional array, you need one loop for each of the
array's dimensions.
Objective: Create an integer array of size 5 and initialize it with values 10, 20,
30, 40, and 50. Print the elements of the array.
int main ()
{
int arr [5] = {10 , 20 , 30 , 40 , 50};
return 0;
}
Output: 10 20 30 40 50
C Programming: Array
E XAMPLE 2: Array Sum
Objective: Create an integer array of size 6 and initialize it with some values.
Calculate and print the sum of all elements in the array.
int main ()
{
int arr [] = {10 , 20 , 30 , 40 , 50 , 60};
int sum = 0;
Output: ??
C Programming: Array
E XAMPLE 3: Largest Element
Objective: Create an integer array of size 7 and initialize it with values. Find and
print the largest element in the array.
int main()
{
int arr [ ] = { 35, 12, 78, 95, 42, 17, 8 };
int largest = arr[0];
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:
Output:
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:
Output:
Modify Strings
To change the value of a specific character in a string, refer to the
index number, and use single quotes:
Output:
Loop Through a String
You can also loop through the characters of a string, using a for loop:
Output:
Another Way of Creating Strings
You should also note that you can create a string with a set of characters.
This example will produce the same result as the previous example :
Output:
Differences
The difference between the two ways of creating strings, is that the first
method is easier to write, and you do not have to include the \0
character, as C will do it for you.
You should note that the size of both arrays is the same:
They both have 13 characters (space also counts as a character by the
way), including the \0 character:
Output:
C Special Characters
C also has many useful string functions, which can be used to perform
certain operations on strings.
To use them, you must include the <string.h> header file in your program:
String Length
For example, to get the length of a string, you can use the strlen() function:
Output:
In the Strings, we used sizeof to get the size of a string/array.
Note that sizeof and strlen behaves differently, as sizeof also includes
the \0 character when counting:
Output:
It is also important that you know that sizeof will always return the
memory size (in bytes), and not the actual string length:
Output:
Concatenate Strings
To concatenate (combine) two strings, you can use the strcat() function:
Output:
Copy Strings
To copy the value of one string to another, you can use the strcpy() function:
Compare Strings
To compare two strings, you can use the strcmp() function.
It returns 0 if the two strings are equal, otherwise a value that is not 0:
C Functions
A function is a block of code which only runs when it is called.
Functions are used to perform certain actions, and they are important
for reusing code: Define the code once, and use it many times.
Predefined Functions
o For example, main() is a function, which is used to execute code, and printf() is
a function; used to output/print text to the screen:
Create a Function
To create (often referred to as declare) your own function,
specify the name of the function, followed by parentheses ( ) and curly brackets { }:
You can add as many parameters as you want, just separate them
with a comma:
C 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.
C Function Parameters
Multiple Parameters
Inside the function, you can add as many parameters as you want:
Pass Arrays as Function Parameters
You can also pass arrays to a function:
Pass Arrays as Function Parameters
Return Values
The void keyword, used in the previous examples, indicates that the function
should not return a value.
If you want the function to return a value, you can use a data type
(such as int or float, etc.) instead of void, and use the return keyword inside the
function:
Function Declaration and Definition
You can create and call a function in the following way:
A function consist of two parts:
Declaration: the function's name, return type, and parameters
(if any)
Definition: the body of the function (code to be executed)
This will make the code better organized and easier to read:
Example
Another Example
If we use the example regarding function parameters and return
values:
C Recursion
Recursion is the technique of making a function call itself.
Example
Since the function does not call itself when k is 0, the program stops there
and returns the result.
C Memory Address
When a variable is created in C, a memory address is assigned to the variable.
The memory address is the location of where the variable is stored on the
computer.
To access it, use the reference operator (&), and the result represents where the
variable is stored:
Note: The memory address is in hexadecimal form (0x..). You will probably not
get the same result in your program, as this depends on where the variable is
stored on your computer.
Unlike an array, a structure can contain many different data types (int, float,
char, etc.).
Create a Structure
You can create a structure by using the struct keyword and declare each of its
members inside curly braces:
Use the struct keyword inside the main() method, followed by the name of the
structure and then the name of the structure variable:
Access Structure Members
To access members of a structure, use the dot syntax (.):
Now you can easily create multiple structure variables with different values,
using just one structure:
Output:
What About Strings in Structures?
Remember that strings in C are actually an array of characters, and unfortunately, you can't
assign a value to an array like this:
However, there is a solution for this! You can use the strcpy() function
and assign the value to s1.myString, like this:
Simpler Syntax
You can also assign values to members of a structure variable at declaration time,
in a single line. Just insert the values in a comma-separated list inside curly braces { }.
Note : You don't have to use the strcpy() function for string values with this
technique:
You can also assign one structure to another. In the following example, the
values of s1 are copied to s2:
Modify Values
If you want to change/modify a value, you can use the dot syntax (.).
And to modify a string value, the strcpy() function is useful again:
Modifying values are especially useful when you copy structure values:
// Print values
printf("%d %c %s\n", s1.myNum, s1.myLetter, s1.myString);
printf("%d %c %s\n", s2.myNum, s2.myLetter, s2.myString);
return 0;
Real Life Example
Use a structure to store different information about Cars:
C Pointers
Creating Pointers
we can get the memory address of a variable with the reference operator & :
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 the pointer:
Explanation:
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 (int in our example).
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 address.
Dereference
In the example above, we used the pointer variable to get the memory address of a
variable (used together with the & reference operator).
You can also get the value of the variable the pointer points to, by using the * operator
(the dereference operator):
C Pointers and Arrays
You can also use pointers to access arrays.
Consider the following array of integers:
You learned from the arrays that you can loop through the array elements with
a for loop:
Instead of printing the value of each array element, let's print the memory address of
each array element:
Note that the last number of each of the elements' memory address is different,
with an addition of 4.
It is because the size of an int type is typically 4 bytes, remember:
So from the "memory address example" above, you can see that the compiler
reserves 4 bytes of memory for each array element, which means that the entire
array takes up 16 bytes (4 * 4) of memory storage:
How Are Pointers Related to Arrays
The memory address of the first element is the same as the name of the
array:
This basically means that we can work with arrays through pointers!
How? Since myNumbers is a pointer to the first element in myNumbers,
you can use the * operator to access it:
To access the rest of the elements in myNumbers, you can increment
the pointer/array (+1, +2, etc):
Or loop through it:
It is also possible to change the value of array elements with pointers:
Arrays in C
Declaring Arrays
To declare an array in C, a programmer specifies the type of the elements and the number of elements
required by an array as follows −
double balance[10];
Here balance is a variable array which is sufficient to hold up to 10 double numbers.
Initializing Arrays
You can initialize an array in C either one by one or using a single statement as follows −
If you omit the size of the array, an array just big enough to hold the initialization is created. Therefore, if
you write −
balance[4] = 50.0;
Example
⚫ #include <stdio.h>
⚫ Int n[10];
⚫ int main () { n[0]= first element in array
N[1]=
⚫ int n[ 10 ]; /* n is an array of 10 integers */
N[2]
⚫ int i,j;
⚫
⚫ return 0;
⚫ } Element[0] = 100
⚫ Element[1] = 101
⚫ Element[2] = 102
⚫ Element[3] = 103
Reference:
⚫ Element[4] = 104 https://www.tutorialspoint.com/cprogrammi
⚫ Element[5] = 105 ng/c_arrays.htm
Write a C program to input and display
roll no , name of 5 students
C-Pointers
⚫ Pointers in C are easy and fun to learn. Some C
programming tasks are performed more easily
with pointers, and other tasks, such as dynamic
Text mesg memory allocation, cannot be performed without
Destination using pointers. So it becomes necessary to learn
address
pointers to become a perfect C programmer.
Int a; Let's start learning them in simple and easy steps.
2bytes ⚫ As you know, every variable is a memory location
and every memory location has its address
Int *p;
defined which can be accessed using ampersand
(&) operator, which denotes an address in
Declaration
syntax for
pointers memory. Consider the following example, which
P=&a; prints the address of the variables defined −
&-address
of variable
a.
#include <stdio.h>
int main () {
int var1;
char var2[10];
return 0;
}
Address of var1 variable: bff5a400 Address of var2 variable: bff5a3f6
4 Passing pointers to functions in CPassing an argument by reference or by address enable the passed
argument to be changed in the calling function by the called function.
5 Return pointer from functions in CC allows a function to return a pointer to the local variable, static
variable, and dynamically allocated memory as well.
Call by value method
WACP to swap program
Function declarartion
Void swap(int,int);
Int main(){
Int a=10;
Int b=20;
Function calling
Swap(a,b);
Printf(%d%d”,a,b);
}
Function definition
Void swap(int x, int y)
{//=10,y=20
Int t;
t=x;
X=y;
Y=t;
Printf(“%d%d”,x,y);
}
Output=20,10 10 20
Call by Reference method
WACP to swap program
Function declarartion
Void swap(int *,int*); A=10 B=20
Int main(){
Int a=10;
Int b=20; 100 200
Function calling
Swap(&a,&b);
Printf(%d%d”,a,b);
}
Function definition
Void swap(int*x, int*y)
{//x= the value of the address 100=10
// y= the value t the address 200 =20
Int t;
t=*x;
*X=*y;
*y=t;
Printf(“%d%d”,*x,*y);
}
Output=20,10 20 10
The automatic storage class
}
The Register Storage Class
⚫The variables stored in register of CPU
are accessed in much lesser time.
⚫The keyword register is used.
⚫The default value is not known
⚫It is applicable to int and char only.
⚫The scope is limited upto the region or
block or function in which it is defined.
Static Storage class
⚫The static storage class variable makes
the variable permanent.
⚫Their can be local i.e. internal static
variables and global i.e. external static
variables.
⚫The default value is zero.
⚫They are stored in primary memory.
⚫The external static variables in a
program are declared like global variables
with the keyword static.
⚫The static var are accessible by all
functions in the program file where these
variables exist and are declared. These
variables are not accessible in the other
files.
⚫These variables exist thrugout the main
program execution.
#include<stdio.h>
Main()
{
Void show();
Printf(“\n first call”)
Show();
Printf(“\n 2nd call”)
Show();
Printf(“\n third call”)
Show();
}
Void show()
{
Static int i;
Printf(“%d”,i);
i++;
}
Op:
First call i=0; 2nd call i=1 3rd call i=2
Recursive Functions
⚫Recursion in programming is a technique
for defining a problem in terms of one
or more smaller versions of the
problem.
⚫ enter a char : H
● 2nd call to print_backward
● enter a char: i.
● 3rd call to print_backward
● enter a char: .
● //now it will not call againcoz its ‘.’
#include<stdio.h>
long int factorial(int no);
int main()
{
int i;
printf(“enter number”);
scanf(“%d”,&i);
printf(“factorial of %d is %ld”, I, factorial(i));
}
Long int factorial(int n)
{ Factorial=5
5*4*3*2*1
if(n==0) 5*factorial(4)
Return 1; 5*4*fact(3)
5*4*3*…..
else
Return (n * factorial(n-1));
}
I/P: 3
o/p: 6
⚫ N->3
⚫ 3==0 false
⚫ Ans = 3* factorial (3-1)//2
⚫ n=2;
⚫ 2==0 false
⚫ Ans=2*factorial(2-1)//1
⚫ n=1
⚫ 1==0 false
⚫ Ans =1 * factorial (1-1)//0
⚫ n=0;
⚫ 0==0 true…
⚫ return 1;
⚫ Ans=1*1
⚫ Return 1;
⚫ Ans=2*1;
⚫ Return 2;
⚫ Ans=3*2;
⚫ Return 6.
Comparing recursion and iteration
}
Union student:
union student
{
Int roll;
Char name[20];
Char address[20];
Float avg;
}s; // structure memory for s= 2+20+20+4
//union memory for s=memory allocated by the variable which takes maximum size
//s=20bytes
Int main()
{
Scanf(“%d%s%s%f”,&s.roll,s.name,s.address,&s.avg);
}
printf(“%d%s%s%f”,s.roll,.name,s.address,s.avg);
// structure variable.(dot operator)structure element name;
}
⚫WACP to input student name, roll no,
subject names of SE sem I and display.
Thank You