Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 136

Introduction to C Language

by Supreet Singh
Overview of C
◦ Dennis Ritchie is the creator of C
◦ Created at Bell Laboratories
C is a structured programming language
C supports functions that enables easy
maintainability of code, by breaking large
file into smaller modules
Comments in C provides easy readability
C is a powerful language
Features of C
Portable Language
◦ C language is machine independent. Source Code
written using C can be compiled on any machine

Structured Language
◦ problem is solved using a divide and conquer
approach
Comments
 Comments are used to document programs and improve readability
 In C a comment will start with /* and ends with */
 Syntax: /* Comments */
/*This is a single line comment */

/* This is a multiline
* comment in C */

/************************************************
* This style of commenting is used for functions
************************************************/

 The C++ style comments will start with a // and ends at the end of that line
Variables
 An identifier for the data in the program
 Hold the data in your program
 Is a location (or set of locations) in memory where a value can be
stored for use by a program
 A quantity that can change during program execution
 Declaration
<<Data type>> <<variable name>>;
int a;
 Definition
<<varname>>=<<value>>;
a=10;
 Usage
<<varname>>
a=a+1; //increments the value of a by 1
Variable names- Rules
 A variable name can either begin with an
alphabet or underscore
 No other special character except
underscore is allowed
 Variable names are case sensitive
 Keywords cannot be used as variable
names
Constants
 A constant is a named or unnamed value, which does not change
during the program execution.
 Named constants are defined by preceding an initialized variable
definition with the keyword const
Example:

const double dPi = 3.141592;


const int iDegrees = 360;
const char cQuit = 'q';

 Unnamed constants are often called literals.


 Example:
3.141592 and 360 in the above definitions are literal
constants
Data types in C(1 of 3)
Data types determine the following:
◦ Type of data stored
◦ Number of bytes it occupies in memory
◦ Range of data
◦ Operations that can be performed on the data

C supports the following data types:


◦ int – for storing whole numbers
◦ char – for storing character
values, represents a single
character
◦ float
◦ Double
Data types in C(2 of 3)
Primitive data types
◦ int, float, double, char
Aggregate data types
◦ Arrays come under this category
◦ Arrays can contain collection of int or float or
char or double data
User defined data types
◦ Structures and enum fall under this category
Data types in C(3 of 3)
Modifiers alter the meaning of the base
type to more precisely fit a specific need

C supports the following modifiers along


with data types:
◦ short
◦ long
◦ signed
◦ unsigned
Header files
The files that are specified in the include
section is called as header file
These are precompiled files that has some
functions defined in them
We can call those functions in our
program by supplying parameters
Header file is given an extension .h
C Source file is given an extension .c
Program structure
A sample C Program

#include<stdio.h>
int main()
{
--other statements
}
A complete program
#include <stdio.h>
int main(int argc, char **argv){ Pre processor
printf(“Hello World”); directive

/* Return success code to the


operating system */
return 0; Entry point for program
execution
}

Each instruction in a
C program
terminates with a
semicolon (;)
The main Function
Entry point of any C program

The operating system locates function ‘main’ and


starts execution from there

Using
the signature int main (int argc,
char** argv) is a good programming practice

The function ‘main’ should return zero if the


program performed its job successfully or any
other non zero value to indicate error
Contd.
When a file is executed, the start point is
the main function
From main function the flow goes as per
the programmers choice.
There may or may not be other functions
written by user in a program
Main function is compulsory for any c
program
Running a C Program
Type a program
Save it
Compile the program – This will generate
an exe file (executable)
Run the program (Actually the exe
created out of compilation will run and
not the .c file)
In different compiler we have different
option for compiling and running. We
give only the concepts.
Preprocessor Directives (1 of 3)
 C provides many built-in functions, also called as library functions
 These functions are declared in header files
 To use them, we need to include proper header files in our program
using
#include statement
e.g.:
#include <stdio.h>

 More Header files in C:


 math.h
 string.h
 limits.h
…
…
 types.h
Preprocessor Directives (2 of 3)
 #define directive tells the preprocessor to search and replace a pattern in
code
 A #define directive is sometimes also known as a Macro
 Example:
#define PASSPERCENT 65
int main(int argc, char **argv) {
/* PASSPERCENT macro being used in code */
printf (“Pass percentage is: %d\n”, PASSPERCENT);
/* Return a success code to Operating System */
return 0;
}
Preprocessor Directives (3 of 3)
A preprocessed code looks like this:

int main(int argc, char **argv){


printf (“Pass percentage is: %d\n”, 65);
return 0;
}
Input and Output
Input
◦ scanf(“%d”,&a);
◦ Gets an integer value from the user and stores
it under the name “a”
Output
◦ printf(“%d”,a)
◦ Prints the value present in variable a on the
screen
Formatted output using printf (1 of 4)
 Writes onto screen (standard output)
 Syntax:
