0% found this document useful (0 votes)
14 views69 pages

Pythhon Cu 2

Uploaded by

wlp74125
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views69 pages

Pythhon Cu 2

Uploaded by

wlp74125
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 69

University Institute of Computing

Master of Computer Applications


WINNING CAMP
On
C & C++

DISCOVER . LEARN . EMPOWER


1
Strings
•1-d arrays of type char
•A string in C is terminated by the end-of-string sentinel ‘\0’
(null character)
•char s[21] - can have variable length string delimited with \
0
•Max length of the string that can be stored is 20 as the size must
include storage needed for the ‘\0’
•String constants : “hello”, “abc”
•“abc” is a character array of size 4

*
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);
}

%s reads a string into a character array


given the array name or start address.
It ends the string with ‘\0’
*
3
An example
void main()
Seen on screen
{
#define SIZE 25
int i, count=0; Typed as input
char name[SIZE]; Satyanarayana
scanf("%s", name); Name = Satyanarayana
printf("Name = %s \n", name);
Total a's = 6
for (i=0; name[i]!='\0'; i++)
if (name[i] == 'a') count++;
printf("Total a's = %d\n", count);
} Printed by program

Note that character strings read


in %s format end with ‘\0’
5
Library Functions for String Handling

• You can write your own C code to do different operations on


