0% found this document useful (0 votes)
2 views44 pages

Module 3B PowerPoint Presentation

The document provides an introduction to computer systems focusing on array handling, functions, and recursion in C programming. It covers topics such as declaring and initializing arrays, string manipulation, and function definitions, including examples of code for practical understanding. Additionally, it discusses parameter passing methods and recursion with examples for calculating factorials.

Uploaded by

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

Module 3B PowerPoint Presentation

The document provides an introduction to computer systems focusing on array handling, functions, and recursion in C programming. It covers topics such as declaring and initializing arrays, string manipulation, and function definitions, including examples of code for practical understanding. Additionally, it discusses parameter passing methods and recursion with examples for calculating factorials.

Uploaded by

Yoosha
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

COMP 2131 : INTRODUCTION TO

COMPUTER SYSTEMS

1 THOMPSON RIVERS UNIVERSITY


SECTION 3.2

2
Contents
Array Handling

Functions

Recursion

3
Arrays
Collection of similar data items
Identified by a single name
Stored in the contiguous memory location

Array is declared as:


type arrayName [ arraySize ];

Ex:
int marks[100];

4
Example (run the code)
/*
* C Program to Find the Largest Number in an Array
*/

#include <stdio.h>

int main()
{
int array[50], size, i, largest;
printf("\n Enter the size of the array: ");
scanf("%d", &size);
printf("\n Enter %d elements of the array: ", size);
for (i = 0; i < size; i++)
scanf("%d", &array[i]);
largest = array[0];
for (i = 1; i < size; i++)
{
if (largest < array[i])
largest = array[i];
}
printf("\n largest element present in the given array is : %d", largest);
return 0;
}

5
2-D arrays
C language also supports
multidimensional arrays.
Two-dimensional array is declared as
follows,

type array-name[row-size][column-size]
Example : int a[3][4];

6
Initializing Two-Dimensional
Arrays
• 2-D arrays may be initialized by
specifying bracketed values for each row.
• Ex:
int a[3][4] = { {0, 1, 2, 3} , {4, 5, 6, 7} , {8, 9, 10, 11}};

Or
int a[3][4] = {0,1,2,3,4,5,6,7,8,9,10,11};
** Both are same declaration as well as
initialization

7
Example (run the code and
check the o/t)
#include<stdio.h>
#include<conio.h>
void main()
{ int arr[3][4];
int i,j,k;
printf("Enter array element");
for(i=0;i<3;i++)
{ for(j=0; j < 4; j++)
{ scanf("%d",&arr[i][j]); } }
for(i=0; i < 3; i++)
{ for(j=0; j < 4; j++)
{ printf("%d",arr[i][j]); } }
getch(); }

8
String and Character array
• A string is a sequence of characters in a character
array that is terminated by null character '\0'.
• C language does not support strings as a data type.
• A string is just a one-dimensional array of characters.
• Different ways to initialize a character array variable are:
char name[10]="ExampleProgram"; //valid character array
initialization
char name[10]={'L','e','s','s','o','n','s','\0'}; //valid initialization

9
Strings
• Strings are a fundamental concept, but they are not
a built-in data type in C
• strings consist of a contiguous sequence of
characters terminated by and including the
first null character.
• The length of a string is the number of bytes preceding the
null character
• The value of a string is the sequence of the values of the
contained characters, in order.
• Series of characters treated as a single unit
• Can include letters, digits and special characters (*, /, $)
• String literal (string constant) - written in double quotes
• "Hello"
h e l l o \0

10 length
String declarations
• Declare as a character array or a variable of type
char *
char color[] = "blue";
char *colorPtr = "blue";
• Remember that strings represented as character
arrays end with '\0'
• color has 5 elements
Inputting strings
• Use scanf
scanf("%s", word);
• Copies input into word[]
• Do not need & (because a string is a pointer)
• Remember to leave room in the array for '\0'

11
Read and write string
#include <stdio.h>
int main()
{
char name[20];
printf("Enter name: ");
scanf("%s",name); // to read a string
printf("Your name is %s.",name); // display a string
return 0;
}