printf(“Conversion Specifier-list”,variable-1,
variable-2,…………………);
Conversion Purpose Example
Specifier
%d To print a signed integer printf(“%d”,iValue);
%x To print an integer as in Hex format printf(“%x”,iValue);
%f To print a float value printf(“%f”,fValue);
%c To print a character printf(“%c”,cChoice);
(both signed and unsigned)
%u To print an unsigned integer printf(“%u”,iResult);
%ld To print a signed long integer printf(“%ld”,lNumber);
%lu To print an unsigned long integer printf(“%lu”,lFactorial);
%lf To print a double value printf(“%lf”,dAverage);
%s To print a string (Strings are discussed printf(“%s”,acEmpName);
later)
%x To print a hex value printf(“%x”,iNumber);
%% To print % sign printf (“Percentage %d%%”,
iScore);
Formatted output using printf (2 of 4)
 Example:

int iEmployeeId = 1001;


double dSalary = 7600.00;
printf(“Employee Id %d” , iEmployeeId);
printf(“Salary %lf”, dSalary);
Formatted output using printf (3 of 4)
 An escape sequence is interpreted to have a special meaning in the
screen output
 All the escape sequences must be preceded by a back slash (\)
 Escape sequences are non printable characters
 Escape sequences are generally used with ‘printf’ function

Escape Sequence Purpose


\n New line character. This moves the cursor to the next
line
\t Prints a sequence of blank spaces
\\ Prints back slash (\)
\” Prints the double quote (“)
\’ Prints a single quote (‘)
\a Causes an audible sound on the computer
Formatted output using printf (4 of 4)
 Example:
int iEmployeeId = 1001;
double dSalary = 7600.00;
printf(“Employee Id %d\n“, iEmployeeId);
printf(“Salary %lf\n”, dSalary);
Reading Keyboard Input – scanf function
(1 of 2)
 ‘scanf’, uses a similar conversion specifier like ‘printf’ to read different types of data
from the keyboard
 The parameters passed to the function ‘scanf’ after the format are pointers (address
of the variables) to the data types being read from keyboard
Syntax:
scanf(”Conversion Specifier”, address of variables);

 Example:
/* To read an integer */ Common programming error:
printf(“Enter a number: ”);
scanf(“%d”, &iCount);