strings like finding the length of a string, copying one string
to another, appending one string to the end of another etc.
• C library provides standard functions for these that you can
call, so no need to write your own code
• To use them, you must do
#include <string.h>
At the beginning of your program (after #include <stdio.h>)

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()

int strlen(const char *s)


• Takes a null-terminated strings (we routinely
You cannot change contents
refer to the char pointer that points to a null-
terminated char array as a string) of s in the function

• Returns the length of the string, not


counting the null (\0) character
int strlen (const char *s) {
int n;
for (n=0; *s!=‘\0’; ++s)
++n;
return n;
}
8
strcat()
You cannot change contents
of s2 in the function
• char *strcat (char *s1, const char
*s2);
char *strcat(char *s1, const char *s2)
• Takes 2 strings as arguments, {
concatenates them, and puts the char *p = s1;
result in s1. Returns s1. while (*p != ‘\0’) /* go to end */
Programmer must ensure that s1 ++p;
points to enough space to hold the while(*s2 != ‘\0’)
result. *p++ = *s2++; /* copy */
*p = ‘\0’;
return s1;
}

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()

char *strcpy (char *s1, const char *s2);


The characters is the string s2 are copied into s1 until ‘\0’ is moved.
Whatever exists in s1 is overwritten. It is assumed that s1 has
enough space to hold the result. The pointer s1 is returned.

char * strcpy (char *s1, const char *s2)


{
char *p = s1;
while (*p++ = *s2++) ;
return s1;
}
11
Example: Using string functions

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.

// Linear Search in C int main()


#include <stdio.h> { int array[ ] = {2, 4, 0, 1, 9};
int search(int array[ ], int n, int x) int x = 1;
int n = sizeof(array) / sizeof(array[0]);
{ // Going through array sequenciallyint result = search(array, n, x);
for (int i = 0; i < n; i++) (result == -1) ? printf("Element not found") :
if (array[i] == x) printf("Element found at index: %d", result);
return i; }
return -1; }
15
Bubble Sort
• Bubble Sort is the simplest sorting algorithm that works by
repeatedly swapping the adjacent elements if they are in the
wrong order. This algorithm is not suitable for large data sets as
its average and worst case time complexity is quite high.
How Bubble Sort Works?
Consider an array arr[] = {5, 1, 4, 2, 8}
First Pass:
•Bubble sort starts with very first two elements, comparing them to check
which one is greater.
• ( 5 1 4 2 8 ) –> ( 1 5 4 2 8 ), Here, algorithm compares the first two
elements, and swaps since 5 > 1.
• ( 1 5 4 2 8 ) –> ( 1 4 5 2 8 ), Swap since 5 > 4
• ( 1 4 5 2 8 ) –> ( 1 4 2 5 8 ), Swap since 5 > 2
• ( 1 4 2 5 8 ) –> ( 1 4 2 5 8 ), Now, since these elements are already in
order (8 > 5), algorithm does not swap them.
16
Bubble Sort
Second Pass:
•Now, during second iteration it should look like this:
• ( 1 4 2 5 8 ) –> ( 1 4 2 5 8 )
• ( 1 4 2 5 8 ) –> ( 1 2 4 5 8 ), Swap since 4 > 2
• ( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
• ( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
Third Pass:
•Now, the array is already sorted, but our algorithm does not know if it is completed.
•The algorithm needs one whole pass without any swap to know it is sorted.

•( 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

Figure 6.1 Types of functions


in C [1] 22
TYPES OF FUNCTION

Figure 6.2 Types of functions 23


in C [3]
NEED OF USER-DEFINED FUNCTIONS
• Sometimes certain type of operations or calculations are repeated at many points throughout a program.
• For e.g. calculating factorial of a number several times in the same program.
• In such situations, we may repeat the program statements wherever they are needed.
• Another approach is to design a function that can be called and used whenever required.
• This saves both time and space.

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.

Figure 6.5 Function


definition
• Compiler will compare the return type, number of arguments and types of argument with those present in
function call.

29
FUNCTION DEFINITION
• If the compiler is unable to find the function definition, then the compile time error will be generated.

Figure 6.5 Compile time error [Program executed on Dev-cpp by 30


Ms. Jasleen Kaur]
FUNCTION CALL
• A called function performs defined task and when its return statement is executed or when its function-ending
closing brace is reached, it returns program control back to the main program.

Figure 6.6 Function call in


C [2] 31
STRUCTURE OF FUNCTION
• So, lets wind up the structure of a function.
• C function involves the following components:

Figure 6.7 Structure of function


in C [5]

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.8 Program 2 executed on


Dev-cpp 34
EXAMPLE 1

Figure 6.9 Program 3 [executed on Dev-cpp by Ms.


Jasleen Kaur] 35
EXAMPLE 1

Figure 6.10 Program


output 36
EXAMPLE 2

Figure 6.11
Program 4 37
EXAMPLE 2

Figure 6.12 Program


Output 38
TYPES OF
ARGUMENTS/PARAMETERS

Figure 6.13 Types of


argument [5] 39
PASSING ARGUMENTS TO A
FUNCTION
• If a function is to use arguments, it must declare variables that accept the values of the arguments.
• These variables are called the formal parameters of the function.
• The formal parameters behave like other local variables inside the function
• They are created upon entry into the function and destroyed upon exit.
• While calling a function, there are two ways that arguments can be passed to a function:
• Call by value (passing value of variable during function call)
• Call by reference (passing address of variable during function call)

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

Figure 6.14 Call by value program [executed on


Dev-cpp IDE]
42
CALL BY VALUE

Figure 6.15 Output of Call by value program [executed on


Dev-cpp IDE]

43
CALL BY VALUE- EXAMPLE 2

Figure 6.16 Call by value program [executed on


Dev-cpp IDE]
44
CALL BY VALUE- EXAMPLE 2

Figure 6.17 Output of Call by value program [executed on


Dev-cpp IDE]

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

Figure 6.18 Call by reference program [executed on


Dev-cpp IDE] 47
CALL BY REFERENCE

Figure 6.19 Call by reference program [executed on


Dev-cpp IDE] 48
CALL BY REFERENCE

Figure 6.20 Output of Call by reference program [executed


on Dev-cpp IDE] 49
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.

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.

Figure 6.21 Recursive


function [5] 51
RECURSIVE FUNCTION

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);

Here is an example of abort() in C language,


Example

#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,

void assert(int exp);


Here.
exp − The expression you want to evaluate.
Here is an example of assert() in C language,
Example
#include <stdio.h>
#include <assert.h>
Output
int main() The value of a : 15 main: main.c:9: main: Assertion `a!=15'
{ int a = 15; failed.
printf("The value of a : %d\n", In the above program, a variable ‘a’ is initialized with a value. The
a); value of variable is printed and assert() function is called. As assert() is
assert(a!=15); called, it evaluates the expression that ‘a’ is not equal to 15 which is
printf("Calling of assert()"); false that is why it aborts the execution and shows an error.
return 0; }
56
Data Storage in Memory
• Variables may be automatic or static

• Automatic variables may only be declared within functions and


compound statements (blocks)
• Storage allocated when function or block is entered
• Storage is released when function returns or block exits

• Parameters and result are (somewhat) like automatic variables


• Storage is allocated and initialized by caller of function
• Storage is released after function returns to caller.

Scope Rules and Storage Types CS-2303, C-Term 2010 57


Scope
• Identifiers declared within a function or compound statement are
visible only from the point of declaration to the end of that function
or compound statement.
• Like Java

Scope Rules and Storage Types CS-2303, C-Term 2010 58


Example
i is visible
int fcn (float a, int b) { from this point
to end of fcn
int i; g is visible from this point
to end of fcn
double g;
for (i = 0; i < b; i++) { h is only double
visible fromhthis= i*g;
loop body – may access a, b, i, g, hpoint to end of loop!
} // for(i…)

fcn body – may access a, b, i, g


}// int fcn( … )
Scope Rules and Storage Types CS-2303, C-Term 2010 59
Static Data – Very different
• Static variables may be declared within or outside of functions
• Storage allocated when program is initialized
• Storage is released when program exits

• Static variables outside of functions may be visible to linker

• Compiler sets aside storage for all static variables at compiler or link time

• Values retained across function calls

• Initialization must evaluate to compile-time constant

Scope Rules and Storage Types CS-2303, C-Term 2010 60


Static Variable Examples
int j; //static, visible to linker & all functs
static float f; // not visible to linker, visible to
// to all functions in this program

int fcn (float a, int b) {


// nothing inside of {} is visible to linker
int i = b; //automatic
double g; //automatic
static double h; //static, not visible to
// linker; value retained from call to call

body – may access j, f, a, b, i, g, h

} // int fcn( … )

Scope Rules and Storage Types CS-2303, C-Term 2010 61


Static Variable Examples (continued)
int j; //static, visible to linker & all functs
static float f; // not visible to linker, visible to
// to all functions in this program
De
cla
fun ration
int fcn (float a, int b) { ctio ou t
st
at n :– a side
// nothing inside of {} is visible to linker i
vis c sto lwa any
int i = b; //automatic ible r ag ys s
to l e cla tati
ink c
double g; //automatic
er s s :– n
static double h; //static, not visible to ot
// linker; value retained from call to call

body – may access j, f, a, b, i, g, h

} // int fcn( … )

Scope Rules and Storage Types CS-2303, C-Term 2010 62


t is
l
Static Variable Examples (continued) n:– d ef au
n o t
tio s :–
c la s
f un tic c
e r
int j; //static, visible to linker & all functs de a a g
n si tom tor nke
static float f; // not visible to linker, visible to I au c
s
o li
t i et
// to all functions in this program
t a ibl
s vis
int fcn (float a, int b) {
// nothing inside of {} is visible to linker
int i = b; //automatic
double g; //automatic
static double h; //static, not visible to
// linker; value retained from call to call

body – may access j, f, a, b, i, g, h

} // int fcn( … )

Scope Rules and Storage Types CS-2303, C-Term 2010 63


Static Variable Examples (continued)
int j; //static, visible to linker & all functs
static float f; // not visible to linker, visible to
// to all functions in this program

int fcn (float a, int b) {


// nothing inside of {} is visible to linker
int i = b; //automatic
double g; //automatic
static double h; //static, not visible to
No
// linker; value retained from call to call t e:
reataluevalue
V
body – may access j, f, a, b, i, g, h nexacrineodf fh of h i
t oss roim s s
rec aolsno
urs e rceta
ion alline
} // int fcn( … ) s to d
Scope Rules and Storage Types CS-2303, C-Term 2010 64
Extern Variables
int j; //static, visible to linker & all functs
static float f; // not visible to linker, visible to
// to all functions in this program
extern float p; // static, defined in another program
ex
te
rn
int fcn (float a, int b) { s tati s tora
// nothing inside of {} is visible to linker c
a no v ar ge c
the iabl lass
int i = b; //automatic rC ed :– a
p ro e f
double g; //automatic gra ined i
static double h; //static, not visible to
m n
// linker; value retained from call to call

body – may access j, f, a, b, i, g, h , p

} // int fcn( … )

Scope Rules and Storage Types CS-2303, C-Term 2010 65


Extern Variables (continued)
• Examples:–
• stdin, stdout, stderr are extern variables that point to standard input,
output, and error streams.

• extern variables:–
• Frequently occur in .h files.
• Each must be actually declared outside any function in exactly one .c file

Scope Rules and Storage Types CS-2303, C-Term 2010 66


ASSESSMENT PATTERN
Section- A

1. All questions are mandatory. Each question carry 2 marks each


(a) Calculate power of a number using recursion.
(b) Write a program to display all prime numbers between intervals.
Section- B

Following questions carry 10 marks each


2. Write a program to find factorial of a large number, such as 50.
3. Write a program in C to find the sum of the series 1!/1+2!/2+3!/3+4!/4+5!/5 using the function.

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

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