SlideShare a Scribd company logo
Programming in C & Data Structures: 15PCD13/23
Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, Govt SKSJTI, Bengaluru Page 1
1) Arrays in C:
 A normal variable can hold only one value.
 Sometime it is required to use a single name for group of data items.
 Such a construct of programming language which stores and organizes a set of data item is called
data structure.
 Different types of data structure are arrays, stacks, queues, linked lists, structures, trees and files etc.
 An array can be defined as an ordered list of homogenous data elements.
 May be of type int, float, char or double.
 All these elements are stored in consecutive memory locations.
 An array is described by a single name or an identifier and each element in an array is referenced by a
subscript (or an index) enclosed in a pair of square brackets.
 For array, memory allocated is static. i.e., if array size is changed during the program execution, it may
result in garbage value or memory overflow condition.
 Array must be declared before it appears in C Program
 Arrays are classified into two types:
o One-dimensional
o Multi-dimensional
 The dimensionality of an array is determined by the number of subscript present in the given
array. i.e., the number of brackets written after the array name.
Programming in C & Data Structures: 15PCD13/23
Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, Govt SKSJTI, Bengaluru Page 2
 If there is only one subscript, then it is called a one-dimensional array.
 If the number of subscripts is more than one, then such arrays are called multi-dimensional arrays.
 Dimension is determined by the number of pairs of square
 brackets placed after the array name.
 Example:
 array1[ ] -> One-Dimensional Array
 array2[ ][ ] -> Two-dimensional Array
 array3[ ] [ ] [ ] -> Three-dimensional Array
You can also declare an array without explicitly indicating the size. Compiler will decide & allocate memory
accordingly. int array[ ] = { 100, 200, 300, 400};
Example program:
#include <stdio.h>
#define MONTHS 12
void main( )
{
int days[ ]= {31,28,31,30,31,30,31,31,30,31,30,31};
int index;
for (index = 0; index < MONTHS; index++)
printf("Month %d has %2d days.n", index +1, days[index]);
}
/* Program to read marks of students and display using Array*/
Programming in C & Data Structures: 15PCD13/23
Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, Govt SKSJTI, Bengaluru Page 3
/* Program to count the no of positive, negative numbers and zeros in an array*/
#include <stdio.h>
#include <conio.h>
void main( )
{
int a[50],n, count_neg=0,count_pos=0, count_zero=0; k;
printf(“Enter the size of the arrayn”);
scanf(“%d”,&n);
printf(“Enter the elements of the arrayn”);
for(k=0;k < n;k++)
scanf(“%d”,&a[k]); // reading elements of the array
for(k=0;k < n;k++) // to count positive, negative numbers and zeros
{
if(a[k] < 0)
count_neg++;
else if ( a[k]>0)
count_pos++;
else
count_zero++;
}
printf(“There are %d negative numbers in the arrayn”, count_neg);
printf(“There are %d positive numbers in the arrayn”, count_pos);
getch( );
}
Programming in C & Data Structures: 15PCD13/23
Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, Govt SKSJTI, Bengaluru Page 4
Searching techniques:
finding the location of given element.
two approaches to search:
•Linear Search
•Binary Search
Linear Search: (Sequential Search)
–Sequentially scan the array, comparing each array item with the searched value one by one.
–If a match is found; return the location of the matched element; otherwise return –1
Programming in C & Data Structures: 15PCD13/23
Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, Govt SKSJTI, Bengaluru Page 5
Another program for Linear Search:
Binary Search
value
•If equal, match found
•If key < middle, looks in first half of array
•If key > middle, looks in last half
•Repeat
n
> number of elements
•Ex: 30 element array takes at most 5 steps ,i.e., 25
> 30, so at most 5 steps
Programming in C & Data Structures: 15PCD13/23
Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, Govt SKSJTI, Bengaluru Page 6
/* Binary Search C program*/
Sorting Techniques: Bubble sort, Insertion Sort, Selection Sort, Quick sort, Radix sort
etc
Programming in C & Data Structures: 15PCD13/23
Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, Govt SKSJTI, Bengaluru Page 7
Programming in C & Data Structures: 15PCD13/23
Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, Govt SKSJTI, Bengaluru Page 8
Two Dimensional Array:
Programming in C & Data Structures: 15PCD13/23
Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, Govt SKSJTI, Bengaluru Page 9
Ex: The following initializes a 2-d array named X[4][3]:
int X[4] [3] = { {1, 2, 3} , { 4, 5, 6} , {7, 8, 9} , {10, 11, 12} };
Also can be written as:
int X[4] [3] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 };
– is equivalent to
X[0][0] = 1; // element at 0th
row & 0th
column
X[0][1] = 2;
X[0][2] = 3;
X[1][0] = 4; // element at 1st
row & 0th
column
...
X[3][2] = 12
Declaring 2-d arrays:
Programming in C & Data Structures: 15PCD13/23
Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, Govt SKSJTI, Bengaluru Page 10
Matrix Multiplication program in C:
Programming in C & Data Structures: 15PCD13/23
Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, Govt SKSJTI, Bengaluru Page 11
2) Strings in C:
 Strings in C are simply arrays of characters.
o Example: char s [10];
 This is a ten (10) element array that can hold a character string consisting of  9 characters.
 This is because C does not know where the end of an array is at run time.
o By convention, C uses a NULL character '0' to terminate all strings in its library
functions
 For example:
o char str [10] = {'u', 'n', 'I', 'x', '0'};
 It’s the string terminator (not the size of the array) that determines the length of the string.
 The first element of any array in C is at index 0. The second is at index 1, and so on ...
Example declaration:
char s[10];
s[0] = 'h'; s[1] = 'e’; s[2] = 'l'; s[3] = 'l'; s[4] = 'o’; s[5] = '0';
Initializing char array:
– char s[10] ="unix"; /* s[4] is '0'; */
– char s[ ] ="unix"; /* s has 5 elements; array size not indicated*/
Programming in C & Data Structures: 15PCD13/23
Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, Govt SKSJTI, Bengaluru Page 12
A string can be read in or written out using the input/output statements.
Reading string
 scanf() with the %s format specification.
 gets() function
 getchar() function several times.
Writing string
 printf() with the %s format specification.
 puts() function
 putchar() function several times