Not including ‘&’ before the
variable name
/* To read a float */
printf(“Enter Amount: ”); •
Missing comma between the
scanf(“%f”, &fAmount);
conversion specifier and variable
name
•Mismatch in the number and type
of conversion specifier for the used
variables
Reading Keyboard Input – scanf function
(2 of 2)
/* Reading multiple input */
short iDay,iMonth,iYear;
printf("Enter day, month and year in
format(dd mm yyyy)");
scanf("%d%d%d",&iDay,&iMonth,&iYear);
/* Reading character input */
char cChoice;
printf(“Want to continue “);
fflush(stdin);
scanf(“%c”,&cChoice);

Note:Use fflush(stdin) statement to clear the input buffer


before reading a char/string using a scanf
ASCII Character Set
 ASCIIis the acronym for American Standard
Code for Information Interchange

 Code
used to represent English alphabets,
numerical digits and commonly used symbols as
numbers

 Other
Character sets: EBCDIC (Mainframes) and
UNICODE (2 byte character set)

C language uses ASCII and Java uses Unicode to


represent non numeric characters
ASCII Table
Operators
The following are the operators that are used
in a program

◦ Arithmetic operators
◦ Assignment operator
◦ sizeof operator
◦ Logical operators
◦ Relational operators
◦ Increment and Decrement Operators
Type Casting
 Temporary conversion of one data type into another
 In some situations, the compiler will automatically convert
one data type into another
 Type casting is an overhead for the compiler and should be
used only when it is absolutely necessary
 Example:
float fResult;
fResult = 7 / 2 ;

The variable fResult will store 3.0 instead of 3.5


To get the ‘float’ value, the expression should be:

fResult = 7.0 / 2; or fResult = 7 / 2.0; or


fResult = 7.0 / 2.0; or
fResult = (float) 7 / 2; or fResult = 7 /
(float) 2;
Type def
The typedef operator is used for creating
alias of a data type
For example I have this statement
typedef int integer;
Now I can use integer in place of int
i.e instead of declaring int a;, I can use
integer a;
This is applied for structures too.
sizeof operator
 sizeof operator is used to find the number of bytes
required for a data type
 sizeof operator returns an integer
 Example:
int iNumber=5;
float fValue = 6.7;

printf(“The size of int is %d bytes\n”,sizeof(iNumber));


printf(“The size of float is %d bytes\n”,sizeof(fValue));
printf(“The size of char is %d bytes\n”,sizeof(char));
printf(“The size of double is %d
bytes\n”,sizeof(double));
Increment and Decrement Operators
 Operators ++ and -- are called as increment and decrement operators

 These operators increment or decrement the variable’s value by 1

 They are also called as unary operators because they have only one
operand to operate

 If the operator is used before the operand, it is prefix and if the


operator is used after the operand, it is postfix

 Example:
++iValue and -–iValue is called as prefix
iValue++ and iValue-- is called as postfix
Control Structures
A control structure refers to the way in which the
Programmer specifies the order of executing the
statements

 The following approaches can be chosen depending on


the problem statement:
Sequential
In a sequential approach, all the statements are executed in the
same order as it is written
Selectional or Conditional
In a selectional approach, based on some conditions, different set
of statements are executed
Iterational or Repetition or Looping
In an iterational approach certain statements are executed
repeatedly
Simple if Statement (1 of 2)
In a simple ‘if’ statement, a condition is
tested

 If the condition is true, a set of


statements are executed

 If the condition is false, the statements


are not executed and the program control
goes to the next statement that
immediately follows the if block
Simple if Statement (2 of 2)
Syntax:
if (condition) {
set of statements;
}
Example:

if (iDuration >= 3) {

/* Interest for deposits equal to or


more than
3 years is 6.0% */
fRateOfInterest = 6.0;
}
else Statement (1 of 2)
 In simple ‘if’ statement, when the condition is
true, a set of statements are executed. But when it
is false, there is no alternate set of statements
 The statement ‘else’ provides the same
 Syntax:
if (condition) {
Statement set-1;
}
else {
Statement set-2;
}
Next Statement;
else Statement (2 of 2)
 Example:

if (iDuration >= 3) {
/* If duration is equal to or
more than 3 years,
Interest rate is 6.0 */
fRateOfInterest = 6.0;
}
else {
/* else, Interest rate is 5.5 */
fRateOfInterest = 5.5;
}
else if Statement (1 of 3)
The ‘else if’ statement is used to check for a
sequence of conditions

When one condition is false, it checks for the


next condition and so on

When all the conditions are false the ‘else’


block is executed

Once the condition is true, all the other ‘else


if’ statements are skipped
else if Statement (2 of 3)
 Syntax:
if (condition-1) {
Statement set-1;
}
else if (condition-2) {
Statement set-2;
}
………………………………
………………………………
else if (condition-n) {
{
Statement set-n;
}
else {
Statement set-x;
}
Next Statement;
else if Statement (3 of 3)

• Always use ‘else if’ when a sequence of


conditions has to be tested

• Using only ‘if’ will make the compiler to


check all the conditions. This
 increases the execution time
Nested if Statement
 An ‘if’ statement embedded within another ‘if’ statement is called as nested
‘if’
 Example:

if (iDuration > 6 ) {
if (dPrincipalAmount > 25000) {
printf(“Your percentage of incentive is 4%”);
}
else {
printf(“Your percentage of incentive is 2%”);
}
else {
printf(“No incentive”);
}
What is the output of the following
code snippet?
iResult = iNum % 2;
if ( iResult = 0) {
printf("The number is even");
}
else {
printf("The number is odd"); The output is
} "The number is
odd"

CASE 1: When iNum is 11

CASE 2: When iNum is 8


The output is
"The number is odd"
switch case Statement (1 of 2)
The ‘switch’ statement is a selectional
control structure that selects a choice from
the set of available choices

It is very similar to ‘if’ statement

But ‘switch’ statement cannot replace ‘if’


statement in all the situations
switch case Statement (2 of 2)
 Syntax:
switch(integer variable or integer expression or
character variable) {
case integer or character constant-1 : Statement(s);
break;
case integer or character constant-2 : Statement(s);
break;
……………
……………
case integer or character constant-n : Statement(s);
break;
default: Statement(s);
break;
}
Iterational Control Structures
 Iterational (repetitive) control structures are used to repeat certain
statements for a specified number of times

 The statements are executed as long as the condition is true

 These kind of control structures are also called as loop control


structures

 There are three kinds of loop control structures:


◦ while
◦ do while
◦ for
while Loop Control Structure (1 of
2)
A ‘while’ loop is used to repeat certain
statements as long as the condition is true

When the condition becomes false, the


‘while’ loop is quitted

This loop control structure is called as an


entry-controlled loop because, only when
the condition is true, are the statements
executed
while Loop Control Structure (2 of
2)
Syntax:
while (condition) {
Set of statements;
}
Next Statement;
Example:
unsigned int iCount = 1;
while (iCount <= 3) {
printf(“%u “,iCount);
iCount++;
}
The above code snippet prints “1 2 3”
do while Loop Control Structure (1
of 2)
The ‘do while’ loop is very similar to
‘while’ loop. In ‘do while’ loop, the
condition is tested at the end of the loop

Because of this, even when the condition


is false, the body of the loop is executed
at least once

This is an exit-controlled loop


do while Loop Control Structure (2
of 2)
 Syntax:
do {
Set of statement(s);
} while (condition);
Next Statement;
 Example:
int iNumber, iSum = 0;
do {
printf(“Enter a number.Type 0(zero) to
end the input ”);
scanf(“%d”,&iNumber);
iSum = iSum + iNumber;
} while (iNumber != 0);
for Loop Control Structure (1 of 3)
The ‘for’ loops are similar to the other
loop control structures

The ‘for’ loops are generally used when


certain statements have to be executed a
specific number of times
for Loop Control Structure (2 of 3)
 Syntax:
for (Initialization; Termination-
Condition; Increment-Step){
Set of statement(s);
}
Next Statement;
 Example:
int iCount;
for (iCount = 1; iCount <= 10;
iCount++){
printf(“%d\n”,iCount);
}
for Loop Control Structure (3 of 3)
Advantage of for loops:
◦ All the three parts of a loop (initialization,
condition and increment) can be given in a
single statement
◦ Because of this, there is no chance of user
missing out initialization or increment steps
which is the common programming error in
‘while’ and ‘do while’ loops
Selection between while, do while
and for loops
A ‘for’ loop is used when the number of
times the loop is executed is well known

A ‘while’ loop is used when the number of


times the loop gets executed is not known
and the loop should not be executed when
the condition is initially false

A ‘do while’ loop is used when the number


of times the loop gets executed is not known
and the loop should be executed even when
the condition is initially false
Nested Loops
 A loop with in another loop is called as nested loop
 Example:
while (1 == iFlag) {
for (iCount=1;iCount<=10;iCount++){
statements;
}
}

 The innermost for loop executes once for each iteration of the
outermost loop
 Question:
if the iterations in the outermost loop is 3 and the iterations in
the innermost loop is 4, then how many times the statements
in the innermost loop gets executed?
Quitting the Loops – break
Statement
 Forces the termination of a loop

 When a ‘break’ statement is encountered in a loop, the loop


terminates immediately and the execution resumes with the
next statement following the loop

 If it is used in a nested loop, it quits only the loop from where


it is called

 Note:
 ‘break’ statement can be used in an if statement only when the
if statement is written in a loop (while, do while or for)
 Just an if statement with ‘break’ (without loops) leads to
compilation error
break Statement Example
for (iLoopIndex = 2; iLoopIndex < iNumber; iLoopIndex++) {
/* It is not a prime if it is divisible by any other
number */
if (iNumber % iLoopIndex == 0) {
cPrime = ‘N’;
break; /* Quit the loop */
}
}
/* After break statement, continue from here */
if (‘Y’ == cPrime) {
printf(“%d is a prime number”,iNumber);
}
else {
printf(“%d is not a prime number”,iNumber);
}
Continuing the Loops - continue Statement
(1 of 2)
 ‘continue’ statement forces the next iteration of the loop
to take place and skips the code between ‘continue’
statement and the end of the loop

 In case of for loop, ‘continue’ makes the execution of


the increment portion of the statement and then
evaluates the conditional part

 In case of while and do-while loops, ‘continue’ makes


the conditional statement to be executed
Continuing the Loops - continue Statement
(2 of 2)
Example:
for(iCount = 0 ; iCount < 10; iCount++) {
if (4 == iCount) {
continue;
}
printf(“%d”, iCount);
}

The above code displays numbers from


0 to 9 except 4.
Terminating the program using
exit() function
 The function ‘exit’ is used to quit the program

 Terminates the program and returns the status code to the


operating system

 This function is defined in ‘stdlib.h’ header file

 Syntax:
exit(int status);

 The status code zero indicates that the program completed


successfully

 If there is a failure any other code has to be returned


Arrays
Arrays
• An array is a series of variables, all being same
type and size
• Each variable in an array is called an array
element
• All the elements are of same type, but may
contain different values
• The entire array is contiguously stored in memory
• The position of each array element is known as
array index or subscript
• An array can either be one dimensional (1-D) or
two dimensional (2-D) or Multi-dimensional
Declaring a 1-D Array
 Syntax:
data-type arrayname[size];
 Example:
int aiEmployeeNumbers[6];
float afSalary[6];

 The array index starts with zero

 The valid array indexes for the above declared array is 0 to 5

 When an array is declared inside a function without initializing it, the elements
have unknown (garbage) values and outside the function the elements have
zero/default values
Declaring and Initializing arrays (1
of 2)
Arrays can be initialized as they are declared
Example:
int aiEmployeeNumbers[] = {15090, 15091,
15092, 15093,15094, 15095};

The size in the above case is optional and it is


automatically computed
In the above example size of the array is 6 and it
occupies 6 * 4 = 24 bytes (6 is the size of the
array and 4 is the number of bytes required to
store one integer on Windows platform)
Declaring and Initializing 1-D
arrays (2 of 2)
When an array is partially initialized within a
function the remaining elements will be
garbage values and outside any function the
remaining elements will be zero values
Example:
int aiEmployeeNumbers[6] =
{15090, 15091, 15092};

In the above example, the array indexes from


3 to 5 may contain zero or garbage values
2-D Arrays
 A 2-D array is used to store tabular data in terms of rows and
columns

 A 2-D array should be declared by specifying the row size and the
column size

 To access the individual elements, the row and the column should be
supplied

 The 2-D array is essentially a one dimensional array wherein each


element itself is another array, hence an array of arrays

 As far storage is concerned, the row elements are in continuous


locations of memory hence called row major ordering in C language

 The table type visualization of rows and columns is therefore only


for convenience
Declaring and using 2-D Arrays
 A 2-D array can be declared by specifying the maximum size for rows and
columns
 Syntax:
data type arrayname [Row Size][Column Size];
 Example:
int aiEmployeeInfo[3][2];
The above declaration declares aiEmployeeInfo with 3 rows and 2 columns

 To access the individual elements row index (starts from zero) and the
corresponding column index (starts from zero) should be supplied
 Example:
printf(“%d”,aiEmployeeInfo[0][1]);

The above printf references the information at 0th row 1st column
Initializing 2-D Arrays(1 of 2)
 A 2-D array can be initialized as given below:

int aiEmployeeInfo[3][2]= {101,1,102,1,103,2};

In the above declaration,


◦ 101, 102 and 103 refers to employeeids and they are
stored in [0][0], [1][0] and [2][0] positions
◦ 1,1 and 2 refers to Job Codes and they are stored in
[0][1], [1][1] and [2][1] positions
Initializing 2-D Arrays (2 of 2)
 A 2-D array can be declared without specifying the row size if
it is initialized

 Example:
int aiEmployeeInfo[][3]=
{101,1,102,1,103,2};
Since there are six initial values and the column size is 3, the
number of
rows is taken as 2

 If the column size is not supplied then there will be a


compilation error
Pointers
Pointers(1 of 5)
A pointer is a special variable which stores the
address of a memory location. It can be the address
of a variable or directly the address of a location in
memory
A variable is a name given to a set of memory
locations allocated to it

 For every variable there is an address, which is the


starting address of its set of memory locations
 Ifa variable called p holds the address of another
variable i then p is called as a pointer variable
and p is said to point to i
Pointers -Address of Operator(2 of
5)
 Ampersand (&) is the “address of” operator .It is used to fetch the
memory address of a variable
 * is called the indirection operator, dereferencing or value at
address operator and is used with a pointer variable to fetch the
value at a given memory location
 Both these operators are used with pointers
iNumber
Memory
Address

8FFE 5

&iNumber
Pointers - Address of Operator(3 of
5)
 To print the address of a variable, precede the variable with an
ampersand (&) Since an address is an unsigned integer,
%u is used as a conversion specifier

 Example:
int iNumber = 100;
printf(“The value is %d\n”,iNumber);
printf(“The address is %u\n”,&iNumber);
printf(“The address in hexa decimal is
%x\n”,&iNumber);

An address can be printed in hexa decimal form


using %x as the conversion specifier
Pointers(4 of 5)
 To declare a pointer variable, use the following syntax
data-type *pointerName;
Example:
1. int *piCount;
This declaration tells the compiler that piCount will be
used to store the address of an integer value – in other
words piCount points to an integer variable.
2. float *pfBasic;
This statement declares pfBasic as a pointer variable which
can contain the address of a float variable.

Note: The size of pointer variable on Windows platform is 4 bytes.


However it may vary from one platform to another.
Pointers(5 of 5)
Example:
int iCount = 8;
int *piCount;
piCount = &iCount;
printf(“Value=%d”,*piCount);

◦ iCount: an integer variable


◦ piCount: an integer pointer
◦ &: the “address of” operator
◦ * : the “indirection” operator
Reading Contents of a variable
using Pointers
 To access the value at the address stored in the pointer, use
the following syntax *pointervariable
 Example:
printf(“%d”, *piCount);
 Here the * operator preceding piCount will fetch the value at the
address stored in piCount

 Using ‘==’ operator (Equal to) on pointers, will check whether


both pointers being compared are pointing to the same address
or not

 Uninitialized pointers may point to any memory location

 Using * (indirection operator) on uninitialized pointers may


result in program throwing a run time error
NULL Pointers
Using a pointer without initializing it to any
valid address may result in data corruption or
even program crash

To differentiate between initialized and un


initialized pointers, we usually set an un
initialized pointer to NULL

Example:
/* Initializing pointer to NULL */
int *piCount = NULL;
Strings
Strings (1 of 2)
A string is a series of characters in a group
that occupy contiguous memory

Example:

“CDAC”
“Information Technology”

 A string should always be enclosed with in


double quotes (“)
Strings (2 of 2)

In memory, a string ends with a null


character ‘\0’

Space should be allocated to store ‘\0’ as


part of the string

A null character (\0) occupies 1 byte of


memory
Declaration of Strings (1 of 2)
Syntax:
char variablename [Number_of_characters];
 Example:
char acEmployeeName[20];
Here 20 implies that the maximum number of characters can
be 19 and one position is reserved for ‘\0’
Since a character occupies one byte, the above array occupies
20 bytes (19 bytes for the employee name and one byte for
‘\0’)
Declaration of Strings (2 of 2)
/* Declare String as a char pointer */

char *pcName = “Cdac”;

/* Declaring a string as a character array */


char acName[ ] = “Cdac”;
Think why ‘\0’ requires only one byte!!
Printing Strings to Console (1 of 2)

 Using Character pointer:


char *pcProg = “C Fundamentals”;
printf(pcProg);
printf(“This is %s course”,pcProg);

 Using Character Array:


char acProg[] = “C Fundamentals”;
printf(acProg);
OR
printf(“%s”, acProg );
printf(“This is %s course”,acProg);
Printing Strings to Console (2 of 2)

Printing a string as part of a formatted


string
int iCourseId = 27;
char *pcProg = “C
Fundamentals”;
/* print the courseId (Int)
and Course name(char*) */
printf(“The Id of this course
is %d and this course is %s

\n”,iCourseId, pcProg);
strlen() Function
 strlen() function is used to count the number of characters in the string

 Counts all the characters excluding the null character ‘\0’

 Syntax:
unsigned int strlen (char string[]);
Here string[ ] can be a string constant or a character pointer or a character
array and the function returns unsigned int

 Example:
strlen(“Programming Fundamentals”); returns 24

strlen(acItemCategory); returns the number of characters


in the
character array ‘acItemCategory’
Input of Strings – scanf and gets functions

scanf(“%s”, acItemCategory);
scanf(“%s”, &acItemCategory[0]);

Both the input functions are valid. The first one passes the base
address (Address of the first element) implicitly
The second function passes the address of the first element explicitly

gets(acItemCategory);
gets(&acItemCategory[0]);

This is an unformatted function to read strings


String Handling functions
 The following are the string functions that are
supported by C
strlen()strcpy() strcat()
strcmp()strcmpi() strncpy()
strncat() strncmp()
strnicmp()

 These functions are defined in string.h header file

 Allthese functions take either a character pointer or a


character array as an argument
strcpy() Function
 strcpy() function is used to copy one string to another

 Syntax:
strcpy (Dest_String , Source_String);
 Here Dest_string should always be variable
 Source_String can be a variable or a string constant
 The previous contents of Dest_String, if any, will be over written

 Example:
char acCourseName[40];
strcpy(acCourseName , “C Programming”);

The resultant string in ‘acCourseName’ will be “C Programming”


strcat() Function
 strcat() function is used to concatenate (Combine) two strings

 Syntax
strcat( Dest_String_Variable ,
Source_String ) ;
 In this, the Destination should be a variable and Source_String can
either be a string constant or a variable.
 The contents of Dest_String is concatenated with Source_String
contents and the resultant string is stored into Dest_String variable.

 Example:
char acTraineeFpCourse [50] = “The course is
“;
strcat(acTraineeFpCourse,”Oracle 10G”);

The resultant string in ‘acTraineeFPCourse’ will be “The course is


Oracle 10G”
strcmp() Function (1 of 2)
strcmp() function is used to compare two
strings

strcmp() does a case sensitive (Upper case


and lower case alphabets are considered to be
different) comparison on strings

Syntax:
int strcmp( String1 ,
String2 );
◦ Here both String1 and String2 can either be a variable or a string
constant
strcmp() Function (2 of 2)
 strcmp() function returns an integer value

 If strings are equal, it returns zero

 Ifthe first string is alphabetically greater than the


second string then, it returns a positive value

 If the first string is alphabetically less than the second


string then, it returns a negative value

 Example:
strcmp(“My Work”, “My Job”); returns a
positive value
strcmpi() Function
strcmpi() function is same as strcmp()
function but it is case insensitive

Example:
strcmpi(“My WoRk” , “MY work”); returns zero
Functions
Functions
 A function is a section of a program that performs a specific task

 Function groups a number of program statements into a unit and


gives it a name. This unit can be reused wherever it is required in
the program

 Functions employ the top down approach and hence becomes


easier to develop and manage
main() User defined function

Function
call
Advantages of Functions
 The functions can be developed by different people and can be
combined together as one application

 Solving a problem using different functions makes


programming much simpler with fewer defects

 Easy to code,modify,debug and also to understand the code

 Functions support reusability ie. once a function is written it


can be called from any other module without having to rewrite
the same. This saves time in rewriting the same code
Passing values to functions and
returning values
 Functions are used to perform a specific task on a set of values

 Values can be passed to functions so that the function performs the


task on these values

 Values passed to the function are called arguments

 After the function performs the task, it may send back the results to
the calling function

 The value sent back by the function is called return value

 A function can return back only one value to the calling function
through a return statement

 Function may be called either from within main() or from within


another function
Elements of a Function
 Function Declaration or Function Prototype :
 The function should be declared prior to its usage

 Function Definition :
 Implementing the function or writing the task of the function
 Consists of
• Function Header
• Function Body

 Function Invocation or Function call:


 To utilize a function’s service, the function have to be invoked
(called)
Declaring Function Prototypes (1 of
2)
A function prototype is the information to the compiler
regarding the user-defined function name, the data type
and the number of values to be passed to the function
and the return data type from the function

 Thisis required because the user-defined function is


written towards the end of the program and the ‘main’
does not have any information regarding these
functions

 Thefunction prototypes are generally written before


‘main’. A function prototype should end with a
semicolon
Declaring Function Prototypes (2 of
2)
 Function Prototypes declare ONLY the signature of the function before
actually defining the function
 Here signature includes function name, return type, list of parameter data
types and optional names of formal parameters

 Syntax:
Return_data_type FunctionName (data_type arg1,
data_type arg2,...,data_type
argn );

 Example:
int fnValidateDate(int iDay,int iMonth, int iYear);

In the above example, iDay, iMonth and iYear are


optional. The same can also be written as:

int fnValidateDate(int,int, int);


Writing User-Defined Functions
 A function header and body looks like this:
Return-data-type function-name(data-type argument-
1,
data-type argument-2,….){
/* Local variable declarations */
/* Write the body of the function here */
Statement(s);
return (expression);
}
 The return data type can be any valid data type
 If a function does not return anything then the ‘void’ is the return
type
 A function header does not end with a semicolon
 The ‘return’ statement is optional. It is required only when a value
has to be returned
Writing User-Defined Functions
Return data type Arguments
(Parameters)
int fnAdd(int iNumber1, int iNumber2){
/* Variable declaration*/
Function header
int iSum;

/* Find the sum */ Function Body


iSum = iNumber1 + iNumber2;

/* Return the result */


return (iSum);
}
Can also be written as return iSum;
Returning values
 The result of the function can be given back to the calling functions

 ‘return’ statement is used to return a value to the calling function

 Syntax:
return (expression) ;

 Example:
return(iNumber * iNumber);
return 0;
return (3);
return;
return (10 * iNumber);
Calling User-Defined Functions (1
of 2)
A function is called by giving its name and passing the
required arguments

 The constants can be sent as arguments to functions


/* Function is called here */
iResult = fnAdd(10, 15);

 Thevariables can also be sent as arguments to


functions
int iResult,iNumber1=10, iNumber2=20;
/* Function is called here */
iResult = fnAdd(iNumber1, iNumber2);
Calling User-Defined Functions (2
of 2)
Calling a function which does not return
any value
/* Calling a function */
fnDisplayPattern(15);

Callinga function that do not take any


arguments and do not return anything
/* Calling a function */
fnCompanyNameDisplay();
Function Terminologies
Function Prototype
void fnDisplay() ;
Calling Function
int main(int argc, char **argv){
fnDisplay();
return 0;
} Function Call Statement

void fnDisplay(){
printf(“Hello World”);
}

Called Function
Function Definition
Formal and Actual Parameters
The variables declared in the function
header are called as formal parameters

The variables or constants that are passed


in the function call are called as actual
parameters

The formal parameter names and actual


parameters names can be the same or
different
Functions – Example (1 of 2)
Function Prototype
int fnAdd(int iNumber1, int iNumber2);

int main(int argc, char **argv) {


int iResult,iValue1=5, iValue2=10;
/* Function is called here */
iResult = fnAdd(iValue1, iValue2);
printf(“Sum of %d and %d is %d\n”,iValue1,
iValue2,iResult);
return 0;
}

Actual Arguments
Functions – Example (2 of 2)
Formal Arguments

/* Function to add two integers */


int fnAdd(int iNumber1, int iNumber2){
/* Local variable declaration*/
int iSum;
iSum = iNumber1 + iNumber2; /* Find the sum */
return (iSum); /* Return the result */
}

Return value
Parameter Passing Techniques
When a function is called and if the
function accepts some parameters, then
there are two ways by which the function
can receive parameters
◦ Pass by value
◦ Pass by reference
Pass by Value (1 of 3)
When parameters are passed from the
called function to a calling function, the
value of the actual argument is copied
onto the formal argument

Since the actual parameters and formal


parameters are stored in different memory
locations, the changes in formal
parameters do not alter the values of
actual parameters
Pass by Value (2 of 3)
void fnUpdateValues(int iNumber1, int iNumber2);
int main(int argc, char **argv) {
int iValue1=100, iValue2=250;
printf("\n\nBefore calling the function: ");
printf("ivalue1=%d iValue2=%d\n\n",iValue1,iValue2);
/* Call the function */
fnUpdateValues(iValue1, iValue2);
printf("After calling the function: ");
printf(" ivalue1=%d iValue2=%d\n\n",iValue1,iValue2);
return 0;
}
void fnUpdateValues(int iNumber1, int iNumber2){
/* Update the values */
iNumber1 = iNumber1 + 15;
iNumber2 = iNumber2 - 10;
}
Pass by Value (3 of 3)

main() fnUpdateValues()

100 115
200 240

End of function fnUpdateValues


Pass by Reference (1 of 4)
Addresses of actual parameters are passed

The function should receive the addresses


of the actual parameters through pointers

The actual parameters and formal


parameters if referencing the same
memory location, then the changes that
are made become permanent
Pass By Reference (2 of 4)
void fnUpdateValues(int *piNumber1, int *piNumber2);

int main(int argc, char **argv){


int iValue1=100, iValue2=250;
printf("\n\nBefore calling the function: ");
printf("ivalue1=%diValue2=
%d\n\n",iValue1,iValue2);
/* Call the function and send the address of the
variables */
fnUpdateValues(&iValue1, &iValue2);
printf("After calling the function: ");
printf("ivalue1=%diValue2=
%d\n\n",iValue1,iValue2);
return 0;
}
Pass By Reference (3 of 4)
void fnUpdateValues(int
*piNumber1, int *piNumber2){
*piNumber1 = *piNumber1 +
15;
*piNumber2 = *piNumber2 -
10;
}
Pass by Reference (4of 4)

a
main() fnUpdateValues()

115 Address of
iValue1

240 Address of
iValue2

End of function fnUpdateValues


Recursive Functions
Recursive Functions (1 of 6)
 When a function calls itself it is called as Recursion

 Many mathematical, searching and sorting algorithms, can be simply


expressed in terms of a recursive definition

 A recursive definition has two parts:


Base condition : When a function will terminate
Recursive condition :The invocation of a recursive call to the function

 When the problem is solved through recursion the source code looks
elegant
Recursive Functions (2 of 6)
/* Finding the factorial of an integer using a
recursive function */

int fnFact(int iNumber); /* Function


Prototype */

int main(int argc, char **argv) {


int iFactorial;
iFactorial=fnFact(4);
printf("The factorial is
%d\n",iFactorial);
return 0;
}
Recursive Functions (3 of 6)
int fnFact(int iNumber){
int iFact;
if (iNumber <= 1) {
return 1;
}
else {
iFact = iNumber * fnFact(iNumber -
1);
}
return iFact;
}
Recursive Functions (4 of 6)
 Find the output of the following code snippet when the function is
called as fnReverse(5);

void fnReverse(int iValue) {


if (iValue > 0) {
fnReverse(iValue-1);
}
printf("%d\t",iValue);
}

Output will be 0 1 2 3 4 5
Recursive Functions (5 of 6)
 Find the output of the following code snippet when the function is
called as fnReverse();
/* Global Variable Declaration */
int giValue = 5;
void fnReverse(){
if (giValue > 0) {
giValue--;
fnReverse();
}
printf("%d\n",giValue);
}

Output: prints 0 six times


Recursive Functions (6 of 6)
 Find the output of the following code snippet when the function is
called as fnReverse();
char gacString[] = "Test";
int giIndex = 0;
void fnReverse(){
if (gacString[giIndex] != '\0') {
giIndex++;
fnReverse();
}
giIndex--;
if (giIndex >= 0){
printf("%c",gacString[giIndex]);
}
}
Output: Prints the string “tseT”
Structures
Structures (1 of 2)
 Data used in real life is complex

 Theprimitive data types which are provided by all


programming languages are not adequate enough to handle the
complexities of real life data

 Examples:

Date: A date is a combination of day of month, month and year


Address: Address of a person can consist of name, flat
number, street, city, pin (zip) code and state
Account Details: Bank account information can contain the
account number, customer ID and Balance
Structures (2 of 2)
A structure is a set of interrelated data

A structure is a set of primitive data types which


are related to business and are grouped together to
form a new data type

A structure is a mechanism provided by the


language to create custom and complex data types
Declaring a Structure (1 of 4)
A structure can be declared using the ‘struct’ keyword
 The set of variables that form the structure must be declared with a valid
name similar to declaring variables
 Each variable inside a structure can be of different data type or same data
type
 Syntax:
struct tag-name{
data-type member-1;
data-type member-2;
……
data-type member-n;
};
 A structure declaration ends with a semicolon
Declaring a Structure (2 of 4)
Date is a simple data structure, but not available as
a built-in data type

A date has three components:


◦ day of month (integer, Range: 1-31)
◦ month (integer, Range: 1-12)
◦ year (integer, four digits)
Declaring a Structure (3 of 4)
struct date {
short iDay;
short iMonth;
short iYear;
};

 In the above structure declaration, date is the tag-name

 Each variable declared inside a structure is known as a ‘member’


variable

 In the date structure, iDay, iMonth and iYear are member variables
Declaring a Structure (4 of 4)
A structure is generally declared globally above
function ‘main’

The member variables cannot be initialized


within a structure declaration. It will lead to
compilation error if member variables are
initialized with in structure declaration

The structure is allocated memory only after


declaring a variable of type structure
Accessing Member Variables of a Structure
(1 of 3)
 Each member variable in a structure can be accessed individually
 Once a structure is declared, it can be used just like any primitive
data type
 In order to access the structure members, a variable of structure
should be created
 Example:
struct date sToday;

 To access individual members of the structure, the ‘.’ operator is used


 Example:
sToday.iDay = 30;
sToday.iMonth = 4;
sToday.iYear = 2007;
Accessing Member Variables of a Structure
(2 of 3)
int main (int argc, char** argv) {
/* Declare two instances of date structure */
struct date sToday, sTomorrow;

/* Set 'day', 'month' and 'year' in instance


sToday */
sToday.iDay = 30;
sToday.iMonth = 4;
sToday.iYear = 2007;
/* Set sTomorrow's date */
sTomorrow.iDay = 1;
sTomorrow.iMonth = 5;
sTomorrow.iYear = 2007;
Accessing Member Variables of a Structure
(3 of 3)
/* Print the contents of the structure
*/
printf ("Today's date is: %d-%d-%d\n",
sToday.iDay, sToday.iMonth,
sToday.iYear);
printf ("Tomorrow's date is: %d-%d-
%d\n",
sTomorrow.iDay, sTomorrow.iMonth,
sTomorrow.iYear);
}
QUESTIONS?
FEEDBACK
THANK YOU.

You might also like