Pythhon Cu 2
Pythhon Cu 2
*
3
Character Arrays and Strings
char C[8] = { 'a', 'b', 'h', 'i', 'j', 'i', 't', '\0' };
• C[0] gets the value 'a', C[1] the value 'b', and so on. The last (7th)
location receives the null character ‘\0’
• Null-terminated (last character is ‘\0’) character arrays are also called
strings
• Strings can be initialized in an alternative way. The last declaration is
equivalent to:
• char C[8] = "abhijit";
• The trailing null character is missing here. C automatically puts it at the
end if you define it like this
• Note also that for individual characters, C uses single quotes, whereas
for strings, it uses double quotes *
3
Reading strings: %s format
void main()
{
char name[25];
scanf("%s", name);
printf("Name = %s \n", name);
}
6
String functions
• strlen : finds the length of a string
• strcat : concatenates one string at the end of
another
• strcmp : compares two strings lexicographically
• strcpy : copies one string to another
7
strlen()
9
strcmp()
int strcmp (const char *s1, int strcmp(char *s1, const char *s2)
{
const char *s2); for (;*s1!=‘\0’&&*s2!=‘\0’; s1++,s2++)
Two strings are passed as {
arguments. An integer is if (*s1>*s2) return 1;
returned that is less than, if (*s2>*s1) return -1;
}
equal to, or greater than 0, if (*s1 != ‘\0’) return 1;
depending on whether s1 is if (*s2 != ‘\0’) return -1;
lexicographically less than, return 0;
equal to, or greater than s2. }
10
strcpy()
int main()
{
Output
char s1[ ] = "beautiful big sky country",
s2[ ] = "how now brown cow"; 25
printf("%d\n",strlen (s1)); 9
printf("%d\n",strlen (s2+8)); -1
printf("%d\n", strcmp(s1,s2)); big sky country
printf("%s\n",s1+10);
beautiful brown cows!
strcpy(s1+10,s2+8);
printf("%s\n", s1);
return 0;
}
12
C gets() function
• The gets() function enables the user to enter some characters followed
by the enter key. All the characters entered by the user get stored in a
character array. The null character is added to the array to make it a
string. Example
#include<stdio.h>
void main ()
{
Syntax char s[30];
char[] gets(char[]); printf("Enter the string? ");
gets(s);
printf("You entered %s",s);
}
Output:
Enter the string?
javatpoint is the best
You entered javatpoint is the best
13
C puts() function
• The puts() function is used to print the string on the console which is
previously read by using gets() or scanf() function. The puts() function
returns an integer value representing the number of characters being
printed on the console.
Example
#include<stdio.h>
Syntax #include <string.h>
int puts(char[]) int main(){
char name[50]; Output:
printf("Enter your name: "); Enter your name: Sonoo Jaiswal
gets(name); //reads string from user Your name is: Sonoo Jaiswal
printf("Your name is: ");
puts(name); //displays string
return 0;
} 14
Linear Search
• Linear search is a sequential searching algorithm where we
start from one end and check every element of the list until the
desired element is found. It is the simplest searching algorithm.
•( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
•( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
•( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
•( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
17
Bubble Sort
/* Function to print an array */
// C program for implementation of Bubble sort void printArray(int arr[], int size)
#include <stdio.h> {
void swap(int* xp, int* yp) int i;
{ for (i = 0; i < size; i++)
int temp = *xp; printf("%d ", arr[i]);
*xp = *yp; printf("\n");
*yp = temp; }
}
// A function to implement bubble sort // Driver program to test above functions
void bubbleSort(int arr[], int n) int main()
{ {
int i, j; int arr[] = { 64, 34, 25, 12, 22, 11, 90 };
for (i = 0; i < n - 1; i++) int n = sizeof(arr) / sizeof(arr[0]);
bubbleSort(arr, n);
// Last i elements are already in place printf("Sorted array: \n");
for (j = 0; j < n - i - 1; j++) printArray(arr, n);
if (arr[j] > arr[j + 1]) return 0;
swap(&arr[j], &arr[j + 1]); }
}
18
FUNCTIONS -INTRODUCTION
• C allows programmers to define their own functions for carrying out various individual tasks.
• In this lesson we will cover the creation and utilization of such user-defined functions.
• Function is a self-contained block of program that performs a particular task.
• Every C program is collection of functions.
• Function is a complete and independent program which is used (or invoked or called) by the main
program or subprograms.
• Thus, a C program can be modularized through the intelligent use of such functions.
19
INTRODUCTION
• For example many programs require a particular group of instructions to be accessed repeatedly from several
different places within a program.
• The repeated instruction can be placed within a single function, which can then be accessed whenever it is
needed.
20
TYPES OF FUNCTION
• C functions can be classified into two categories, namely library functions and user-defined functions.
• main() is an example of user-defined functions.
• printf() and scanf() belong to the category of library functions.
• The main distinction between these two categories is that library functions are not required to be written by the
programmers whereas a user-defined function has to be developed by the user at the time of writing a program.
21
TYPES OF FUNCTION
24
Figure 6.3 Structure of
function in C 25
CREATING FIRST USER-DEFINED
FUNCTION
26
Figure 6.4
GENERAL FORM OF FUNCTION
• Before defining your own user-defined function, it is necessary to declare the function globally.
• By declaring the function, we are informing the compiler about the return type, name and parameter of the
function that we are going to use in our program.
return_type function_name(argument1,argument2,…);
27
FUNCTION DECLARATION
• Tells the return type
• Tells the name of the function
• Tells how many arguments are needed
• Tells the types of the arguments
• Tells the formal parameter names
• Formal parameters are like placeholders for the actual arguments used when the function is called
• Formal parameter names can be any valid identifier
Example:
28
FUNCTION DEFINITION
• When the function will be called, compiler will look for the definition of function inside the source code in order to
give you the desirable output.
29
FUNCTION DEFINITION
• If the compiler is unable to find the function definition, then the compile time error will be generated.
32
TYPES OF USER-DEFINED
FUNCTIONS
• Function can be divided into 4 categories:
• A function with no arguments and no return value
• A function with no arguments and a return value
• A function with an argument or arguments and returning no value
• A function with arguments and returning a values
33
EXAMPLE 1
Figure 6.11
Program 4 37
EXAMPLE 2
40
CALL BY VALUE
• It copies the actual value of an argument into the formal parameter of the function.
• Changes made to the parameter inside the function have no effect on the argument.
• By default, C programming language uses call by value method to pass arguments.
• In general, this means that code within a function cannot alter the arguments used to call the function.
• Consider the function swap() definition as follows.
41
CALL BY VALUE- EXAMPLE 1
43
CALL BY VALUE- EXAMPLE 2
45
CALL BY REFERENCE
• Copies the address of an argument into the formal parameter.
• Inside the function, the address is used to access the actual argument used in the call.
• This means that changes made to the parameter affect the passed argument.
• To pass the value by reference, argument pointers are passed to the functions just like any other value.
46
CALL BY REFERENCE
50
RECURSIVE FUNCTION
• The process of calling a function by itself is called recursion.
• The function which calls itself is called recursive function.
• Recursion is used to solve various mathematical problems by dividing it into smaller problems.
• This method of solving a problem is called Divide and Conquer.
• In programming, it is used to divide complex problem into simpler ones and solving them individually.
52
CONS/PRONS
• Recursion is more elegant and requires few variables which make program clean.
• Recursion can be used to replace complex nesting code by dividing the problem into same problem of its sub-
type.
• In other hand, it is hard to think the logic of a recursive function.
• It is also difficult to debug the code containing recursion.
53
exit() function
The function exit() is used to terminate the calling function immediately without executing further
processes. As exit() function calls, it terminates processes. It is declared in “stdlib.h” header file. It does
not return anything.
Here is the syntax of exit() in C language,
void exit(int status_value);
Here,
status_value − The value which is returned to parent process.
Here is an example of exit() in C language,
Example
#include <stdio.h>
Output
#include <stdlib.h>
int main() { The value of x : 10
int x = 10;
printf("The value of x : %d\n", x); In the above program, a variable ‘x’ is initialized with a value.
exit(0); The value of variable is printed and exit() function is called. As
printf("Calling of exit()"); exit() is called, it exits the execution immediately and it does
return 0; } not print the printf().
54
abort() function
The function abort() terminates the execution abnormally. It is suggested to not to use this function for
termination. It is declared in “stdlib.h” header file.
Here is the syntax of abort() in C language,
void abort(void);
#include <stdio.h>
Output
#include <stdlib.h>
int main() The value of a : 15
{ int a = 15;
printf("The value of a : %d\n", a);
abort(); In the above program, a variable ‘a’ is initialized with the value
printf("Calling of abort()"); and printed. As the abort() is called, it terminates the execution
return 0; } immediately but abnormally.
55
assert() function
The function assert() is declared in “assert.h” header file. It evaluates the expressions given as argument.
If expression is true, it does nothing. If expression is false, it abort the execution.
Here is the syntax of assert() in C language,
• Compiler sets aside storage for all static variables at compiler or link time
} // int fcn( … )
} // int fcn( … )
} // int fcn( … )
} // int fcn( … )
• extern variables:–
• Frequently occur in .h files.
• Each must be actually declared outside any function in exactly one .c file
67
REFERENCES
Reference Books
[1] Kanetkar, Y. (2010). Let us C. 15th ed.
[2] Thareja Reema (2014) Programming in C. 2nd ed.
[3] Zed A. Shaw, Learn C the Hard Way’
Reference Website
[4] fresh2refresh.com. (2019). C Language - Learn C Programs From
Basics | Fresh2Refresh. [online] Available at: https://fresh2refresh.com/c-
programming/c-basic-program/ [Accessed 17 May 2019].
[5] trytoprogram.com. (2019). C Programming- c programming user defined
functions. [online] Available at: http://www.trytoprogram.com/c-
programming/c-programming-user-defined-functions/
[6] btechsmartclass.com.(2019). C Programming- C Programming Basis
[online] Available at: http://www.btechsmartclass.com/c_programming/C-
Program-Basics.html
68
THANK YOU