Programming in C & Data Structures: 15PCD13/23
Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, Govt SKSJTI, Bengaluru Page 13
1) Printing a string literal with printf ():
char msg[ ] = "A message to display";
printf ("%sn", msg);
printf expects to receive a string as an additional parameter when it sees %s in the format string
printf knows how much to print out because of the NULL character at the end of all strings.
– When it finds a 0, it knows to stop.
2) printing using puts ()
The puts function is a much simpler output function than printf for string printing.
Prototype of puts is defined in stdio.h
int puts(const char * str)
– This is more efficient than printf, because your program doesn't need to analyze the
format string at run-time.
For example:
char name[ ] = "The world of programming n";
puts (name);
Output on the screen:
The world of programming
3) Reading a string using scanf function
To read a string include:
– %s scans up to but not including the “next” white space character
– %ns scans the next n characters or up to the next white space character, whichever
comes first
Example:
scanf ("%s%s%s", s1, s2, s3);
scanf ("%2s%2s%2s", s1, s2, s3);
– Note: No ampersand(&) with scanf when inputting strings into character arrays!
4) Reading a string using gets
gets( ) gets a line from the standard input.
The prototype is defined in stdio.h
char *gets(char *str)
– str is a pointer to the space where gets will store the line to, or a character array.
– Returns NULL upon failure. Otherwise, it returns str.
char city[100];
printf("Enter a line:n");
gets(city);
puts("Your input is:n");
puts(city);
Difference between gets and scanf (“%s”):
gets reads an entire line from standard input. But scanf only reads what you tell it to. i..e, you told
scanf to read just a single %s, which means just a group of non-whitespace characters. So, it quits
reading from input, when it encounters the first white-space character.
– gets () reads an entire line of text from the keyboard
– scanf("%s",…) reads until the next whitespace character
Difference between puts and printf (“%s”):
puts() can be preferred for printing a string because it is generally less expensive (implementation of
puts() is generally simpler), and if the string has formatting characters like ‘%’, then printf() would
give unexpected results. Also, if str is a user input string, then use of printf() might cause security
issues. Also note that puts() moves the cursor to next line, i.e., automatically appends a new line after
printing.
Programming in C & Data Structures: 15PCD13/23
Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, Govt SKSJTI, Bengaluru Page 14
Example Programs on Strings:
/* Example program on strings using for loop */
#include<stdio.h>
#include<conio.h>
void main()
{
char a[ ]="ECE DEPARTMENT";
int i=0;
clrscr( );
for(i=0;i<=15;i++)
{
printf("%c",a[i]);
} // end of for loop
getch( );
}
/* Example program on strings using while loop */
#include<stdio.h>
#include<conio.h>
void main()
{
char a[30]="ECE DEPARTMENT";
int i=0;
clrscr( );
while(a[i]!='0')
{
printf("%c",a[i]);
i++;
} // end of while loop
getch( );
}
/* Example prog using printf (“%s”) function */
#include<stdio.h>
#include<conio.h>
void main()
{
char a[ ]="CIVIL DEPARTMENT";
clrscr();
printf("%s",a);
getch();
}
/* Example prog using puts function */
#include<stdio.h>
#include<conio.h>
void main()
{
char a[ ]="CIVIL DEPARTMENT";
clrscr ( );
puts (a);
getch();
}
Programming in C & Data Structures: 15PCD13/23
Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, Govt SKSJTI, Bengaluru Page 15
/* program to find and count the occurrence of characters in a string */
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char text[25]="c programming is good";
int i, m=0,p=0,r=0;
clrscr();
for(i=0;i<=25;i++)
{
if(text[i]=='m')
++m;
if(text[i]=='r')
++r;
if(text[i]=='o')
++p;
}
printf("n'm' found in text = %d times",m);
printf("n'r' found in text = %d times",r);
printf("n'o' found in text = %d times",p);
getch();
}
C Supports a number of string handling functions.
Header File - string.h
Standard Library functions in string.h header file:
S.no String functions Description
1 strcat (s1, s2 ) Concatenates s2 at the end of s1 and returns s1. (s1 is now s1+s2)
2 strncat (s1, s2, n ) appends n characters of string s2 to string s1 and returns s1.
3 strcpy (s1, s2 ) Copies s2 into s1 and returns s1. i.e., s1 is replaced by s2.
4 strncpy (s1,s2,n ) copies n characters from s2 to s1. Returns s1.
5 strlen (str) gives the length of str, not counting the NULL character.
6 strcmp (s1,s2 )
Compares S1 and S2 for equality.(ASCII values are compared) Returns 0 if
s1 is same as s2, positive value if s1>s2, negative value if s1<s2
Programming in C & Data Structures: 15PCD13/23
Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, Govt SKSJTI, Bengaluru Page 16
7 strcmpi ( )
Same as strcmp() function. But, this function neglects the case of the
character. “A” and “a” are treated as same.
8 strchr ( s1) Returns pointer to first occurrence of char in s1.
9 strrchr ( ) last occurrence of given character in a string is found
10 strstr ( ) Returns pointer to first occurrence of str2 in str1.
11 strrstr ( ) Returns pointer to last occurrence of str2 in str1.
12 strdup ( ) duplicates the string
13 strlwr ( ) converts string to lowercase
14 strupr ( ) converts string to uppercase
15 strrev ( ) reverses the given string
16 strset ( ) sets all character in a string to given character
17 strnset ( ) It sets the portion of characters in a string to given character
18 strtok ( ) tokenizing given string using delimiter
Some of the string handling functions are:
1) strcmp()- function
The function compares two strings character by character and return one of the three values: -1,0,1
C strings can be compared for equality or inequality. If they are equal - they are ASCII identical.
If they are unequal, the comparison function will return an int that is interpreted as:
< 0 : str1 is less than str2
0: str1 is equal to str2
> 0: str1 is greater than str2
Syntax:
a) int strcmp (char *str1, char *str2) ;
Does an ASCII comparison one char at a time until a difference is found between two chars
Return value is as stated before
If both strings reach a '0' at the same time, they are considered equal.
b) int strncmp (char *str1, char * str2, size_t n);
Compares n chars of str1 and str2
– Continues until n chars are compared or the end of str1or str2 is encountered
Also have strcasecmp() and strncasecmp() which do the same as above, but ignore case in letters.
2) strcpy()- function
 The function used to copy one string to the other.
 Syntax - strcpy(string1,string2)
 The Content on string1 will be overwritten by content of string2.
3) strcat()- function
 The function used to concatenate.
 Syntax - strcat(string1,string2)
 String string2 is appended to the end of string1.
4) strlen()- function
 The function returns the numbers of characters in the string. The string length does not include
the ’0’(null) character.
 Syntax - strlen(string1)
 string1 is one dimension array of characters.
5) strncmp()- function
Programming in C & Data Structures: 15PCD13/23
Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, Govt SKSJTI, Bengaluru Page 17
 The function used to compare the first n character of string.
 Syntax - strncmp(string1,string2,n)
 -1 - if ASCII value of the charecter of first string is less than of the second.
 0 - if both strings are same
 1 - if both strings are different
6) strlwr()- function
 The function is used to convert any uppercase letters in a string to its equivalent lowercase.
 Syntax - strlwr(string1)
 string1 is one dimension array of characters.
7) strncat()- function
 The function used to append first n characters of the second string at the end of the first string.
 Syntax - strncat(string1,string2,n)
8) strchr()- function
 The function seraches for for specified character in a given string.
 Returns NULL if the desired character is not found in the string.
 Syntax - strncat(string, desired-char)
