100% found this document useful (1 vote)
976 views

Type Conversion in C

Type conversion in C can be either implicit or explicit. Implicit type conversion is performed automatically by the compiler without user input, such as when variables of different data types are combined in an expression. Explicit type conversion requires a cast inserted by the user to convert a value from one type to another. Arrays in C are a collection of elements of the same type that can be accessed using indices, and they can be initialized at compile-time or run-time. Arrays can also be passed to functions either by value or by reference.

Uploaded by

suryavamsi
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
976 views

Type Conversion in C

Type conversion in C can be either implicit or explicit. Implicit type conversion is performed automatically by the compiler without user input, such as when variables of different data types are combined in an expression. Explicit type conversion requires a cast inserted by the user to convert a value from one type to another. Arrays in C are a collection of elements of the same type that can be accessed using indices, and they can be initialized at compile-time or run-time. Arrays can also be passed to functions either by value or by reference.

Uploaded by

suryavamsi
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 107

Type Conversion in C

• A type cast is basically a conversion from one


type to another. There are two types of type
conversion:
Implicit Type Conversion
• Implicit Type Conversion Also known as ‘automatic
type conversion’.Done by the compiler on its own,
without any external trigger from the user.
• Generally takes place when in an expression more
than one data type is present. In such condition type
conversion (type promotion) takes place to avoid lose
of data.
• All the data types of the variables are upgraded to the
data type of the variable with largest data type.
Implicit Type Conversion
• It is possible for implicit conversions to lose
information, signs can be lost (when signed is
implicitly converted to unsigned), and
overflow can occur (when long long is
implicitly converted to float)
Explicit Type Conversion
• This process is also called type casting and it
is user defined. Here the user can type cast the
result to make it of a particular data type.
• The syntax in C:
– (type) expression
DIFFERENCE BETWEEN TYPE CASTING AND
TYPE CONVERSION
• When the two types are compatible with each
other, then the conversion of one type to other
is done automatically by the compiler that is
cold type conversion .
• we can store a large data type into the other for
example we can not store a float into int
because a float is greater than int.
whereas, type casting is to be explicitly done
by the programmer.
DIFFERENCE BETWEEN TYPE CASTING AND
TYPE CONVERSION
Inbuilt Typecast Functions In C
• There are many inbuilt type casting functions
available in C language which performs data
type conversion from one type to another.
Mathematical Library Functions
• All C inbuilt functions which are declared in
math.h header file are given below.
• “math.h” header file supports all the
mathematical related functions in C language.
• All the arithmetic functions used in C
language are also.
LIST OF INBUILT C FUNCTIONS IN
MATH.H FILE:
• abs()
• floor()
• sin()
• cos()
• tan()
• exp()
• log()
• Sqrt()
• floor ( )

• This function returns the