12
Calculate the length of a string
Example:
#include <stdio.h>
int main()
{ char s[1000],i;
printf("Enter a string: ");
scanf("%s",s);
for(i=0; s[i]!='\0'; ++i);
printf("Length of string: %d",i);
return 0;
}

13
String handling functions
• Large number of string handling functions are
supported
• These are used through string.h library.

Method Description
It is used to concatenate(combine)
strcat()
two string

strlen() It is used to show length of a string

It is used to show reverse of a


strrev()
string
strcpy() Copies one string into another
strcmp() It is used to compare two string
Example (Practice)
#include<stdio.h>
main()
{int c, i, nwhite, nother;
int ndigit[10];
nwhite=nother=0;
for(i=0;i<10;i++) ndigit[i]=0;
while ((c=getchar()!=EOF)
{
if ((c>=’0’ && c<=’9’) ++ndigit[c-‘0’];
else if (c==’ ‘ || c==’\n’ || c==’\t’) ++nwhite;
else ++nother;
printf(“digits =”);
for(i=0;i<10;i++) printf(“%d “, ndigit[i]);
printf(“ White space = %d other = %d\n”,
nwhite, nother);
}
Example
#include <stdio.h>
void main(void)
{
char Password[80];
puts("Enter 8 character password:");
gets(Password);
Puts(Password);
}

•gets: The program reads from standard input until a


newline character is read or an end of file (EOF)
condition is encountered.
•Programmer does not know the size of input.
•Standard (vulnerable) solution allocates a much
bigger buffer than expected input.
Solution
#include<string.h>
#include <stdio.h>
int main(void)
{
char Password[80];
puts("Enter 8 character password:");
fgets(Password, 80, stdin); // this tells the length and input
stream
puts(Password);
return 0;
}
Another way to input array

#include<stdio.h>
main()
{char c, sentence[80];
Int i=0;
while ((c=getchar()!=’\n’)
sentence[i++]=c;
sentence[i]=’\0’;
printf(“ Input data is %s\n”, sentence);
}
String Conversion Functions
• Conversion functions
• In <stdlib.h> (general utilities library)
• Convert strings of digits to integer and floating-
point values

Prototype Description
double atof( const char *nPtr ) Converts the string nPtr to double.
int atoi( const char *nPtr ) Converts the string nPtr to int.
long atol( const char *nPtr ) Converts the string nPtr to long int.
Example
#include <stdlib.h>
int main(int argc, char *argv[])
{
printf("The value entered is %d ", atoi(argv[1]));
printf("The next parameter is float and value is %f\n",
atof(argv[2]));
return 0;
} * Quick review of Command-line arguments

int main(int argc, char *argv[]);


argcthe number of arguments
argv[0] the program name, e.g., [Link]
argv[1] the first argument from the user
E.g., $ ./[Link] test this comp
argc: 4
argv[0]: “./[Link]”
argv[1]: “test
String Manipulation Functions
String handling library has functions to
• Manipulate string data
• Search strings
• Tokenize strings
• Determine string length

Function prototype Function description


char *strcpy( char *s1, Copies string s2 into array s1. The value of s1 is
const char *s2 ) returned.
char *strncpy( char *s1, Copies at most n characters of string s2 into array s1.
const char *s2, size_t n ) The value of s1 is returned.
char *strcat( char *s1, Appends string s2 to array s1. The first character of
const char *s2 ) s2 overwrites the terminating null character of s1.
The value of s1 is returned.
char *strncat( char *s1, Appends at most n characters of string s2 to array s1.
const char *s2, size_t n ) The first character of s2 overwrites the terminating
null character of s1. The value of s1 is returned.
Example
#include <string.h>
#include<stdio.h>
int main(void)
{

char s1[20]="Happy ";


char s2[]="New Year";
char s3[40];

printf("%s %s\n", s1, s2);


printf("strcat(s1,s2) = %s\n", strcat(s1, s2));
printf("strncat (s3, s1, 6) = %s\n", strncat(s3,s1,6));
return 0;
}
Comparing functions
• Computer compares numeric ASCII codes of
characters in string
int strcmp( const char *s1, const char *s2 );
• Compares string s1 to s2
• Returns a negative number if s1 < s2, zero if s1 ==
s2 or a positive number if s1 > s2
int strncmp( const char *s1, const char *s2,
size_t n );
• Compares up to n characters of string s1 to s2
• Returns values as above
String Tokenizing
• char *strtok( char *s1, const char *s2 );
• A sequence of calls to strtok breaks string s1 into
“tokens”—logical pieces such as words in a line of
text—separated by characters contained in string
s2. The first call contains s1 as the first argument,
and subsequent calls to continue tokenizing the
same string contain NULL as the first argument. A
pointer to the current token is returned by each call.
If there are no more tokens when the function is
called, NULL is returned.
example
include<string.h>
#include<stdlib.h>
#include<stdio.h>
int main(void)
{
char a[]="This line has 5 different words";
char *p;
printf(" %s\n", a);
p=strtok(a, " ");
while (p !=NULL)
{
printf("%s\t", p);
p = strtok(NULL," ");
}
}
Character Handling Library
• Character handling library
• Includes functions to perform useful tests and
manipulations of character data
• Each function receives a character (an int) or
EOF as an argument
• The following slides contain a table of all the
functions in <ctype.h>
Character handling Library
Prototype Function description
int isdigit( int c ); Returns a true value if c is a digit and 0 (false) otherwise.
int isalpha( int c ); Returns a true value if c is a letter and 0 otherwise.
int isalnum( int c ); Returns a true value if c is a digit or a letter and 0 otherwise.
int isxdigit( int c ); Returns a true value if c is a hexadecimal digit character and 0 otherwise.

int islower( int c ); Returns a true value if c is a lowercase letter and 0 otherwise.

int isupper( int c ); Returns a true value if c is an uppercase letter and 0 otherwise.

int tolower( int c ); If c is an uppercase letter, tolower returns c as a lowercase letter. Otherwise, tolower
returns the argument unchanged.

int toupper( int c ); If c is a lowercase letter, toupper returns c as an uppercase letter. Otherwise, toupper
returns the argument unchanged.
int isspace( int c ); Returns a true value if c is a white-space character—newline ('\n'), space (' '), form
feed ('\f'), carriage return ('\r'), horizontal tab ('\t') or vertical tab ('\v')—and 0
otherwise.
int iscntrl( int c ); Returns a true value if c is a control character and 0 otherwise.

int ispunct( int c ); Returns a true value if c is a printing character other


than a space, a digit, or a letter and returns 0 otherwise.
int isprint( int c ); Returns a true value if c is a printing character including a space (' '), else returns 0
int isgraph( int c ); Returns a true value if c is a printing character other than a space (' '), else returns 0 .

Ref: [Link]
FUNCTIONS
Functions
#include <stdio.h>
int power(int m, int n);

int main() {
int i;
for (i = 0; i < 10; i++)
printf("%d %d %d\n", i, power(2, i), power(3, i));
return 0;
}

int power(int base, int n)


{
int i, p;
p = 1;
for (i = 1; i <= n; i++)
p = p * base;

return p;
}
Functions and Program
Structure
• Function in C is the same as method in Java.

• return-type function-name(argument declarations)

• Various parts may be absent.


Functions
• The program code can be divided into separate functions.
• Each function logically, should performs a specific task.
• A function declaration is used to tell the compiler about:
• a function's name,
• Its return type, and
• The type and number of parameters.
• A function definition provides the actual body of the function i.e
the functionality defined within a function

Ex: function declaration is:


return_type function_name( parameter list )
{ body of the function }
Example
#include <stdio.h>
int max(int num1, int num2); // function declaration or prototype
int main () {
int a = 100, b = 200, ret;
ret = max(a, b); // function calling
printf( "Max value is : %d\n", ret );
return 0;
}
int max(int n1, int n2) {
int result;
if (n1 > n2)
result = n1;
else
result = n2;
return result;
}
Parameter passing
• while calling a function, there are two ways in which arguments
can be passed :
• Call by value – In this method, the actual value of an
argument is passed into the formal parameter of the
function. Hence here, changes made to the parameter
inside the function body do not have any effect on the
actual argument value.
• Call by reference – Since in this method, the address of an
argument is copied to the formal parameter, and address is
used for manipulations inside the function. Hence the
changes made to the parameter affect the argument i.e.
changes the actual data.
Recursion
• Recursion is the process of repeating a function call
from itself
• if a function calls the same function within, then it is
called a recursive call of the function.
Ex:
void recursion() { recursion(); }
int main()
{ recursion(); }
Even though, the C programming language supports
recursion, careful consideration is required to define an exit
condition from the function, else an infinite loop is created.
Example (factorial)
#include <stdio.h>
int factorial(unsigned int i)
{ if(i <= 1)
{ return 1; }
return i * factorial(i - 1);
}
int main()
{ int i = 15;
printf("Factorial of %d is %d\n", i, factorial(i));
return 0; }
SPECIAL VARIABLE DECLARATIONS
External Variables
• If a large number of variables must be shared among functions, external
variables (or also called global variables) are more convenient and
efficient than long argument lists.

• External variables are declared outside of any function, usually with initial
values.

• Automatic variables (local variables and parameters) are internal to a


function; they come into existence when the function is entered, and
disappear when it is left.

• External variables, on the other hand, are permanent, so they can retain
values from one function invocation to the next. Thus if two functions must
share some data, yet neither calls the other, it is often most convenient if
the shared data is kept in external variables rather than being passed in
and out via arguments.
Static Variables
• The static declaration, applied to an external variable or
function, limits the scope of that object to the rest of the
source file being compiled.
• External static thus provides a way to hide names from
other files.
static char buf[BUFSIZE]; // only in this
file
static int bufp = 0; // only in this
file
int getch(void) { ... }
void ungetch(int c) { ... }

• Static in Java has a bit different meaning.


Register Variables
• A register declaration advises the compiler that the variable in
question will be heavily used.
• The idea is that register variables are to be placed in machine
registers, which may result in smaller and faster programs. But
compilers are free to ignore the advice.
register int x;
register char c;

f(register unsigned m, register long n) {


register int i;
...
}

• Usually for index variables used in loop structures


Initialization
• Very similar to Java

• In the absence of explicit initialization, external and


static variables are guaranteed to be initialized to
zero; but automatic and register variables have
undefined (i.e., garbage) initial values.
Scope Rules
• A scope in any programming is a region of the program where
a defined variable can have its existence and beyond that
variable can not be accessed.

• There are three places where variables can be declared in C


programming language:
• Inside a function or a block which is
called local variables,
• Outside of all functions which is called global variables.
• In the definition of function parameters which is
called formal parameters.
Scope Rules- local variables
• Variables that are declared inside a function or block are called
local variables. They can be used only by statements that are
inside that function or block of code.
#include <stdio.h>
int main ()
{
/* local variable declaration */
int a, b; int c;
/* actual initialization */
a = 10;
b = 20;
c = a + b;
printf ("value of a = %d, b = %d and c = %d\n", a, b, c);
return 0;
}
Scope Rules- global variables
• Global variables are defined outside of a function, usually on
top of the program. The global variables will hold their value
throughout the lifetime of your program and they can be
accessed inside any of the functions defined for the program.
#include <stdio.h>
/* global variable declaration */
int g;
int main () A program can have same name
{ for local and global variables but
/* local variable declaration */ value of local variable inside a
int a, b; function will take preference.
/* actual initialization */
a = 10;
b = 20;
g = a + b;
printf ("value of a = %d, b = %d and g = %d\n", a, b, g);
return 0;
}
Scope Rules- formal parameters
• Function parameters, formal parameters, are treated as local
variables with-in that function and they will take preference
over the global variables.
#include <stdio.h>
/* global variable declaration */
int a = 20;
int main ()
{
/* local variable declaration in main function */
int a = 10;
int b = 20;
int c = 0;
printf ("value of a in main() = %d\n", a);
c = sum( a, b);
printf ("value of c in main() = %d\n", c);
return 0;
}
int sum(int a, int b) {/* function to add two integers */
printf ("value of a in sum() = %d\n", a);
printf ("value of b in sum() = %d\n", b);
return a + b;
}

You might also like