/* illustration of strlen() Library function */
#include<stdio.h>
#include<conio.h>
void main()
{
char text[20];
int length;
clrscr();
printf("Type the Text n");
gets(text);
length=strlen(text);
printf("Length of string = %d", length);
getch();
}
/* illustration of strcpy() Library function */
#include<stdio.h>
#include<conio.h>
void main()
{
char str1[20], str2[20];
int length;
clrscr();
printf("Enter 1st stringn");
gets(str1);
printf("Enter 2nd stringn");
gets(str2);
printf("n1st String is --->t%s",str1);
printf("n2nd String is --->t%s",str2);
strcpy(str1,str2);
printf("nn1st String after strcpy() is --->t%s",str1);
getch();
}
Programming in C & Data Structures: 15PCD13/23
Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, Govt SKSJTI, Bengaluru Page 18
/* illustration of strcmp() Library function */
#include<stdio.h>
#include<conio.h>
void main()
{
char str1[20], str2[20];
int result;
clrscr();
printf("Enter 1st stringn");
gets(str1);
printf("Enter 2nd stringn");
gets(str2);
printf("n1st String is --->t%s",str1);
printf("n2nd String is --->t%s",str2);
result=strcmp(str1,str2);
//In case of match result will be ZERO otherwise NON ZERO
printf("nnResult after Comparing is %d",result);
if (result==0)
printf (“n strings are same n”);
else
printf (“ strings %s and %s are differentn”, str1, str2);
getch();
}
/* illustration of strcat() Library function */
#include<stdio.h>
#include<conio.h>
void main()
{
char str1[20],str2[20];
int length;
clrscr();
printf("Enter 1st stringn");
gets(str1);
printf("Enter 2nd stringn");
gets(str2);
printf("n1st String is --->t%s",str1);
printf("n2nd String is --->t%s",str2);
strcat(str1,str2);
printf("nnString after strcat() is --->t%s",str1);
getch();
}
/* illustration of strrev() Library function */
#include<stdio.h>
#include<conio.h>
void main()
{
char str1[20], str2[20];
int length;
clrscr();
printf("Enter 1st stringn");
gets(str1);
printf("n1st String is --->t%s",str1);
Programming in C & Data Structures: 15PCD13/23
Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, Govt SKSJTI, Bengaluru Page 19
str2 = strrev(str1);
printf("nnString after strrev() is --->t%s",str2);
if (str2==str1)
printf (“n given string %s is palindrome”, str1);
else
printf (“n given string %s is not palindrome”, str1);
getch();
}
/* Program to check for string palindrome without using strrev()*/
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char str[10];
int i=0,j,test;
clrscr();
printf("Enter the word t");
gets(str);
j=strlen(str)-1;
while(i<=j)
{
if(str[i]==str[j])
test=1;
else
{
test=0;
break;
}
i++;
j--;
} // end of while
if(test==1)
printf("nword %s is palindrome", str);
else
printf("n word %s is not palindrome", str);
getch();
}
/* program to count the number of words in a sentence */
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char text[30];
int count=0,i=0;
clrscr();
printf("Enter the line of textn");
printf("Give one space after each wordn");
gets(text);
while(text[i++]!='0')
{
Programming in C & Data Structures: 15PCD13/23
Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, Govt SKSJTI, Bengaluru Page 20
if (text[i]==32 || text[i]=='0')
count++;
}
printf("Number of words in line = %d",count);
getch();
}
/* program to illustrate strcpy and strcat */
#include <string.h>
#include <stdio.h>
int main() {
char str1[27] = "abc";
char str2[100];
printf("%dn",strlen(str1));
strcpy(str2,str1);
puts(str2);
puts("n");
strcat(str2,str1);
puts(str2);
getch();
}
/* program to find the occurrence of a character in a string literal */
/* Searching Strings
Example use of strchr: */
#include<stdio.h>
#include<string.h>
int main() {
char ch='b', buf[80];
strcpy(buf, "The quick brown fox");
if (strchr(buf,ch) == NULL)
printf ("The character %c was not found.n",ch);
else
printf ("The character %c was found at position %dn", ch, strchr(buf,ch)-buf+1);
}
Programming in C & Data Structures: 15PCD13/23
Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, Govt SKSJTI, Bengaluru Page 21
Programming in C & Data Structures: 15PCD13/23
Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, Govt SKSJTI, Bengaluru Page 22
/* Palindrome program using library function in string.h */
Programming in C & Data Structures: 15PCD13/23
Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, Govt SKSJTI, Bengaluru Page 23
/* String Palindrome Program using Pointers */
/* String reverse using Pointers */
Programming in C & Data Structures: 15PCD13/23
Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, Govt SKSJTI, Bengaluru Page 24
Converting Strings to Numbers:
Contained in <stdlib.h> and are often used
int atoi (char *ptr);
– Takes a character string and converts it to an integer.
– White space and + or - are OK.
– Starts at beginning and continues until something non-convertible is encountered.
Some examples:
String Value returned
"157" 157
"-1.6" -1
"+50x" 50
"twelve" 0
"x506" 0
long atol (char *ptr) ;
– Same as atoi except it returns a long.
double atof (char * str);
– Handles digits 0-9.
– A decimal point.
– An exponent indicator (e or E).
– If no characters are convertible a 0 is returned.
Examples:
– String Value returned
"12" 12.000000
"-0.123" -0.123000
"123E+3" 123000.000000
"123.1e-5" 0.001231
Programming in C & Data Structures: 15PCD13/23
Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, Govt SKSJTI, Bengaluru Page 25
3) Functions in C:
De_nition
 A Function is a self-contained block of statement that perform a coherent task of some kind.
 Every C Program can be thought of as a collection of these functions.
 Function is a set of instruction to carryout a particular task.
 Function after its execution may/may not return a value.
 Generally, the function are classified into standard function and user-defined functions.
 The Standard function are also called library function or built-in function.
 All standard functions, such as sqrt(), abs(), log(), sin(), printf() etc. are provided in the library
of function.
 But, most of the application need other functions than those available in the library; these are
known as user-defined functions.
 A function receives zero or more parameters from the calling program, performs a specific
task, and returns zero or one value.
 A function is invoked by its name and parameters.
o No two functions can have the same name in your C program.
o The communication between the function and invoker is through the parameters and the
return value.
 A function is independent:
o It is “completely” self-contained.
o It can be called at any places of your code and can be ported to another program.
 Functions make programs reusable and readable
Advantages of Modular Programming using Functions:
 Reduction in code redundancy
 Enabling code reuse
 Better readability
 Information Hiding
 Improved debugging and testing
 Improved maintainability
Programming in C & Data Structures: 15PCD13/23
Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, Govt SKSJTI, Bengaluru Page 26
User Defined Function:
Defined by user at the time of writing the program.
There are three aspects of user-defined functions:
 Function Declaration, also known as function Prototype
 Function Definition
 Function call or function invocation
1) Function Declaration:
Introduces the function name, function return type, and function parameters to the program.
The declaration is terminated with a semicolon.
A function must be declared before it is used.
Syntax of Function Prototype:
return_type function_name (datatype1 name1, datatype2 name2, ..., typen namen);
parameter list
return type can be void, int, float or double.
function_name is any variable name.
datatype can be int, char, float or double. Parameter list can have 0 or more parameters. All
parameters need not be of same data type.
2) Function Definition:
also known as function implementation, means composing a function. Every Function definition
consists of two Parts: Header of the function and Body of the function.
Programming in C & Data Structures: 15PCD13/23
Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, Govt SKSJTI, Bengaluru Page 27
The general form of header of a function is:
Note: The header of function is not terminated with a semicolon.
Body of the function:
{
st1;
st2;
….
return (value) //not required if return_type is void
}
The body of a function consist of a set of statements enclosed within braces.
The return statement is used to return the result of the computations done in the called function and/or
to return the program control back to the calling function.
3) Function Call:
Syntax:
function_name (parameter1, parameter2 , …);
variable_name = function_name (parameter1, parameter2 , …);
Function call always terminated with a semicolon.
Local Variables
int func1 (int y)
{
int a, b = 10;
float rate;
double cost = 12.55;
}
Those variables declared “within” the function are considered “local variables”. They can only be used
inside the function they were declared in, and not elsewhere.
return_type function_name (datatype1 name1, datatype2 name2, ...,typen namen)
Programming in C & Data Structures: 15PCD13/23
Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, Govt SKSJTI, Bengaluru Page 28
To return a value from a C function, you must explicitly return it with a return statement.
Syntax:
return<expression>;
The expression can be any valid C expression that resolves to the type defined in the function header.
 Type conversion may occur if type does not match.
 Multiple return statements can be used within a single function (eg: inside an “if-else”
statement…)
Programming in C & Data Structures: 15PCD13/23
Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, Govt SKSJTI, Bengaluru Page 29
Example C programs using User defined functions:
// function prototype (declaration)
int max(int a, int b);
int main()
{
int x;
x = max(5,8); // function call
x = max(x,7); // function call
}
int max(int a, int b) // function body
{
return a>b?a:b;
} // end of function
#include<stdio.h>
int twice(int x) // function body
{
x=x+x;
return x;
}
int main()
{
int x=10,y;
y=twice(x); // function call
printf("%d,%dn",x,y);
}
Programming in C & Data Structures: 15PCD13/23
Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, Govt SKSJTI, Bengaluru Page 30
Abhineet
Programming in C & Data Structures: 15PCD13/23
Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, Govt SKSJTI, Bengaluru Page 31
a) function with NO arguments and NO return value
b) function with arguments and NO return value
Programming in C & Data Structures: 15PCD13/23
Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, Govt SKSJTI, Bengaluru Page 32
c) function with return value and NO arguments
d) function with arguments and return value
Programming in C & Data Structures: 15PCD13/23
Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, Govt SKSJTI, Bengaluru Page 33
//Function with no input-output ( NO return value & NO arguments)
#include<stdio.h>
printsum(); //Function deceleration
void main() //main function, the master function
{ ………
printsum(); //Function Call
………. // from function, control returns to this statement in main
} // end of main
printsum() //definition of function printsum
{
printf("Sum of 2 and 3 is %d",2+3);
} // end of function
//Function with input and No output (with arguments but NO return value)
#include<stdio.h>
void printsum(int, int); //Function deceleration
main() //main function, the master function
{
int a,b;
printf("Enter values of a & bt");
scanf("%d %d", &a,&b);
printsum(a,b); //Function Call with actual arguments a, b
} // end of main
printsum(int x, int y) //definition of function printsum
{ // formal arguments x, y get the value of a,b
printf("Sum of %d and %d is %d",x,y,x+y);
} // end of function
Parameter Passing Methods in C:
Programming in C & Data Structures: 15PCD13/23
Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, Govt SKSJTI, Bengaluru Page 34
1) Call (Pass)-by-Value Method:
Note: all the examples discussed above are examples of “call-by-value” method.
 In this method, the calling function passes the values of “actual arguments” to the called