nearest integer which is
less than or equal to the
argument passed to this
function.
• sqrt()
• sqrt( ) function in C is
used to find the square
root of the given
number.
• abs()
• abs( ) function in C
returns the absolute
value of an
integer. The absolute
value of a number is
always positive. Only
integer values are
supported in C.
• sin() cos() tan() exp() log()
• sin( ), cos( ) and tan( ) functions in C are used to
calculate sine, cosine and  tangent values.
• sinh( ), cosh( ) and tanh( ) functions are used to
calculate hyperbolic sine, cosine and tangent values.
• exp( ) function is used to calculate the exponential
“e” to the xth power. log( ) function is used to
calculates natural logarithm and log10( ) function is
used to calculates base 10 logarithm.
Interactive Input
• A standard task in C programming is to get
interactive input from the user; that is, to read
in a number or a string typed at the keyboard.
• One method is to use the function scanf.
• For example to get an integer, we might use
(#include is implied):
int answer; /* an integer chosen by the user */
scanf ("%d", &answer);
Assignment variation
• Sum=sum+10;
• Is a valid c expression
• The value of sum+10 is stored in variable sum
• Not a valid algebra equation
Assignment variation
#include<stdio.h>
Main()
{
int sum=25;
Printf(“the sum before variation%d”,sum);
Sum=sum+10;
Printf(“the sum after variation%d”,sum);
}
Assignment variation
• Assignment expression such as
• Sum=sum+10;
• Can be written by using following shortcut
operators.
• example
Sum=sum+10;
Can be written as.
Sum +=10;
inputting and outputting
• inputting and outputting data we use library
function .the important of these functions are
• getchar( ),
• putchar( ),
• scanf( ),
• printf( ),
• gets( ),
• puts( ).
getchar() function
• It is used to read a single character (char type)
from keyboard.
• The syntax is
char variable name = getchar( );
• Example:
char c;
c = getchar( );
getchar() function
#include<stdio.h>
Output:
int main() Enter character: a
{ Character entered: a
char c;
printf("Enter character: ");
c=getchar();
printf("Character entered: ");
putchar(c);
return(0);
}
Putchar() function
• It is used to display single character.
• The syntax is
putchar(char c);
– Example
char c;
c = ‘a’;
putchar(c);
Putchar() function
#include<stdio.h>
int main () Output:
{ ABCDEFGHIJKLMNOPQRSTUVWXYZ

char ch;
for(ch = 'A' ; ch <= 'Z' ; ch++)
{
putchar(ch);
}
return(0);
}
function - gets()
• reads a line from stdin and stores it into the string pointed
to by str. It stops when either the newline character is read
or when the end-of-file is reached, whichever comes first.
#include <stdio.h>
Output:
int main () Enter a string :hai what doing
{ You entered: hai what doing
char str[50];
printf("Enter a string : ");
gets(str);
printf("You entered: %s", str);
return(0);
}
function - puts()
• writes a string to stdout up to but not including the null character. A
newline character is appended to the output.
#include <stdio.h>
#include <string.h>
int main () { Output:
char str1[15]; HAI TO ALL
HOW ARE YOU
char str2[15];
strcpy(str1, "HAI TO ALL");
strcpy(str2, "HOW ARE YOU");
puts(str1);
puts(str2);
return(0);
}
Arrays
• An array is a collection of data that holds fixed
number of values of same type.
• For example:
– if you want to store marks of 100 students, you can
create an array for it.
– The size and type
of arrays cannot be
changed after its
declaration.
Arrays
• arrays are reffered to as structured data types.
An array is defined as finite ordered
collection of homogenous data, stored in
contiguous memory locations.
– finite means data range must be defined.
– ordered means data must be stored in continuous
memory addresses.
– homogenous means data must be of similar data
type.
Arrays
• Example where arrays are used,
– to store list of Employee or Student names,
– to store marks of students,
– or to store list of numbers or characters etc.
How to declare an array in C?
• Syntax:
– data_type array_name[array_size];
• Example :
– float mark[5];
• we declared an array, mark, of floating-point
type and size 5. Meaning, it can hold 5
floating-point values.
How to access them Elements of an
Array ?
• You can access elements of an array by indices.
• Arrays have 0 as the first index not 1. In this
example, mark[0]
• If the size of an array is n, to access the last
element, (n-1) index is used. In this example, mark[4]
• Suppose the starting address of mark[0] is 2120d.
Then, the next address, a[1], will be 2124d, address
of a[2] will be 2128d and so on.
• It's because the size of a float is 4 bytes.
How to initialize an array in C
programming?
• It's possible to initialize an array during
declaration.
• For example
int mark[5] = {19, 10, 8, 17, 9};
• Another method to initialize array during
declaration:
int mark[ ] = {19, 10, 8, 17, 9};
Compile time Array initialization
#include<stdio.h>
void main()
{
int i;
int arr[]={2,3,4}; // Compile time array initialization
for(i=0;i<3;i++)
{
printf("%d\t",arr[i]);
}
}
Runtime Array initialization
#include<stdio.h>
void main()
{
int arr[4];
int i,j;
printf("Enter array element");
for(i=0;i<4;i++)
{
scanf("%d",&arr[i]); //Run time array initialization
}
for(j=0;j<4;j++)
{
printf("%d\n",arr[j]);
}
}
How to insert and print array elements?
• int mark[5] = {19, 10, 8, 17, 9}

• // insert different value to third element


mark[2] = 9;

• // take input from the user and insert in third element


scanf("%d", &mark[2]);

• // print first element of an array


printf("%d", mark[0]);

• // print ith element of an array


printf("%d", mark[i-1]);
Program to find the average of n numbers
using arrays
#include<stdio.h>
int main()
{
int marks[10],i,n,sum=0,average;
printf("Enter n:");
scanf("%d",&n);
for(i=0;i<n;++i)
{
printf("Enter number%d:",i+1);
scanf("%d",&marks[i]);
sum+=marks[i];
}
average=sum/n;
printf("Average=%d",average);
return 0;
}
How to pass Array to a Function
• Declaring Function with array as a
parameter
– There are two possible ways
• using call by value and other
• by using call by reference.
Passing Arrays as Function 
Arguments in C
• If you want to pass a single-dimension array as
an argument in a function, you would have to
declare a formal parameter in one of following
three ways and all three declaration methods
produce similar results because each tells the
compiler that an integer pointer is going to be
received.
• Similarly, you can pass multi-dimensional
arrays as formal parameters.
Passing Arrays as Function 
Arguments in C
Way-1
Formal parameters as a sized array −
void myFunction(int param[10])
{
.
.
.
}
Passing Arrays as Function 
Arguments in C
#include<stdio.h>
#include<conio.h>
void modify(int a[3]); Output:
void main()
{
149
int arr[3]={1,2,3};
modify(arr);
for(i=0;i<3;i++)
printf("%d",arr[i]);
getch();
}
void modify(int a[3])
{
int i;
for(i=0;i<3;i++)
a[i] = a[i]*a[i];
}
Passing Arrays as Function 
Arguments in C
Way-2
Formal parameters as an unsized array −

void myFunction(int param[])


{
.
.
.
}
Formal parameters as an unsized array
#include<stdio.h>
float findAverage(int marks[]);
int main()
{
float avg;
int marks[]={99,90,96,93,95};
avg=findAverage(marks); // name of the array is passed as argument.
printf("Average marks=%.1f",avg);
return 0;
}

float findAverage(int marks[])


{
int i,sum=0;
float avg;
for(i=0;i<=4;i++)
{
sum+=marks[i];
}
avg=(sum/5);
return avg;
}
Passing Arrays as Function 
Arguments in C
Way-3
Formal parameters as a pointer −
void myFunction(int *param)
{
.
.
.
}
How to pass arrays to a function in C
Programming
• A single array element or an entire array can
be passed to a function like passing variable to
a function.
• This can be done for both one-dimensional
array or a multi-dimensional array.
How to pass arrays to a function in C
Programming
Passing an entire one-dimensional array to
a function
• While passing arrays as arguments to the
function, only the name of the array is passed
(,i.e, starting address of memory area is passed
as argument).
C program to find average age and display
the average age in main function.
Display Largest Element of an array
The program below computes the largest element of
an array without modifying the original array
Two-Dimensional Arrays
• An array of arrays is known as 2D array.
• The two dimensional (2D) array in C
programming is also known as matrix.
• A matrix can be represented as a table of rows
and columns.
Compile time Initializing Two-Dimensional
Arrays
• arrays may be initialized by specifying bracketed
values for each row. Following is an array with 3
rows and each row has 4 columns.
int a[3][4]={
{0,1,2,3} , /* initializers for row indexed by 0 */
{4,5,6,7} , /* initializers for row indexed by 1 */
{8,9,10,11} /* initializers for row indexed by 2 */
};
Or
int a[3][4] = {0,1,2,3,4,5,6,7,8,9,10,11};
Runtime initialization of a two dimensional
Array
#include<stdio.h> for(i=0;i<3;i++)
void main() {
{ for(j=0;j<4;j++)
int arr[3][4]; {
int i,j,k; printf("%d",arr[i][j]);
}
printf("Enter array element");
}
for(i=0;i<3;i++) }
{
for(j=0;j<4;j++)
{
scanf("%d",&arr[i][j]);
}
}
Accessing Two-Dimensional Array
Elements
• An element in a two-dimensional array is accessed by using the subscripts, i.e.,
row index and column index of the array.
#include<stdio.h>
int main()
{
/* an array with 5 rows and 2 columns*/
int a[5][2]={{0,0},{1,2},{2,4},{3,6},{4,8}};
int i, j;
/* output each array element's value */
for(i=0;i<5;i++)
{
for(j=0;j<2;j++)
{
printf("a[%d][%d]:%d\n",i,j,a[i][j]);
}
}
return 0;
}
operations on matrix
• Matrices Addition :
The addition of two matrices A m*n and Bm*n gives a
matrix Cm*n. The elements of C are sum of
corresponding elements in A and B which can be
shown as:

cij = aij + bij


#include <stdio.h> // Adding Two matrices
int main() for(i=0;i<r;++i)
{ for(j=0;j<c;++j)
int r,c,a[100][100],b[100][100],sum[100][100],i,j; {
printf("Enter number of rows (between 1 and 100):"); sum[i][j]=a[i][j]+b[i][j];
scanf("%d",&r); }
printf("Enter number of columns (between 1 and 100):"); // Displaying the result
scanf("%d",&c);
printf("\nSum of two matrix is: \n\n");
printf("\nEnter elements of 1st matrix:\n");
for(i=0;i<r;++i)
for(i=0;i<r;++i)
for(j=0;j<c;++j)
for(j=0;j<c;++j)
{
{
printf("Enter element a%d%d:",i+1,j+1);
printf("%d ",sum[i][j]);
scanf("%d",&a[i][j]); if(j==c-1)
} {
printf("Enter elements of 2nd matrix:\n"); printf("\n\n");
for(i=0;i<r;++i) }
for(j=0;j<c; ++j) }
{
printf("Enter element a%d%d: ",i+1, j+1); return 0;
scanf("%d", &b[i][j]); }
}
Advantages of arrays
• It is better and convenient way of storing the data of same
datatype with same size.
• It allows us to store known number of elements in it.
• It allocates memory in contiguous memory locations for
its elements. It does not allocate any extra space/ memory
for its elements. Hence there is no memory overflow or
shortage of memory in arrays.
• Iterating the arrays using their index is faster compared to
any other methods like linked list etc.
• It allows to store the elements in any dimensional array -
supports multidimensional array.
Advantages of arrays
• It allows us to enter only fixed number of elements into it.
We cannot alter the size of the array once array is declared.
Hence if we need to insert more number of records than
declared then it is not possible. We should know array size at
the compile time itself.
• Inserting and deleting the records from the array would be
costly since we add / delete the elements from the array, we
need to manage memory space too.
• It does not verify the indexes while compiling the array. In
case there is any indexes pointed which is more than the
dimension specified, then we will get run time errors rather
than identifying them at compile time.
Explanation With Algorithm
1. Set K=1 and Loc=0
2. Repeat Steps 3 and 4
while K<=N
3. if key=LA[K], then Set
Loc=K,
print: Loc and Exit
4. Set K=K+1
5. if Loc=0 then Write:
Item in List
6. Exit
Sequence of Successful Search - 1
low high mid
search( 44 )
#1 0 8 4

 low  high 
mid   
 2

0 1 2 3 4 5 6 7 8

5 12 17 23 38 44 77 84 90

low mid high

38 < 44 low = mid+1 = 5


Sequence of Successful Search - 2
low high mid
search( 44 )
#1 0 8 4
#2 5 8 6
 low  high 
mid   
 2

0 1 2 3 4 5 6 7 8

5 12 17 23 38 44 77 84 90

low mid high


high = mid-1=5 44 < 77
Sequence of Successful Search - 3
low high mid
search( 44 )
#1 0 8 4
#2 5 8 6
 low  high 
#3 5 5 5 mid   
 2

0 1 2 3 4 5 6 7 8

5 12 17 23 38 44 77 84 90

Successful Search!! low high


44 == 44 mid
Sequence of Unsuccessful Search - 4
low high mid
search( 45 )
#1 0 8 4
#2 5 8 6
 low  high 
#3 5 5 5 mid   
 2
#4 6 5

0 1 2 3 4 5 6 7 8

5 12 17 23 38 44 77 84 90

Unsuccessful Search
high low
no more elements to search low > high
Strings
• Strings are actually one-dimensional array of
characters terminated by a null character '\0'.
Thus a null-terminated string contains the
characters that comprise the string followed by
a null.
S.N. Function & Purpose

strcpy(s1, s2);
1 Copies string s2 into string s1.

strcat(s1, s2);
2 Concatenates string s2 onto the end of string s1.

strlen(s1);
3 Returns the length of string s1.

strcmp(s1, s2);
4 Returns 0 if s1 and s2 are the same; less than 0 if s1<s2; greater than 0 if
s1>s2.
strlen() function
• strlen( ) function counts the number of
characters in a given string and returns the
integer value.
• It stops counting the character when null
character is found. Because, null character
indicates the end of the string in C.
• Example: length of the string “freshers” is
determined by strlen( ) function as below.
Length of this string 8 is displayed as output.
strlen() function
Calculate Length of String without Using
strlen() Function
strcat() function
• strcat( ) function in C language concatenates
two given strings.
• It concatenates source string at the end of
destination string. 
• Syntax.
char * strcat (char * destination, const char * source );
• Example:
strcat ( str2, str1 ); – str1 is concatenated at the end of str2.
strcat ( str1, str2 ); – str2 is concatenated at the end of str1.
strcat() function
Concatenate Two Strings Without Using
strcat()
strcpy() function
• If destination string length is less than source
string, entire source string value won’t be
copied into destination string.
• For example, consider destination string length
is 20 and source string length is 30.
• Then, only 20 characters from source string
will be copied into destination string and
remaining 10 characters won’t be copied and
will be truncated.
strcpy() function
Copy String Manually Without Using
strcpy()
strcmp() function
• strcmp( ) function in C compares two given
strings and returns zero if they are same.
• If length of string1<string2, it returns < 0 value. 
• If length of string1 > string2, it returns > 0 value.
• Syntaxstrcmp()
int strcmp ( const char * str1, const char * str2 );
• strcmp( ) function is case sensitive. i.e, “A” and
“a” are treated as different characters.
strcmp() function
• The strcmp() compares two strings character by character.
• If the first character of two strings are equal, next character of
two strings are compared.
• This continues until the corresponding characters of two
strings are different or a null character '\0' is reached.
strcmp() function
Compare two String Manually Without
Using strcmp()
Passing strings to function:
• As strings are character arrays, so we can pass
strings to function in a same way we pass an
array to a function.
#include<stdio.h>
void printStr(char str[])
{
printf("String is:%s",str);
}
int main()
{
// declare and initialize string
char str[]="jntukucev";
// print string by passing string
// to a different function
printStr(str);
return 0;
}
Dynamic memory allocation
• The process of allocating memory during program
execution is called dynamic memory allocation.
• The process of allocating memory at runtime is known
as dynamic memory allocation. Library routines known
as memory management functions are used for allocating
and freeing memory during execution of a program. These
functions are defined in stdlib.h header file.
• Dynamic memory management refers to manual memory
management.
• This allows you to obtain more memory when required and
release it when not necessary.
Dynamic memory allocation
• C language offers 4 dynamic memory
allocation functions. They are,
– malloc()
– calloc()
– realloc()
– free()
Dynamic memory allocation
Function Description
malloc() allocates requested size of bytes and returns a void pointer
pointing to the first byte of the allocated space

calloc() allocates space for an array of elements, initialize them to zero


and then returns a void pointer to the memory

free releases previously allocated memory


realloc modify the size of previously allocated space
MALLOC() FUNCTION
• malloc() function is used to allocate space in
memory during the execution of the program.
• malloc() does not initialize the memory
allocated during execution.  It carries garbage
value.
• malloc() function returns null pointer if it
couldn’t able to allocate requested amount of
memory.
MALLOC() FUNCTION
• Syntax of malloc()
malloc (number *sizeof(int));
• The malloc() function returns a pointer to an
area of memory with size of byte size.
• If the space is insufficient, allocation fails and
returns NULL pointer.
Pointer
• Pointers in C language is a variable that stores/points the address of
another variable.
• A Pointer in C is used to allocate memory dynamically i.e. at run time. 
• The pointer variable might be belonging to any of the data type such as
int, float, char, double, short etc.
• Pointer Syntax :
data_type *var_name; 
• Example :
int *p;  
char *p;
• Where, * is used to denote that “p” is pointer variable and not a normal
variable.
• dynamic memory allocation, cannot be performed without using pointers
Pointer
• Normal variable stores the value whereas pointer variable stores the
address of the variable.
• The content of the C pointer always be a whole number i.e. address.
• Always C pointer is initialized to null, i.e. int *p = null.
• The value of null pointer is 0.
• & symbol is used to get the address of the variable.
• * symbol is used to get the value of the variable that the pointer is
pointing to.
• If a pointer in C is assigned to NULL, it means it is pointing to
nothing.
• The size of any pointer is 2 byte .
reasons for pointers use
• They are used for several reasons, such as:
• Strings
• Dynamic memory allocation
• Sending function arguments by reference
• Building complicated data structures
• Pointing to functions
• Building special data structures (i.e. Tree,
Tries, etc...)
How to Use Pointers
• A pointer is a variable whose value is the
address of another variable, i.e., direct address
of the memory location.
(a) We define a pointer variable, 
(b) assign the address of a variable to a pointer
and 
(c) finally access the value at the address
available in the pointer variable.
Declaration of Pointer variable
• Data type of a pointer must be same as the
data type of the variable to which the pointer
variable is pointing. void type pointer works
with all data types, but is not often used.
• int* pc; creates a pointer pc and int c; creates a normal variable c.
Since pc and c are both not initialized, pointer pc points to either no address or a
random address. Likewise, variable c is assigned an address but contains a
random/garbage value.
• c=22; assigns 22 to the variable c, i.e.,22 is stored in the memory location of
variable c.
Note that, when printing &c (address of c), we use %u rather than %d since address
is usually expressed as an unsigned integer (always positive).
• pc=&c; assigns the address of variable to c to the pointer pc.
When printing, you see value of pc is the same as the address of c and the content
of pc (*pc) is 22 as well.
• c=11; assigns 11 to variable c.
We assign a new value to c to see its effect on pointer pc.
• Since, pointer pc points to the same address as c, value pointed by pointer pc is 11
as well.
Printing the address and content of pc shows the updated content as 11.
• *pc=2; changes the contents of the memory location pointed by pointer pc to 2.
Since the address of pointer pc is same as address of c, value of c also changes to 2.
Initialization of Pointer variable
• Pointer Initialization is the process of assigning
address of a variable to a pointer variable.
• Pointer variable can only contain address of a
variable of the same data type.
• In C language address operator & is used to
determine the address of a variable.
• The & returns the address of the variable
associated with it.
A pointer variable is therefore nothing but a variable which holds an address of
some other variable. And the value of a pointer variable gets stored in another
memory location.
Benefits of using pointers
• Pointers are more efficient in handling Arrays and
Structures.
• Pointers allow references to function and thereby
helps in passing of function as arguments to other
functions.
• It reduces length of the program and its execution
time as well.
• It allows C language to support Dynamic
Memory management.
Pointers as Function Argument
• Pointer as a function parameter is used to hold
addresses of arguments passed during function
call.
• This is also known as call by reference. When
a function is called by reference any change
made to the reference variable will effect the
original variable.
Swapping two numbers using Pointer
Functions returning Pointer variables

• A function can also return a pointer to the


calling function.
• In this case you must be careful, because local
variables of function doesn't live outside the
function. They have scope only inside the
function.
• Hence if you return a pointer connected to a
local variable, that pointer will be pointing to
nothing when the function ends.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy