Computer Programming Midterm Reviewer

Download as pdf or txt
Download as pdf or txt
You are on page 1of 7

FUNCTION of a function.

Parameters are optional; that is, a


 A function is a group of statements that together function may contain no parameters.
perform a task.  Function Body − The function body contains a
 Every C program has at least one function, which is collection of statements that define what the
main(), and all the most trivial programs can define function does.
additional functions. /* function returning max between 2numbers */
 You can divide up your code into separate functions. int max(int num1, int num2)
 How you divide up your code among different {
functions is up to you, but logically the division is such /* local variable declaration */
that each function performs a specific task. int result;
 A function can also be referred as a method or a sub- if (num1 > num2)
routine or a procedure result = num1;
else
THREE ELEMENTS OF FUNCTIONS result = num2;
 Function Prototype (Declaration) return result;
 A function declaration tells the compiler about a }
function's name, return type, and parameters. (how
to call the function)  Function Call
 A function declaration has the following parts –  Function Execution in the main program
return_type function_name( parameter list );  To use a function, you will have to call that function
int max(int num1, int num2); to perform the defined task.
int max(int, int);  When a program calls a function, the program
control is transferred to the called function. A called
 Function Definition function performs a defined task and when its return
 A function definition provides the actual body of the statement is executed or when its function-ending
function. closing brace is reached, it returns the program
control back to the main program.
return_type function_name( parameter list )  To call a function, you simply need to pass the
{ required parameters along with the function name,
body of the function and if the function returns a value, then you can
} store the returned value.

 A function definition in C programming consists of a TWO TYPES OF FUNCTION BY DEFINITION


function header and a function body. Here are all the  Built-In Function or Pre-defined Function
parts of a function −  User – Defined Function
Return Type − A function may return a value. The
return_type is the data type of the value the FUNCTION ARGUMENTS
function returns. Some functions perform the  Formal Parameters
desired operations without returning a value. In  If a function is to use arguments, it must declare
this case, the return_type is the keyword void. variables that accept the values of the arguments
Function Name − This is the actual name of the  Formal parameters behave like other local variables
function. The function name and the parameter list inside the function and are created upon entry into
together constitute the function signature. the function and destroyed upon exit.
Parameters − A parameter is like a placeholder.
When a function is invoked, you pass a value to the  Call Parameters
parameter. This value is referred to as actual Types of Passing Arguments to Function
parameter or argument. The parameter list refers  Pass-by Reference (Call-by Reference)
to the type, order, and number of the parameters  This method copies the address of an argument
into the formal parameter. Inside the function, the
address is used to access the actual argument used int a, b;
in the call. This means that changes made to the
parameter affect the argument. /* actual initialization */
 Pass-by Value (Call-by Value) a = 10;
 This method copies the actual value of an b = 20;
argument into the formal parameter of the g = a + b;
function. In this case, changes made to the
parameter inside the function have no effect on printf ("value of a = %d, b = %d and g = %d\n",
the argument. a, b, g);
VARIABLE SCOPE return 0;
 A scope in any programming is a region of the program }
where a defined variable can have its existence and
beyond that variable it cannot be accessed. A program can have same name for local and global
variables but the value of local variable inside a function
 Local Variable will take preference. Here is an example –
 Inside a function or a block
 Variables that are declared inside a function or #include <stdio.h>
block are called local variables. They can be used /* global variable declaration */
only by statements that are inside that function or int g = 20;
block of code. Local variables are not known to int main ()
functions outside their own. {
 The following example shows how local variables /* local variable declaration */
are used. Here all the variables a, b, and c are local int g = 10;
to main() function. printf ("value of g = %d\n", g);
return 0;
#include <stdio.h> }
int main ()
{ When the above code is compiled and executed, it
/* local variable declaration */ produces the following result −
int a, b; value of g = 10
int c;
#include <stdio.h>
/* actual initialization */ /* global variable declaration */
a = 10; int a = 20;
b = 20; int main ()
c = a + b; {
/* local variable declaration in main function */
printf ("value of a = %d, b = %d and c = %d\n", int a = 10;
a, b, c); int b = 20;
return 0; int c = 0;
}
printf ("value of a in main() = %d\n", a);
 Global Variable c = sum( a, b);
 Outside of all functions printf ("value of c in main() = %d\n", c);
 The following program show how global variables return 0;
are used in a program. }
/* function to add two integers */
#include <stdio.h> int sum(int a, int b)
/* global variable declaration */ {
int g; printf ("value of a in sum() = %d\n", a);
int main () printf ("value of b in sum() = %d\n", b);
{ return a + b;
/* local variable declaration */ }
character at the end of the array, the size of the
CTYPE FUNCTIONS character array containing the string is one more than
 The ctype.h header file of the C Standard Library the number of characters in the word "Hello."
declares several functions that are useful for testing
and mapping characters. char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
 All the functions accepts int as a parameter, whose
value must be EOF or representable as an unsigned  If you follow the rule of array initialization then you can
char. write the above statement as follows
 All the functions return non-zero (true) if the argument
c satisfies the condition described, and zero(false) if char greeting[] = "Hello";
not.
CTYPE FUNCTIONS  Following is the memory presentation of the above
 int isalnum (int c) defined string in C/C++ −
- This function checks whether the passed character is
alphanumeric.
 int isalpha (int c)
- This function checks whether the passed character is
alphabetic.
 int iscntrl (int c)
- This function checks whether the passed character is
control character.
 int isdigit (int c) STRING FUNCTIONS
- This function checks whether the passed character is strcpy(s1, s2);
decimal digit. - Copies string s2 into string s1.
 int isgraph (int c) strcat(s1, s2);
- This function checks whether the passed character - Concatenates string s2 onto the end of string s1.
has graphical representation using locale. strlen(s1);
 int islower (int c) - Returns the length of string s1.
- This function checks whether the passed character is strcmp(s1, s2);
lowercase letter - Returns 0 if s1 and s2 are the same; less than 0 if s1<s2;
 int isprint (int c) greater than 0 if s1>s2.
- This function checks whether the passed character is strchr(s1, ch);
printable. - Returns a pointer to the first occurrence of character
 int ispunct (int c) ch in string s1.
- This function checks whether the passed character is strstr(s1, s2);
a punctuation character - Returns a pointer to the first occurrence of string s2 in
 int isspace (int c) string s1.
- This function checks whether the passed character is
white-space. MATH FUNCTIONS
 int isupper (int c)  pow (Power)
- This function checks whether the passed character is - The pow function is used to calculate the power of the
an uppercase letter. base raised to the power of exponent. It accepts two
 int isxdigit (int c) double values as arguments which are the base and
- This function checks whether the passed character is exponents numbers and it returns a single double
a hexadecimal digit. integer which is base to the power of exponent.
double pow( double, double)
STRING/ARRAY Calling syntax Output
 Strings are actually one-dimensional array of characters double x = pow(2, 4) pow( 2 , 4 ) = 16
terminated by a null character '\0'. Thus a null-
terminated string contains the characters that comprise  sqrt (Squareroot)
the string followed by a null. - sqrt function in C++ returns the square root of the
 The following declaration and initialization create a double integer inside the parameter list. The method
string consisting of the word "Hello". To hold the null
accept a double integer value as input find square root that memory; and the set of operations that can be
and returns a double integer as output. applied to the variable.

double sqrt( double) WAYS TO CHARACTERIZE VARIABLES


Calling syntax Output  By Data Type
double x = sqrt(25.00) sqrt( 25 ) = 5.00  refers to the type of information represented by a
variable
 log (Logarithm)  Data types in c refer to an extensive system used for
- The log function is used to find the natural log of the declaring variables or functions of different types.
given number. this method accepts single double The type of a variable determines how much space it
integer value finds logarithmic value and returns a occupies in storage and how the bit pattern stored is
double integer result of log(). interpreted.
double log( double) Types Of Data
Calling syntax Output  Basic Types
double x = log(1.35) log( 1.35 ) = 0.300105 - They are arithmetic types and are further
classified into:
 floor o Integer Types
- The floor function is used to return the floor value of
the given double integer. floor value means rounded Storage
Type Value range
Size
down value. the function accepts a double value as
input and Returns double integer value calculated using char 1 byte -128 to 127 or 0 to 255
floor(). unsigned
1 byte 0 to 255
char
double floor( double)
Calling syntax Output signed char 1 byte -128 to 127
double x = floor(6.24) floor( 6.24 ) = 6 -32,768 to 32,767 or -
int 2/4 bytes
2,147,483,648 to 2,147,483,647
 ceil 0 to 65,535 or 0 to
unsigned int 2/4 bytes
- The ceil function is used to return the ceil value of the 4,294,967,295
given double integer. ceil value means rounded up short 2 bytes -32,768 to 32,767
value. the function accepts a double value as input and
Returns double integer value calculated using ceil(). unsigned
2 bytes 0 to 65,535
short
double ceil( double)
Calling syntax Output long 4 bytes -2,147,483,648 to 2,147,483,647
double x = ceil(6.64) ceil( 6.64 ) = 7 unsigned
4 bytes 0 to 4,294,967,295
long
 abs
- The abs function returns the absolute value of the
integer value. The function accepts an integer value and o Floating-Point Types
returns an integer value that has the same magnitude
but positive sign.
Storage
double abs( double) Type Value range Precision
Size
Calling syntax Output
double x = abs(-512) abs( -512) = 512 1.2E-38 to 6 decimal
float 4 byte
3.4E+38 places

VARIABLE 2.3E-308 to 15 decimal


double 8 byte
 A variable definition tells the compiler where and how 1.7E+308 places
much storage to create for the variable
 Each variable in C has a specific type, which
determines the size and layout of the variable's long 3.4E-4932 to 19 decimal
10 byte
memory; the range of values that can be stored within double 1.1E+4932 places
 Enumerated Types they are declared; that is their scope is confined
- They are again arithmetic types and they are used to that function.
to define variables that can only assign certain - Automatic variables defined in different
discrete integer values throughout the program. functions will therefore be independent of
 The Type Void another, even though they may have the same
- The type specifier void indicates that no value is name.
available. - Any variable declared within a function is
o Function returns as void interpreted as an automatic variable unless a
- There are various functions in C which do not different storage class specification is included
return any value or you can say they return void. within the declaration.
A function with no return value has the return - Since the location of the variable declarations
type as void. For example, void exit (int status); within the program determine the automatic
o Function arguments as void storage class, the keyword AUTO is not required
- There are various functions in C which do not at the beginning of each variable declaration.
accept any parameter. A function with no - There is no harm in including an auto
parameter can accept a void. For example, int specification within a declaration if the
rand(void); programmer wishes, though this is normally not
o Pointers to void done.
- A pointer of type void * represents the address - An automatic variable does not retain its value
of an object, but not its type. For example, a once the control is transferred out of its defining
memory allocation function void *malloc(size_t function. Therefore, any value assigned to an
size); returns a pointer to void which can be automatic variable within a function will be lost
casted to any data type once the function is exited.
 Derived Type - If the program logic requires that an automatic
- They include (a) Pointer types, (b) Array types, variable be assigned a particular value each time
the function is executed, that the value will have
(c) Structure types, (d) Union types and (e)
to be reset whenever the function is re-entered.
Function types.
 External variables or Extern
- External variables, in contrast to automatic
 To get the exact size of a type or a variable on a
variables, are not confined to single functions.
particular platform, you can use the sizeof operator.
Their scope extends from the point of definition
The expressions sizeof(type) yields the storage size of
through the remainder of the program. Hence,
the object or type in bytes. Given below is an example
they usually span two or more functions, and
to get the size of int type on any machine
often an entire program.
int main()
 Static variables
{
- To allow local variable to retain its previous
printf("Storage size for int : %d \n",
value when the block is re-entered.
sizeof(int));
- Use in connection with external declarations.
return 0;
Static variables can be utilized within the function
}
in the same manner as other variables. They
----------------------------------------------------------------------
cannot however be accessed outside of their
defining function.
 By Storage Class
 refers to the permanence of a variable and its scope
 Register Variables
within the program, that is, the portion of the
- The storage class register tells the compiler that
program over which the variable is recognized.
the associated variables should be stored in high-
 There are four storage-class specifications in C:
speed memory registers, provided it is physically
 Automatic variables or Auto
and semantically possible.
- Automatic variables are always declared within
a function and are local to the function in which
Sample Program(External And Automatic) POINTER
int a=3;  A pointer is a variable that represents the location
main() (rather than the value) of a data item, such as a
{ variable of an array element.
int count;  A pointer is a variable whose value is the address of
int funct1(int b); another variable, i.e., direct address of the memory
clrscr(); location.
for(count=1; count<=5; ++count)  A pointer in c is an address, which is a numeric value.
{ Therefore, you can perform arithmetic operations on a
a = funct1(count); pointer just as you can on a numeric value.
printf(“%d\t”,a); USEFUL APPLICATIONS OF POINTER
}  Pointers can be used to pass information back and fort
getch(); between a function and its reference point. In
return 1; particular, pointers provide a way to return multiple
} data items from a function via function arguments.
 Pointers also permit references to other functions to
int funct1(int b) be specified as arguments to a given function. This has
{ effect of passing functions as arguments the given
int count; function.
count = b + a++;  Pointers are also closely associated with arrays and
return count; therefore provide an alternate way to access individual
} array elements.
}  Pointers provide a convenient way to represent
OUTPUT multidimensional arrays, allowing a single
multidimensional array to be replaced by a lower-
Sample Program(Static) dimensional array of pointers. This feature permits a
int a = 100, b = 200; collection of strings to be represented within a single
funct1(int y); array, even though the individual strings may differ in
{ length.
int c, d;
int funct2(int x); HOW TO DECLARE POINTER VARIABLE?
c = funct2(y);  int *ip; /* pointer to an integer */
d = (c < 100) ? (a + c) : b;  double *dp; /* pointer to a double */
return d;  float *fp; /* pointer to a float */
}  char *ch /* pointer to a character */
funct2(int x)
{ HOW TO USE POINTERS?
static int prod = 1; int main ()
prod *= x; {
return prod; int var = 20; /* actual variable declaration */
} int *ip; /* pointer variable declaration */
main() ip = &var; /* store address of var in pointer variable*/
{
int count; printf("Address of var variable: %x\n", &var );
int funct1(int y);
clrscr(); /* address stored in pointer variable */
for(count = 1; count <= 5; ++count) printf("Address stored in ip variable: %x\n", ip );
printf(“%d”, funct1(count));
getch(); /* access the value using the pointer */
return 1; printf("Value of *ip variable: %d\n", *ip );
} return 0;
OUTPUT: }
#include <stdio.h>

int main ()
{
int var = 20; /* actual variable declaration */
int *ip; /* pointer variable declaration */
ip = &var; /* store address of var in pointer variable*/

printf("Address of var variable: %x\n", &var );

/* address stored in pointer variable */


printf("Address stored in ip variable: %x\n", ip );

/* access the value using the pointer */


printf("Value of *ip variable: %d\n", *ip );

return 0;
}

Sample Run:
Address of var variable: bffd8b3c
Address stored in ip variable: bffd8b3c
Value of *ip variable: 20

POINTER IN DETAILS
 Pointer Arithmetic
- There are four arithmetic operators that can be used
in pointers: ++, - , + , -
 Array of Pointers
- You can define arrays to hold a number of pointers
 Pointer to Pointer
- C allows you to have pointer on a pointer and so on.
 Passing Pointers to Functions in C
- Passing an argument by reference or by address
enable the passed argument to be changed in the
calling function by the called function
 Return Pointer from Functions in C
- C allows a function to return a pointer to the local
variable, static variable, and dynamically allocated
memory as well.

DYNAMIC MEMORY ALLOCATION


Syntax:
Object = (datatype) malloc(sizeof(datatype));
Example:
x = (int ) malloc(10sizeof(int));
current = (struct node*) malloc (sizeof(struct node));

You might also like