function. However, these values are copied into “formal arguments” declared in the function
body. So, the changes made to these “local variables” inside the function, do not affect the
actual variables in the calling function.
 This is useful, when few parameters are to be passed.
Example: Swapping two integers using “Call-by-value” method
Programming in C & Data Structures: 15PCD13/23
Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, Govt SKSJTI, Bengaluru Page 35
Programming in C & Data Structures: 15PCD13/23
Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, Govt SKSJTI, Bengaluru Page 36
2) Call (pass)-by-Reference method:
Programming in C & Data Structures: 15PCD13/23
Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, Govt SKSJTI, Bengaluru Page 37
Swapping two integers using “Call-by-Reference” method:
Programming in C & Data Structures: 15PCD13/23
Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, Govt SKSJTI, Bengaluru Page 38
Programming in C & Data Structures: 15PCD13/23
Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, Govt SKSJTI, Bengaluru Page 39
Passing array as parameter to Function:
#include <stdio.h>
double getAverage(int arr[ ], int size); /* function declaration */
int main ()
{
int balance[5] = {1000, 2, 3, 17, 50}; /* an int array with 5 elements */
double avg;
/* pass pointer to the array as an argument */
avg = getAverage( balance, 5 ) ; // function call with array as argument
/* output the returned value */
printf( "Average value is: %f ", avg ); // avg value is returned from function
return 0;
} // end of main
double getAverage(int arr[], int size) // function definition
{
int i; // local variable declarations
double avg;
double sum;
for (i = 0; i < size; ++i)
{ sum += arr[i];
}
avg = sum / size;
return avg;
} // end of function
/* Passing Array as Parameter to a function */
void mysort (int a[ ], int len); // function declaration
void main()
{
int i;
int tab[10] = {3,6,3,5,9,2,4,5,6,0};
for(i=0;i<10;i++)
printf("%d ",tab[i]);
printf("n");
mysort(tab,10); // function call with Array name as argument
for(i=0;i<10;i++)
printf("%d ",tab[i]); // display sorted array
printf ("n");
} // end of main
void mysort(int a[ ], int size) // function definition (body)
{
int i, j, x; // function to sort the array
for(i=0; i<size; i++)
{
for(j=i; j>0; j--)
{
Programming in C & Data Structures: 15PCD13/23
Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, Govt SKSJTI, Bengaluru Page 40
if(a[ j ] < a[ j-1])
{ /* Change the order of a[ j ] and a[ j-1] */
x=a[ j ]; a[ j ]=a[ j-1]; a[j-1]=x;
} // end of if
} // end of inner for loop
} // end of outer for loop
} // end of function
Passing String as Argument to a function:
Programming in C & Data Structures: 15PCD13/23
Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, Govt SKSJTI, Bengaluru Page 41
Programming in C & Data Structures: 15PCD13/23
Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, Govt SKSJTI, Bengaluru Page 42
Recursive Functions:
Factorial Program: a) without function
Factorial Program: b) with function
Programming in C & Data Structures: 15PCD13/23
Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, Govt SKSJTI, Bengaluru Page 43
Factorial Program: c) with Recursive function
// This function returns the sum of natural numbers 1 to num
int sum (int num)
{
int result;
if (num == 1)
result = 1;
else
result = num + sum (n-1);
return result;
}
Programming in C & Data Structures: 15PCD13/23
Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, Govt SKSJTI, Bengaluru Page 44
2) Fibonacci Series program: a) without function
b) Fibonacci series using Recursion
important drawbacks of recursion
_ Function-Call Overhead
_ Memory-Management Issues
Programming in C & Data Structures: 15PCD13/23
Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, Govt SKSJTI, Bengaluru Page 45
Standard Library Functions in ctype.h
Programming in C & Data Structures: 15PCD13/23
Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, Govt SKSJTI, Bengaluru Page 46
Programming in C & Data Structures: 15PCD13/23
Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, Govt SKSJTI, Bengaluru Page 47
Programming in C & Data Structures: 15PCD13/23
Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, Govt SKSJTI, Bengaluru Page 48

More Related Content

PPS
C programming session 04
PPTX
C Programming Unit-3
PPS
C programming session 02
PPS
C programming session 01
PPS
C programming session 05
PPT
PDF
Strings in c mrs.sowmya jyothi
PDF
Functions, Strings ,Storage classes in C
C programming session 04
C Programming Unit-3
C programming session 02
C programming session 01
C programming session 05
Strings in c mrs.sowmya jyothi
Functions, Strings ,Storage classes in C

What's hot (20)

PDF
C programming & data structure [arrays & pointers]
PDF
C programming & data structure [character strings & string functions]
PPS
C programming session 09
PPTX
Computer programming(CP)
PPT
14. Query Optimization in DBMS
PPT
Data type in c
PPT
Lecture 21 22
PDF
Introduction to c++ ppt
PDF
2 expressions (ppt-2) in C++
PPTX
Chapter 2.datatypes and operators
PPTX
Concept of c data types
PPTX
C Programming Unit-2
DOC
Bt0065
PPS
C programming session 05
PPT
Query optimisation
PDF
An Introduction To C++Templates
PPTX
Object Oriented Programming with C++
PDF
Arrays in c_language
PPTX
Programming construction tools
C programming & data structure [arrays & pointers]
C programming & data structure [character strings & string functions]
C programming session 09
Computer programming(CP)
14. Query Optimization in DBMS
Data type in c
Lecture 21 22
Introduction to c++ ppt
2 expressions (ppt-2) in C++
Chapter 2.datatypes and operators
Concept of c data types
C Programming Unit-2
Bt0065
C programming session 05
Query optimisation
An Introduction To C++Templates
Object Oriented Programming with C++
Arrays in c_language
Programming construction tools
Ad

Similar to Lk module3 (20)

PPTX
Array , Structure and Basic Algorithms.pptx
PPTX
Arrays & Strings
DOCX
Array &strings
PPTX
C-Arrays & Strings (computer programming).pptx
PPTX
C (PPS)Programming for problem solving.pptx
PPT
Array THE DATA STRUCTURE. ITS THE STRUCT
PPTX
c unit programming arrays in detail 3.pptx
PDF
DATA STRUCTURE ARRAY AND STRUCTURES CHAPTER 2
PDF
DATA STRUCTRES ARRAY AND STRUCTURES CHAPTER 2
PPTX
FALLSEM2022-23_BCSE202L_TH_VL2022230103292_Reference_Material_I_08-08-2022_C_...
PPTX
C language
PPTX
ARRAY's in C Programming Language PPTX.
PPTX
Console I/o & basics of array and strings.pptx
PPTX
2 Arrays & Strings.pptx
PDF
Unit ii data structure-converted
PPTX
MY STRING AND ARRAY PROGRAM for all student
PPSX
Esoft Metro Campus - Certificate in c / c++ programming
PDF
C for Java programmers (part 3)
PPTX
C data types, arrays and structs
PPTX
3.ArraysandPointers.pptx
Array , Structure and Basic Algorithms.pptx
Arrays & Strings
Array &strings
C-Arrays & Strings (computer programming).pptx
C (PPS)Programming for problem solving.pptx
Array THE DATA STRUCTURE. ITS THE STRUCT
c unit programming arrays in detail 3.pptx
DATA STRUCTURE ARRAY AND STRUCTURES CHAPTER 2
DATA STRUCTRES ARRAY AND STRUCTURES CHAPTER 2
FALLSEM2022-23_BCSE202L_TH_VL2022230103292_Reference_Material_I_08-08-2022_C_...
C language
ARRAY's in C Programming Language PPTX.
Console I/o & basics of array and strings.pptx
2 Arrays & Strings.pptx
Unit ii data structure-converted
MY STRING AND ARRAY PROGRAM for all student
Esoft Metro Campus - Certificate in c / c++ programming
C for Java programmers (part 3)
C data types, arrays and structs
3.ArraysandPointers.pptx
Ad

More from Krishna Nanda (16)

PDF
Python regular expressions
PDF
Python dictionaries
PDF
Python lists
PDF
Python-Tuples
PDF
Python- strings
PDF
Python-files
PDF
Computer Communication Networks- Introduction to Transport layer
PDF
Computer Communication Networks- TRANSPORT LAYER PROTOCOLS
PDF
COMPUTER COMMUNICATION NETWORKS -IPv4
PDF
COMPUTER COMMUNICATION NETWORKS-R-Routing protocols 2
PDF
Computer Communication Networks-Routing protocols 1
PDF
Computer Communication Networks-Wireless LAN
PDF
Computer Communication Networks-Network Layer
PDF
Lk module4 structures
PDF
Lk module4 file
PDF
Lk module5 pointers
Python regular expressions
Python dictionaries
Python lists
Python-Tuples
Python- strings
Python-files
Computer Communication Networks- Introduction to Transport layer
Computer Communication Networks- TRANSPORT LAYER PROTOCOLS
COMPUTER COMMUNICATION NETWORKS -IPv4
COMPUTER COMMUNICATION NETWORKS-R-Routing protocols 2
Computer Communication Networks-Routing protocols 1
Computer Communication Networks-Wireless LAN
Computer Communication Networks-Network Layer
Lk module4 structures
Lk module4 file
Lk module5 pointers

Recently uploaded (20)

PDF
Vision Prelims GS PYQ Analysis 2011-2022 www.upscpdf.com.pdf
PDF
Weekly quiz Compilation Jan -July 25.pdf
PDF
RTP_AR_KS1_Tutor's Guide_English [FOR REPRODUCTION].pdf
PPTX
A powerpoint presentation on the Revised K-10 Science Shaping Paper
PDF
احياء السادس العلمي - الفصل الثالث (التكاثر) منهج متميزين/كلية بغداد/موهوبين
DOC
Soft-furnishing-By-Architect-A.F.M.Mohiuddin-Akhand.doc
PPTX
ELIAS-SEZIURE AND EPilepsy semmioan session.pptx
PDF
What if we spent less time fighting change, and more time building what’s rig...
PPTX
Virtual and Augmented Reality in Current Scenario
PPTX
Unit 4 Computer Architecture Multicore Processor.pptx
PDF
A GUIDE TO GENETICS FOR UNDERGRADUATE MEDICAL STUDENTS
PDF
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
PDF
medical_surgical_nursing_10th_edition_ignatavicius_TEST_BANK_pdf.pdf
PDF
MBA _Common_ 2nd year Syllabus _2021-22_.pdf
PDF
Computing-Curriculum for Schools in Ghana
PDF
advance database management system book.pdf
PPTX
History, Philosophy and sociology of education (1).pptx
PDF
HVAC Specification 2024 according to central public works department
PDF
Trump Administration's workforce development strategy
PPTX
TNA_Presentation-1-Final(SAVE)) (1).pptx
Vision Prelims GS PYQ Analysis 2011-2022 www.upscpdf.com.pdf
Weekly quiz Compilation Jan -July 25.pdf
RTP_AR_KS1_Tutor's Guide_English [FOR REPRODUCTION].pdf
A powerpoint presentation on the Revised K-10 Science Shaping Paper
احياء السادس العلمي - الفصل الثالث (التكاثر) منهج متميزين/كلية بغداد/موهوبين
Soft-furnishing-By-Architect-A.F.M.Mohiuddin-Akhand.doc
ELIAS-SEZIURE AND EPilepsy semmioan session.pptx
What if we spent less time fighting change, and more time building what’s rig...
Virtual and Augmented Reality in Current Scenario
Unit 4 Computer Architecture Multicore Processor.pptx
A GUIDE TO GENETICS FOR UNDERGRADUATE MEDICAL STUDENTS
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
medical_surgical_nursing_10th_edition_ignatavicius_TEST_BANK_pdf.pdf
MBA _Common_ 2nd year Syllabus _2021-22_.pdf
Computing-Curriculum for Schools in Ghana
advance database management system book.pdf
History, Philosophy and sociology of education (1).pptx
HVAC Specification 2024 according to central public works department
Trump Administration's workforce development strategy
TNA_Presentation-1-Final(SAVE)) (1).pptx

Lk module3

  • 1. Programming in C & Data Structures: 15PCD13/23 Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, Govt SKSJTI, Bengaluru Page 1 1) Arrays in C:  A normal variable can hold only one value.  Sometime it is required to use a single name for group of data items.  Such a construct of programming language which stores and organizes a set of data item is called data structure.  Different types of data structure are arrays, stacks, queues, linked lists, structures, trees and files etc.  An array can be defined as an ordered list of homogenous data elements.  May be of type int, float, char or double.  All these elements are stored in consecutive memory locations.  An array is described by a single name or an identifier and each element in an array is referenced by a subscript (or an index) enclosed in a pair of square brackets.  For array, memory allocated is static. i.e., if array size is changed during the program execution, it may result in garbage value or memory overflow condition.  Array must be declared before it appears in C Program  Arrays are classified into two types: o One-dimensional o Multi-dimensional  The dimensionality of an array is determined by the number of subscript present in the given array. i.e., the number of brackets written after the array name.
  • 2. Programming in C & Data Structures: 15PCD13/23 Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, Govt SKSJTI, Bengaluru Page 2  If there is only one subscript, then it is called a one-dimensional array.  If the number of subscripts is more than one, then such arrays are called multi-dimensional arrays.  Dimension is determined by the number of pairs of square  brackets placed after the array name.  Example:  array1[ ] -> One-Dimensional Array  array2[ ][ ] -> Two-dimensional Array  array3[ ] [ ] [ ] -> Three-dimensional Array You can also declare an array without explicitly indicating the size. Compiler will decide & allocate memory accordingly. int array[ ] = { 100, 200, 300, 400}; Example program: #include <stdio.h> #define MONTHS 12 void main( ) { int days[ ]= {31,28,31,30,31,30,31,31,30,31,30,31}; int index; for (index = 0; index < MONTHS; index++) printf("Month %d has %2d days.n", index +1, days[index]); } /* Program to read marks of students and display using Array*/
  • 3. Programming in C & Data Structures: 15PCD13/23 Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, Govt SKSJTI, Bengaluru Page 3 /* Program to count the no of positive, negative numbers and zeros in an array*/ #include <stdio.h> #include <conio.h> void main( ) { int a[50],n, count_neg=0,count_pos=0, count_zero=0; k; printf(“Enter the size of the arrayn”); scanf(“%d”,&n); printf(“Enter the elements of the arrayn”); for(k=0;k < n;k++) scanf(“%d”,&a[k]); // reading elements of the array for(k=0;k < n;k++) // to count positive, negative numbers and zeros { if(a[k] < 0) count_neg++; else if ( a[k]>0) count_pos++; else count_zero++; } printf(“There are %d negative numbers in the arrayn”, count_neg); printf(“There are %d positive numbers in the arrayn”, count_pos); getch( ); }
  • 4. Programming in C & Data Structures: 15PCD13/23 Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, Govt SKSJTI, Bengaluru Page 4 Searching techniques: finding the location of given element. two approaches to search: •Linear Search •Binary Search Linear Search: (Sequential Search) –Sequentially scan the array, comparing each array item with the searched value one by one. –If a match is found; return the location of the matched element; otherwise return –1
  • 5. Programming in C & Data Structures: 15PCD13/23 Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, Govt SKSJTI, Bengaluru Page 5 Another program for Linear Search: Binary Search value •If equal, match found •If key < middle, looks in first half of array •If key > middle, looks in last half •Repeat n > number of elements •Ex: 30 element array takes at most 5 steps ,i.e., 25 > 30, so at most 5 steps
  • 6. Programming in C & Data Structures: 15PCD13/23 Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, Govt SKSJTI, Bengaluru Page 6 /* Binary Search C program*/ Sorting Techniques: Bubble sort, Insertion Sort, Selection Sort, Quick sort, Radix sort etc
  • 7. Programming in C & Data Structures: 15PCD13/23 Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, Govt SKSJTI, Bengaluru Page 7
  • 8. Programming in C & Data Structures: 15PCD13/23 Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, Govt SKSJTI, Bengaluru Page 8 Two Dimensional Array:
  • 9. Programming in C & Data Structures: 15PCD13/23 Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, Govt SKSJTI, Bengaluru Page 9 Ex: The following initializes a 2-d array named X[4][3]: int X[4] [3] = { {1, 2, 3} , { 4, 5, 6} , {7, 8, 9} , {10, 11, 12} }; Also can be written as: int X[4] [3] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 }; – is equivalent to X[0][0] = 1; // element at 0th row & 0th column X[0][1] = 2; X[0][2] = 3; X[1][0] = 4; // element at 1st row & 0th column ... X[3][2] = 12 Declaring 2-d arrays:
  • 10. Programming in C & Data Structures: 15PCD13/23 Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, Govt SKSJTI, Bengaluru Page 10 Matrix Multiplication program in C:
  • 11. Programming in C & Data Structures: 15PCD13/23 Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, Govt SKSJTI, Bengaluru Page 11 2) Strings in C:  Strings in C are simply arrays of characters. o Example: char s [10];  This is a ten (10) element array that can hold a character string consisting of  9 characters.  This is because C does not know where the end of an array is at run time. o By convention, C uses a NULL character '0' to terminate all strings in its library functions  For example: o char str [10] = {'u', 'n', 'I', 'x', '0'};  It’s the string terminator (not the size of the array) that determines the length of the string.  The first element of any array in C is at index 0. The second is at index 1, and so on ... Example declaration: char s[10]; s[0] = 'h'; s[1] = 'e’; s[2] = 'l'; s[3] = 'l'; s[4] = 'o’; s[5] = '0'; Initializing char array: – char s[10] ="unix"; /* s[4] is '0'; */ – char s[ ] ="unix"; /* s has 5 elements; array size not indicated*/
  • 12. Programming in C & Data Structures: 15PCD13/23 Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, Govt SKSJTI, Bengaluru Page 12 A string can be read in or written out using the input/output statements. Reading string  scanf() with the %s format specification.  gets() function  getchar() function several times. Writing string  printf() with the %s format specification.  puts() function  putchar() function several times
  • 13. Programming in C & Data Structures: 15PCD13/23 Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, Govt SKSJTI, Bengaluru Page 13 1) Printing a string literal with printf (): char msg[ ] = "A message to display"; printf ("%sn", msg); printf expects to receive a string as an additional parameter when it sees %s in the format string printf knows how much to print out because of the NULL character at the end of all strings. – When it finds a 0, it knows to stop. 2) printing using puts () The puts function is a much simpler output function than printf for string printing. Prototype of puts is defined in stdio.h int puts(const char * str) – This is more efficient than printf, because your program doesn't need to analyze the format string at run-time. For example: char name[ ] = "The world of programming n"; puts (name); Output on the screen: The world of programming 3) Reading a string using scanf function To read a string include: – %s scans up to but not including the “next” white space character – %ns scans the next n characters or up to the next white space character, whichever comes first Example: scanf ("%s%s%s", s1, s2, s3); scanf ("%2s%2s%2s", s1, s2, s3); – Note: No ampersand(&) with scanf when inputting strings into character arrays! 4) Reading a string using gets gets( ) gets a line from the standard input. The prototype is defined in stdio.h char *gets(char *str) – str is a pointer to the space where gets will store the line to, or a character array. – Returns NULL upon failure. Otherwise, it returns str. char city[100]; printf("Enter a line:n"); gets(city); puts("Your input is:n"); puts(city); Difference between gets and scanf (“%s”): gets reads an entire line from standard input. But scanf only reads what you tell it to. i..e, you told scanf to read just a single %s, which means just a group of non-whitespace characters. So, it quits reading from input, when it encounters the first white-space character. – gets () reads an entire line of text from the keyboard – scanf("%s",…) reads until the next whitespace character Difference between puts and printf (“%s”): puts() can be preferred for printing a string because it is generally less expensive (implementation of puts() is generally simpler), and if the string has formatting characters like ‘%’, then printf() would give unexpected results. Also, if str is a user input string, then use of printf() might cause security issues. Also note that puts() moves the cursor to next line, i.e., automatically appends a new line after printing.
  • 14. Programming in C & Data Structures: 15PCD13/23 Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, Govt SKSJTI, Bengaluru Page 14 Example Programs on Strings: /* Example program on strings using for loop */ #include<stdio.h> #include<conio.h> void main() { char a[ ]="ECE DEPARTMENT"; int i=0; clrscr( ); for(i=0;i<=15;i++) { printf("%c",a[i]); } // end of for loop getch( ); } /* Example program on strings using while loop */ #include<stdio.h> #include<conio.h> void main() { char a[30]="ECE DEPARTMENT"; int i=0; clrscr( ); while(a[i]!='0') { printf("%c",a[i]); i++; } // end of while loop getch( ); } /* Example prog using printf (“%s”) function */ #include<stdio.h> #include<conio.h> void main() { char a[ ]="CIVIL DEPARTMENT"; clrscr(); printf("%s",a); getch(); } /* Example prog using puts function */ #include<stdio.h> #include<conio.h> void main() { char a[ ]="CIVIL DEPARTMENT"; clrscr ( ); puts (a); getch(); }
  • 15. Programming in C & Data Structures: 15PCD13/23 Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, Govt SKSJTI, Bengaluru Page 15 /* program to find and count the occurrence of characters in a string */ #include<stdio.h> #include<conio.h> #include<string.h> void main() { char text[25]="c programming is good"; int i, m=0,p=0,r=0; clrscr(); for(i=0;i<=25;i++) { if(text[i]=='m') ++m; if(text[i]=='r') ++r; if(text[i]=='o') ++p; } printf("n'm' found in text = %d times",m); printf("n'r' found in text = %d times",r); printf("n'o' found in text = %d times",p); getch(); } C Supports a number of string handling functions. Header File - string.h Standard Library functions in string.h header file: S.no String functions Description 1 strcat (s1, s2 ) Concatenates s2 at the end of s1 and returns s1. (s1 is now s1+s2) 2 strncat (s1, s2, n ) appends n characters of string s2 to string s1 and returns s1. 3 strcpy (s1, s2 ) Copies s2 into s1 and returns s1. i.e., s1 is replaced by s2. 4 strncpy (s1,s2,n ) copies n characters from s2 to s1. Returns s1. 5 strlen (str) gives the length of str, not counting the NULL character. 6 strcmp (s1,s2 ) Compares S1 and S2 for equality.(ASCII values are compared) Returns 0 if s1 is same as s2, positive value if s1>s2, negative value if s1<s2
  • 16. Programming in C & Data Structures: 15PCD13/23 Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, Govt SKSJTI, Bengaluru Page 16 7 strcmpi ( ) Same as strcmp() function. But, this function neglects the case of the character. “A” and “a” are treated as same. 8 strchr ( s1) Returns pointer to first occurrence of char in s1. 9 strrchr ( ) last occurrence of given character in a string is found 10 strstr ( ) Returns pointer to first occurrence of str2 in str1. 11 strrstr ( ) Returns pointer to last occurrence of str2 in str1. 12 strdup ( ) duplicates the string 13 strlwr ( ) converts string to lowercase 14 strupr ( ) converts string to uppercase 15 strrev ( ) reverses the given string 16 strset ( ) sets all character in a string to given character 17 strnset ( ) It sets the portion of characters in a string to given character 18 strtok ( ) tokenizing given string using delimiter Some of the string handling functions are: 1) strcmp()- function The function compares two strings character by character and return one of the three values: -1,0,1 C strings can be compared for equality or inequality. If they are equal - they are ASCII identical. If they are unequal, the comparison function will return an int that is interpreted as: < 0 : str1 is less than str2 0: str1 is equal to str2 > 0: str1 is greater than str2 Syntax: a) int strcmp (char *str1, char *str2) ; Does an ASCII comparison one char at a time until a difference is found between two chars Return value is as stated before If both strings reach a '0' at the same time, they are considered equal. b) int strncmp (char *str1, char * str2, size_t n); Compares n chars of str1 and str2 – Continues until n chars are compared or the end of str1or str2 is encountered Also have strcasecmp() and strncasecmp() which do the same as above, but ignore case in letters. 2) strcpy()- function  The function used to copy one string to the other.  Syntax - strcpy(string1,string2)  The Content on string1 will be overwritten by content of string2. 3) strcat()- function  The function used to concatenate.  Syntax - strcat(string1,string2)  String string2 is appended to the end of string1. 4) strlen()- function  The function returns the numbers of characters in the string. The string length does not include the ’0’(null) character.  Syntax - strlen(string1)  string1 is one dimension array of characters. 5) strncmp()- function
  • 17. Programming in C & Data Structures: 15PCD13/23 Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, Govt SKSJTI, Bengaluru Page 17  The function used to compare the first n character of string.  Syntax - strncmp(string1,string2,n)  -1 - if ASCII value of the charecter of first string is less than of the second.  0 - if both strings are same  1 - if both strings are different 6) strlwr()- function  The function is used to convert any uppercase letters in a string to its equivalent lowercase.  Syntax - strlwr(string1)  string1 is one dimension array of characters. 7) strncat()- function  The function used to append first n characters of the second string at the end of the first string.  Syntax - strncat(string1,string2,n) 8) strchr()- function  The function seraches for for specified character in a given string.  Returns NULL if the desired character is not found in the string.  Syntax - strncat(string, desired-char) /* illustration of strlen() Library function */ #include<stdio.h> #include<conio.h> void main() { char text[20]; int length; clrscr(); printf("Type the Text n"); gets(text); length=strlen(text); printf("Length of string = %d", length); getch(); } /* illustration of strcpy() Library function */ #include<stdio.h> #include<conio.h> void main() { char str1[20], str2[20]; int length; clrscr(); printf("Enter 1st stringn"); gets(str1); printf("Enter 2nd stringn"); gets(str2); printf("n1st String is --->t%s",str1); printf("n2nd String is --->t%s",str2); strcpy(str1,str2); printf("nn1st String after strcpy() is --->t%s",str1); getch(); }
  • 18. Programming in C & Data Structures: 15PCD13/23 Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, Govt SKSJTI, Bengaluru Page 18 /* illustration of strcmp() Library function */ #include<stdio.h> #include<conio.h> void main() { char str1[20], str2[20]; int result; clrscr(); printf("Enter 1st stringn"); gets(str1); printf("Enter 2nd stringn"); gets(str2); printf("n1st String is --->t%s",str1); printf("n2nd String is --->t%s",str2); result=strcmp(str1,str2); //In case of match result will be ZERO otherwise NON ZERO printf("nnResult after Comparing is %d",result); if (result==0) printf (“n strings are same n”); else printf (“ strings %s and %s are differentn”, str1, str2); getch(); } /* illustration of strcat() Library function */ #include<stdio.h> #include<conio.h> void main() { char str1[20],str2[20]; int length; clrscr(); printf("Enter 1st stringn"); gets(str1); printf("Enter 2nd stringn"); gets(str2); printf("n1st String is --->t%s",str1); printf("n2nd String is --->t%s",str2); strcat(str1,str2); printf("nnString after strcat() is --->t%s",str1); getch(); } /* illustration of strrev() Library function */ #include<stdio.h> #include<conio.h> void main() { char str1[20], str2[20]; int length; clrscr(); printf("Enter 1st stringn"); gets(str1); printf("n1st String is --->t%s",str1);
  • 19. Programming in C & Data Structures: 15PCD13/23 Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, Govt SKSJTI, Bengaluru Page 19 str2 = strrev(str1); printf("nnString after strrev() is --->t%s",str2); if (str2==str1) printf (“n given string %s is palindrome”, str1); else printf (“n given string %s is not palindrome”, str1); getch(); } /* Program to check for string palindrome without using strrev()*/ #include<stdio.h> #include<conio.h> #include<string.h> void main() { char str[10]; int i=0,j,test; clrscr(); printf("Enter the word t"); gets(str); j=strlen(str)-1; while(i<=j) { if(str[i]==str[j]) test=1; else { test=0; break; } i++; j--; } // end of while if(test==1) printf("nword %s is palindrome", str); else printf("n word %s is not palindrome", str); getch(); } /* program to count the number of words in a sentence */ #include<stdio.h> #include<conio.h> #include<string.h> void main() { char text[30]; int count=0,i=0; clrscr(); printf("Enter the line of textn"); printf("Give one space after each wordn"); gets(text); while(text[i++]!='0') {
  • 20. Programming in C & Data Structures: 15PCD13/23 Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, Govt SKSJTI, Bengaluru Page 20 if (text[i]==32 || text[i]=='0') count++; } printf("Number of words in line = %d",count); getch(); } /* program to illustrate strcpy and strcat */ #include <string.h> #include <stdio.h> int main() { char str1[27] = "abc"; char str2[100]; printf("%dn",strlen(str1)); strcpy(str2,str1); puts(str2); puts("n"); strcat(str2,str1); puts(str2); getch(); } /* program to find the occurrence of a character in a string literal */ /* Searching Strings Example use of strchr: */ #include<stdio.h> #include<string.h> int main() { char ch='b', buf[80]; strcpy(buf, "The quick brown fox"); if (strchr(buf,ch) == NULL) printf ("The character %c was not found.n",ch); else printf ("The character %c was found at position %dn", ch, strchr(buf,ch)-buf+1); }
  • 21. Programming in C & Data Structures: 15PCD13/23 Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, Govt SKSJTI, Bengaluru Page 21
  • 22. Programming in C & Data Structures: 15PCD13/23 Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, Govt SKSJTI, Bengaluru Page 22 /* Palindrome program using library function in string.h */
  • 23. Programming in C & Data Structures: 15PCD13/23 Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, Govt SKSJTI, Bengaluru Page 23 /* String Palindrome Program using Pointers */ /* String reverse using Pointers */
  • 24. Programming in C & Data Structures: 15PCD13/23 Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, Govt SKSJTI, Bengaluru Page 24 Converting Strings to Numbers: Contained in <stdlib.h> and are often used int atoi (char *ptr); – Takes a character string and converts it to an integer. – White space and + or - are OK. – Starts at beginning and continues until something non-convertible is encountered. Some examples: String Value returned "157" 157 "-1.6" -1 "+50x" 50 "twelve" 0 "x506" 0 long atol (char *ptr) ; – Same as atoi except it returns a long. double atof (char * str); – Handles digits 0-9. – A decimal point. – An exponent indicator (e or E). – If no characters are convertible a 0 is returned. Examples: – String Value returned "12" 12.000000 "-0.123" -0.123000 "123E+3" 123000.000000 "123.1e-5" 0.001231
  • 25. Programming in C & Data Structures: 15PCD13/23 Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, Govt SKSJTI, Bengaluru Page 25 3) Functions in C: De_nition  A Function is a self-contained block of statement that perform a coherent task of some kind.  Every C Program can be thought of as a collection of these functions.  Function is a set of instruction to carryout a particular task.  Function after its execution may/may not return a value.  Generally, the function are classified into standard function and user-defined functions.  The Standard function are also called library function or built-in function.  All standard functions, such as sqrt(), abs(), log(), sin(), printf() etc. are provided in the library of function.  But, most of the application need other functions than those available in the library; these are known as user-defined functions.  A function receives zero or more parameters from the calling program, performs a specific task, and returns zero or one value.  A function is invoked by its name and parameters. o No two functions can have the same name in your C program. o The communication between the function and invoker is through the parameters and the return value.  A function is independent: o It is “completely” self-contained. o It can be called at any places of your code and can be ported to another program.  Functions make programs reusable and readable Advantages of Modular Programming using Functions:  Reduction in code redundancy  Enabling code reuse  Better readability  Information Hiding  Improved debugging and testing  Improved maintainability
  • 26. Programming in C & Data Structures: 15PCD13/23 Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, Govt SKSJTI, Bengaluru Page 26 User Defined Function: Defined by user at the time of writing the program. There are three aspects of user-defined functions:  Function Declaration, also known as function Prototype  Function Definition  Function call or function invocation 1) Function Declaration: Introduces the function name, function return type, and function parameters to the program. The declaration is terminated with a semicolon. A function must be declared before it is used. Syntax of Function Prototype: return_type function_name (datatype1 name1, datatype2 name2, ..., typen namen); parameter list return type can be void, int, float or double. function_name is any variable name. datatype can be int, char, float or double. Parameter list can have 0 or more parameters. All parameters need not be of same data type. 2) Function Definition: also known as function implementation, means composing a function. Every Function definition consists of two Parts: Header of the function and Body of the function.
  • 27. Programming in C & Data Structures: 15PCD13/23 Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, Govt SKSJTI, Bengaluru Page 27 The general form of header of a function is: Note: The header of function is not terminated with a semicolon. Body of the function: { st1; st2; …. return (value) //not required if return_type is void } The body of a function consist of a set of statements enclosed within braces. The return statement is used to return the result of the computations done in the called function and/or to return the program control back to the calling function. 3) Function Call: Syntax: function_name (parameter1, parameter2 , …); variable_name = function_name (parameter1, parameter2 , …); Function call always terminated with a semicolon. Local Variables int func1 (int y) { int a, b = 10; float rate; double cost = 12.55; } Those variables declared “within” the function are considered “local variables”. They can only be used inside the function they were declared in, and not elsewhere. return_type function_name (datatype1 name1, datatype2 name2, ...,typen namen)
  • 28. Programming in C & Data Structures: 15PCD13/23 Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, Govt SKSJTI, Bengaluru Page 28 To return a value from a C function, you must explicitly return it with a return statement. Syntax: return<expression>; The expression can be any valid C expression that resolves to the type defined in the function header.  Type conversion may occur if type does not match.  Multiple return statements can be used within a single function (eg: inside an “if-else” statement…)
  • 29. Programming in C & Data Structures: 15PCD13/23 Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, Govt SKSJTI, Bengaluru Page 29 Example C programs using User defined functions: // function prototype (declaration) int max(int a, int b); int main() { int x; x = max(5,8); // function call x = max(x,7); // function call } int max(int a, int b) // function body { return a>b?a:b; } // end of function #include<stdio.h> int twice(int x) // function body { x=x+x; return x; } int main() { int x=10,y; y=twice(x); // function call printf("%d,%dn",x,y); }
  • 30. Programming in C & Data Structures: 15PCD13/23 Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, Govt SKSJTI, Bengaluru Page 30 Abhineet
  • 31. Programming in C & Data Structures: 15PCD13/23 Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, Govt SKSJTI, Bengaluru Page 31 a) function with NO arguments and NO return value b) function with arguments and NO return value
  • 32. Programming in C & Data Structures: 15PCD13/23 Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, Govt SKSJTI, Bengaluru Page 32 c) function with return value and NO arguments d) function with arguments and return value
  • 33. Programming in C & Data Structures: 15PCD13/23 Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, Govt SKSJTI, Bengaluru Page 33 //Function with no input-output ( NO return value & NO arguments) #include<stdio.h> printsum(); //Function deceleration void main() //main function, the master function { ……… printsum(); //Function Call ………. // from function, control returns to this statement in main } // end of main printsum() //definition of function printsum { printf("Sum of 2 and 3 is %d",2+3); } // end of function //Function with input and No output (with arguments but NO return value) #include<stdio.h> void printsum(int, int); //Function deceleration main() //main function, the master function { int a,b; printf("Enter values of a & bt"); scanf("%d %d", &a,&b); printsum(a,b); //Function Call with actual arguments a, b } // end of main printsum(int x, int y) //definition of function printsum { // formal arguments x, y get the value of a,b printf("Sum of %d and %d is %d",x,y,x+y); } // end of function Parameter Passing Methods in C:
  • 34. Programming in C & Data Structures: 15PCD13/23 Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, Govt SKSJTI, Bengaluru Page 34 1) Call (Pass)-by-Value Method: Note: all the examples discussed above are examples of “call-by-value” method.  In this method, the calling function passes the values of “actual arguments” to the called function. However, these values are copied into “formal arguments” declared in the function body. So, the changes made to these “local variables” inside the function, do not affect the actual variables in the calling function.  This is useful, when few parameters are to be passed. Example: Swapping two integers using “Call-by-value” method
  • 35. Programming in C & Data Structures: 15PCD13/23 Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, Govt SKSJTI, Bengaluru Page 35
  • 36. Programming in C & Data Structures: 15PCD13/23 Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, Govt SKSJTI, Bengaluru Page 36 2) Call (pass)-by-Reference method:
  • 37. Programming in C & Data Structures: 15PCD13/23 Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, Govt SKSJTI, Bengaluru Page 37 Swapping two integers using “Call-by-Reference” method:
  • 38. Programming in C & Data Structures: 15PCD13/23 Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, Govt SKSJTI, Bengaluru Page 38
  • 39. Programming in C & Data Structures: 15PCD13/23 Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, Govt SKSJTI, Bengaluru Page 39 Passing array as parameter to Function: #include <stdio.h> double getAverage(int arr[ ], int size); /* function declaration */ int main () { int balance[5] = {1000, 2, 3, 17, 50}; /* an int array with 5 elements */ double avg; /* pass pointer to the array as an argument */ avg = getAverage( balance, 5 ) ; // function call with array as argument /* output the returned value */ printf( "Average value is: %f ", avg ); // avg value is returned from function return 0; } // end of main double getAverage(int arr[], int size) // function definition { int i; // local variable declarations double avg; double sum; for (i = 0; i < size; ++i) { sum += arr[i]; } avg = sum / size; return avg; } // end of function /* Passing Array as Parameter to a function */ void mysort (int a[ ], int len); // function declaration void main() { int i; int tab[10] = {3,6,3,5,9,2,4,5,6,0}; for(i=0;i<10;i++) printf("%d ",tab[i]); printf("n"); mysort(tab,10); // function call with Array name as argument for(i=0;i<10;i++) printf("%d ",tab[i]); // display sorted array printf ("n"); } // end of main void mysort(int a[ ], int size) // function definition (body) { int i, j, x; // function to sort the array for(i=0; i<size; i++) { for(j=i; j>0; j--) {
  • 40. Programming in C & Data Structures: 15PCD13/23 Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, Govt SKSJTI, Bengaluru Page 40 if(a[ j ] < a[ j-1]) { /* Change the order of a[ j ] and a[ j-1] */ x=a[ j ]; a[ j ]=a[ j-1]; a[j-1]=x; } // end of if } // end of inner for loop } // end of outer for loop } // end of function Passing String as Argument to a function:
  • 41. Programming in C & Data Structures: 15PCD13/23 Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, Govt SKSJTI, Bengaluru Page 41
  • 42. Programming in C & Data Structures: 15PCD13/23 Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, Govt SKSJTI, Bengaluru Page 42 Recursive Functions: Factorial Program: a) without function Factorial Program: b) with function
  • 43. Programming in C & Data Structures: 15PCD13/23 Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, Govt SKSJTI, Bengaluru Page 43 Factorial Program: c) with Recursive function // This function returns the sum of natural numbers 1 to num int sum (int num) { int result; if (num == 1) result = 1; else result = num + sum (n-1); return result; }
  • 44. Programming in C & Data Structures: 15PCD13/23 Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, Govt SKSJTI, Bengaluru Page 44 2) Fibonacci Series program: a) without function b) Fibonacci series using Recursion important drawbacks of recursion _ Function-Call Overhead _ Memory-Management Issues
  • 45. Programming in C & Data Structures: 15PCD13/23 Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, Govt SKSJTI, Bengaluru Page 45 Standard Library Functions in ctype.h
  • 46. Programming in C & Data Structures: 15PCD13/23 Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, Govt SKSJTI, Bengaluru Page 46
  • 47. Programming in C & Data Structures: 15PCD13/23 Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, Govt SKSJTI, Bengaluru Page 47
  • 48. Programming in C & Data Structures: 15PCD13/23 Compiled & Edited by: Prof. L. Krishnananda, HOD, Dept of ECE, Govt SKSJTI, Bengaluru Page 48