KEMBAR78
ECE - C Unit-III | PDF | Pointer (Computer Programming) | Parameter (Computer Programming)
0% found this document useful (0 votes)
7 views21 pages

ECE - C Unit-III

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)
7 views21 pages

ECE - C Unit-III

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
You are on page 1/ 21

LECTURE NOTES

EC-405 Programming in C

UNIT - III
Strings, Functions & pointers in C
Course Contents: Define string - Reading and writing strings –String manipulation
functions –function call - Return statement, passing parameters to function- Function
calls - Pointer declaration, address and dereferencing operators.

3.1 Strings (or) Character arrays:

A string can be defined as a group of characters, terminate with a NULL. Since


there is no separate data type to declare strings, we declare a string as an array of
characters using the data type ‘char’.

Syntax:

char variable [length];


Ex:
char name[10];

Here, it declares name as a character array (string) variable that can hold a maximum of
10 characters.

 Initialization of strings:
A string can be initialized in different ways.

Ex:

(i) char name[4] = {‘s’, ‘s’, ‘n’, ‘\0’};


(ii) char name[] = “ssn”;

A string is always terminated by a NULL character ‘\0’ , which represents the end of
the string.

s s n \0

We can also declare the size much larger than the string size in the initializer.

Ex:

Char name[10] = “RAKI MRK”;

The storage will look like as: R A K I M R K

3.2.1 Reading strings from Terminal:

1.Using scanf():
 The familiar input function ‘scanf()’ can be used with ‘%s’ format specification
to read in a string of characters.
Ex: char a[10];
scanf(“%s”,a);

Department of Computer Engineering


Aditya Polytechnic Colleges (255, 249, 404), Surampalem Page 1
LECTURE NOTES
EC-405 Programming in C
 Therefore, In the case of character arrays, the ampersand (&) is not required
before the variable name.

Ex: Write a C program to read a series of words from a terminal scanf().

Program:

#include<stdio.h>
main()
{
Char a[40],b[40],c[40],d[40];
printf(“Enter text:\n”);
scanf(“%s%s%s%s”,a,b,c,d);
printf(“word1=%s\n word2=%s\n word3=%s\n word4=%s”,a,b,c,d);
}
2. Using getchar() function:
 To read a single character from the terminal, using the function getchar().
 Thegeneral form for getchar() function is as follows:
 Example: char ch;
 ch=getchar(); //Note: that getchar() has no parameters.
3. Using gets() function:
 gets() function is available in the <stdio.h> header file.
 This is a simple function withone string parameter and called as follows:
 Example: char name[20];
 gets(str);
 printf(“%s”,name);

3.2.2 Writing strings to screen

1. Using printf() function :

 The printf() function with %s format to print strings to the screen.The format %s
canbe used to display an array of characters that is terminated by the null
character.
 Example: printf(“%s”, name);

2. Using putchar() function:

 Like getchar(), C supports another character handling function putchar() to


outputthe values of character variables.It takes the following syntax:

 char ch=‘A’;

 putchar(ch); //The function putchar requires one parameter.

 This statement is equivalent to printf(“%c”,ch);


Department of Computer Engineering
Aditya Polytechnic Colleges (255, 249, 404), Surampalem Page 2
LECTURE NOTES
EC-405 Programming in C
3. Using puts() function:

 The puts() function works exactly opposite to gets() function. It outputs a


string tothe screen from memory that is form the array we declare until
reaches the null character.

 The general form of puts() function is as follows:

 puts(variable name);

 Example:

 char name[20];

 gets(name);

 puts(name);

3.6 Operation of getchar(), getch(), getche() and putchar() functions:

 These are the unformatted I/O functions in which it works only with
characterdatatype(char).

 The unformatted Input functions used in C are getch(), getche(), getchar(), gets().

1. getchar():

 It accepts one character type data from the keyboard.

 The C library function int getchar(void) gets a character from stdin.This is


equivalentto getc() with stdin as its argument.

 Syntax: Variable_name=value;

Example Program for getchar():


#include<stdio.h>
int main()
{
char c;
printf("Enter character:");
c=getchar();
printf("Character entered:");
putchar(c);
return 0;
}

2. getch():

 It accepts only single character from keyboard.The character entered


throughgetch() is not displayed in the screen(monitor).

 Syntax: variable_name=getch();
Department of Computer Engineering
Aditya Polytechnic Colleges (255, 249, 404), Surampalem Page 3
LECTURE NOTES
EC-405 Programming in C
3. getche():

 Like gtech(),getche() also accepts only single character, but unlike getch(),
getche()displays the entered character in the screen.

 Syntax: variable_name=getche();

4. putchar():

 The C library function int putchar(int char) writes a character specified by


theargument char to stdout.The declaration for putchar() function is:

 int putchar(int char);

Example Program for putchar()

#include<stdio.h>
void main()
{
char ch;
for(ch='A';ch<='Z';ch++)
{
putchar(ch);
}
return 0;
}

3.3 String handling functions

 C library supports a large number of string handling functions that can be


used tocarry out many of the string manipulations.

 The following are most commonly used string-handling functions.

1. strcat()

2. strncat()

3. strcpy()

4. strncpy()

5. strcmp()

6. strlen()

1.strcat() function:

 This function is used to concatenate( append ) one string after another


string.Thestrcat function joins two strings together.

 Syntax: strcat(string1, string 2);

Department of Computer Engineering


Aditya Polytechnic Colleges (255, 249, 404), Surampalem Page 4
LECTURE NOTES
EC-405 Programming in C

 String 1 A R R A Y S \0

 String 2 S T R I N G S \0

Execution of the statements strcat(string1,string2);

A R R A Y S S T R I N G S \0

Example for strcat() function:

#include<stdio.h>
#include<string.h>
void main()
{
char x[15]="Good";
char y[10]="Morning";
strcat(x, y);
printf("%s" , x); // Result :GoodMorning
}

2.strncat() function:

 To combine only a number of characters of the string 2 with the string 1, so we


usestrncat() function.

 Syntax: strncat(string1,string2,number);

 Example for strncat() function:


#include<stdio.h>
#include<string.h>
void main()
{
char x[15]="Good";
char y[10]="Morning";
strncat(x, y,3);
printf("%s" , x); // Result :GoodMor
}
3.strcpy() function:

 This function is used to copy one string into another string.

 Syntax: strcpy(string2,string1);

Example for strcpy() function:

#include<stdio.h>
#include<string.h>

Department of Computer Engineering


Aditya Polytechnic Colleges (255, 249, 404), Surampalem Page 5
LECTURE NOTES
EC-405 Programming in C
void main()
{
char x[10]="WELCOME";
char y[10];strcpy(y, x);
printf("%s" , y); // Result: WELCOME

4.strncpy() function:

If you want to copy only part of the string 2 to the string 1 we use strncpy() function.

Syntax: strncpy(string2,string1,number);

Example for strncpy() function:

#include<stdio.h>
#include<string.h>
void main()
{
char x[10]="WELCOME TO C CLASS";
char y[10];
strncpy(y, x,3);
printf("%s" , y); // Result: WEL
}

5.strcmp() function:

 This function is used to compare two strings. It return 0 if the strings are
sameotherwise it return non zero value.

 Syntax: strcmp(string1,string2);

 Example:

 Strcmp(name1,name2);

Example for strcmp() function:

#include<stdio.h>

#include<string.h>

void main()

char x[10]="WELCOME";

char y[10]="WELCOME";

int n;

Department of Computer Engineering


Aditya Polytechnic Colleges (255, 249, 404), Surampalem Page 6
LECTURE NOTES
EC-405 Programming in C
n=strcmp(x, y);

if(n == 0 )

printf("Strings are same");

else

{
printf("Strings are different");

6.strlen() function:

 This function is counts and returns the number of characters in a string.

 Syntax: n=strlen(string);

 Where n is an integer variable,which receives the value of the length of the string.

 The counting ends at the first null character.

Example for strlen() function:

#include<stdio.h>
#include<string.h>
void main()
{
char x[10]="Welcome";
int n;
n=strlen(x);
printf("%d" , n); // Result: 7
}

3.4 Functions:

* Function is a smallest building black of a program. It is a part of the program.

* C function can be classified into two categories of


function,
* Library function printf ( ), scanf ( ).

* user – defined function main()


Library function :

* printf and scanf belong to the category of function and it is a


default function known as the library function.

Department of Computer Engineering


Aditya Polytechnic Colleges (255, 249, 404), Surampalem Page 7
LECTURE NOTES
EC-405 Programming in C
Example :

printf (“\n Welcome”);


scanf (“%d”,&);

* It is also used other library function such as sqrt, cos, strcat, etc.,

User – defined Function:

A user –defined function has to be developed by the user


at the time of writing a program.

It is used to main( ) user – defined function can


later become a part of the C program library.

Example :

main( )

int a=30,b=10,c;

c= a+b;

printf(“\n the addition is:%d”,c);

Need for User – Defined Function:

The program may become too large and complex and as a result the task of debugging,
testing and maintaining becomes difficult.

Function Calls :

A function can be called by simply using the function name by a list of actual parameters
or arguments.

Example :

main()
{
int y;
y = mul (10,5); function call
printf(“%d\n”,y);
}

3.5 Function Declaration :

 A function declaration also known as function prototype.

Syntax : (int mul (int m, int n));

Department of Computer Engineering


Aditya Polytechnic Colleges (255, 249, 404), Surampalem Page 8
LECTURE NOTES
EC-405 Programming in C
* Function type.
* Function name.
* Parameter list.
* Terminating semicolon.

Use of return Statement:

 A function may or not send back any value to the calling function. It is done throughthe
return statement.

 The return statement can take the following syntax:

return;

or return(expression);

 Example for simple return with an expression

int mul(int x,int y)


{
int z;
z=x*y;
return(z);
}

Passing parameter techniques:


1.Call by value:

 In call by value, original value cannot be changed or modified.

 In call by value, when you passed value to the function it is locally stored by the
function parameter in stack memory location.

 If you change the value of function parameter, it is changed for the current function
only but it not change the value of variable inside the caller method such as main().

EXAMPLE PROGRAM:

#include<stdio.h>

#include<conio.h>

void swap(int a, int b)

int temp;

temp=a;

a=b;

Department of Computer Engineering


Aditya Polytechnic Colleges (255, 249, 404), Surampalem Page 9
LECTURE NOTES
EC-405 Programming in C
b=temp;

void main()

int a=100, b=200;

clrscr();

swap(a, b); // passing value to function

printf("\nValue of a: %d",a);

printf("\nValue of b: %d",b);

getch();

Output

Value of a: 200

Value of b: 100

2.Call by reference:

 In call by reference, original value is changed or modified because we pass reference


(address).

 Here, address of the value is passed in the function, so actual and formal arguments
shares the same address space.

 Hence, any value changed inside the function, is reflected inside as well as outside
the function.

EXAMPLE PROGRAM:

#include<stdio.h>

#include<conio.h>

void swap(int *a, int *b)

int temp;

temp=*a;

*a=*b;

Department of Computer Engineering


Aditya Polytechnic Colleges (255, 249, 404), Surampalem Page 10
LECTURE NOTES
EC-405 Programming in C
*b=temp;

void main()

int a=100, b=200;

clrscr();

swap(&a, &b); // passing value to function

printf("\nValue of a: %d",a);

printf("\nValue of b: %d",b);

getch();

Output

Value of a: 200

Value of b: 100

Function Call:

 A function cab be called by simply using the function name followed by a list of
actual parameters (or arguments), enclosed in parentheses.

 Example:

main()

int a;

A=add(10,15);

/*Function call*/

printf(“%d\n”,a);

}
int add(int x,int y)

int z; //local variable


z=a+b; //x=10,y=15

Department of Computer Engineering


Aditya Polytechnic Colleges (255, 249, 404), Surampalem Page 11
LECTURE NOTES
EC-405 Programming in C
return(z);
}

 A function call is a postfix expression. The operator (..) is a very high level
of sprecedence.

 In a function call, the function name is the operand and the parentheses set(..) which
contains the actual parameters is the operator.

 The actual parameters must match the function formal parameters in type, order
andnumber. Multiple actual parameters are separated by commas.

Function prototype:

 All functions in C program, must be declared, before they are invoked. A function
declaration (also known as function prototype) consists of four parts.

 Function type(return type)

 Function name

 Parameter list

 Terminating semicolon

 The syntax for function prototype is as follows:

 Function_type Function_name (parameter list);

 Example: int add( int a,int b);

 void display(void) /*function does not take any parameter*/


 When we place the declaration above all the functions (in the global declaration
section), the prototype is referred to as a global prototype.

 Such declarations are available for all the functions in the program.

 When we place it in a function definition (in the local declaration section), the
prototype is called a local prototype.

 Such declarations are primarily used by the functions containing them.

Elements of Function:

 A function definition, also known as function implementation shall include the


following elements:
4. Local variable declarations
1. Function name
5. Function statements and
2. Function type
6. Return statement
3. List of parameters

Department of Computer Engineering


Aditya Polytechnic Colleges (255, 249, 404), Surampalem Page 12
LECTURE NOTES
EC-405 Programming in C

 All the six elements are grouped into two parts, namely

 Function header (function name,type,list of parameters)

 Function Body (local variables,statements and return statement)

 The general form of a function definition can be as follows:

Function_type function_name(parameter list)

local variable declaration;

Statement1;

Statement2;

………….

………..

…………….
return statement;

 Some examples of function definitions are as follows:

a) int sum(int a,int b,int c)

printf(“sum=%d”,a+b+c);
return;
}

b) void display(void)

printf(“No Parameters,no type”);

}
Storage classes:
 Storage Classes Storage class tells :

1. Where the variable is stored.

2. Initial value of the variable.

3. Scope of the variable. (which a variable is accessed.)

4. Life of the variable.

Department of Computer Engineering


Aditya Polytechnic Colleges (255, 249, 404), Surampalem Page 13
LECTURE NOTES
EC-405 Programming in C

 There are four types of storage classes:

1. Automatic storage class

2. Register storage class

3. Static storage class

4. External storage class

Automatic storage class:

 Variable is stored in memory. Default value is garbage value.

 Scope is local to the block where it is declared Life is, with in the block in where it is
declared.

 Automatic variable can be declared using the keyword auto. Eg: auto int a;
 By default all variables are automatic int a; same as auto int a;

Example 1:

main()
{
auto int i=10;
printf(“%d”,i);
}

Output: 10

Example 2:

main()
{
auto int i;
printf(“%d”,i);
}
Output: 1002

 In example 1, i value is initialised to 10.So,output is 10.

 In example 2, i value is not initialized. So,compiler reads i value is a garbage value.

Register storage class:

 Variable is stored in a register instead of RAM.

 Default value is garbage value.

 Scope is local to the block where it is declared Life is, with in the block in where it is
declared.
Department of Computer Engineering
Aditya Polytechnic Colleges (255, 249, 404), Surampalem Page 14
LECTURE NOTES
EC-405 Programming in C
 When a variable stored in register, it access high speed.

 The no of registers are limited in a processor, if the registers are not free it will
convert to automatic variable.

 The mostly length of the registers are 2 bytes, so we cannot store a value greater
than its size, if it so it will covert to automatic variable.

 Register variable can be declared using the keyword register.

 Eg: register int a;

Static Storage Class:

 Variable is stored in memory. Default value is 0.

 Scope local to the block. Life is, value of the variable persists between different function
calls.

 static variable can be declared using the keyword static.

 Eg: static int a;

 static can also be defined within a function.

 The variable cannot reinitialized when the function is called.

 This inside a function static variable retains its value during various calls.

Example

main()

void show();

show();

show();

void show()

static int a=10;

printf(“%d”,a);

a++;

Department of Computer Engineering


Aditya Polytechnic Colleges (255, 249, 404), Surampalem Page 15
LECTURE NOTES
EC-405 Programming in C

1. Output will be 10 11

2. second time a=10; will not execute

External Storage Class:

 Variable is stored in memory. Default value is 0.

 Scope is end of the program.

 Life is, with in the block in end of the program external variable can be declared
using the keyword extern.

 extern is used to give a reference of a global variable that is visible to ALL the
program files.

Example

extern int a=10;

void main()

void show();
Output:
printf(“a= %d”,a);

show(); a= 10 10

void show()

printf(“%d”,a);
}

• The extern keyword is used before a variable to inform the compiler that the
variable is declared some where else.

Recursion :

* Recursion is a special case of this process, where a function calls itself. A very simple
example of recursion is present in the function.

* A called function in turn calls another function a process of ‘chaining’ occurs it used
factorial function.
Example :

#include<stdio.h>

Department of Computer Engineering


Aditya Polytechnic Colleges (255, 249, 404), Surampalem Page 16
LECTURE NOTES
EC-405 Programming in C
void main()
{
int number;
long fact;
printf("Enter a number: ");
scanf("%d", &number);
fact = factorial(number);
printf("Factorial of %d is %ld\n", number, fact);
getch();
OUTPUT:
}
Enter a number: 5
int factorial(int n)
Factorial of 5 is 120
{
if (n == 0)
return 1;
else
return n * factorial(n-1);
}
3.10 Pointer:

• A variable that holds a memory address. This address is the location of another object in
the memory.

• Pointer as an address indicates where to find an object.

 Not all pointers actually contain an address example NULL pointer.

 Value of NULL pointer is 0.

• Pointer can have three kinds of content in it

1) The address of an object, which can be dereferenced.

2) A NULL pointer.

3) Invalid content, which does not point to an object.

(If p does not hold a valid value, it can crash the program)

• If p is a pointer to integer, then

– int *p

Department of Computer Engineering


Aditya Polytechnic Colleges (255, 249, 404), Surampalem Page 17
LECTURE NOTES
EC-405 Programming in C
 It is possible in some environments to have multiple pointer values with different
representations that point to same location in memory.

 But make sure if the memory is deleted using delete or if original variable goes out
of scope.

Declaring pointer:

Data-type *name;

 * is a unary operator, also called as indirection operator.

 Data-type is the type of object which the pointer is pointing.

 Any type of pointer can point to anywhere in the memory.

 * is used to declare a pointer and also to dereference a pointer.

 When you write int *, compiler assumes that any address that it holds points to an integer type.

 m= &count;

it means memory address of count variable is stored into m.

& is unary operator that returns the memory address.

i.e. & (orally called as ampersand) is returning the address.

 so it means m receives the address of count.

 Suppose, count uses memory Address 2000 to store its value 100. so,
m=&count means m has 2000 address.
count=100
2000
 q= *m

 it returns the value at address m. value at address 2000 is 100.


 so, q will return value 100.

 i.e. q receives the value at address m.

Accessing the address of variable using & operator:

 Accessing the address of a variable can be done with the help of & operator
available in C. We have already seen the use of this address operator in the
scanf function.

 The operator & immediately preceding a variable returns the address of the
variable associated with it.

 Example: p=&a;

 If x is an array, then expressions such as

Department of Computer Engineering


Aditya Polytechnic Colleges (255, 249, 404), Surampalem Page 18
LECTURE NOTES
EC-405 Programming in C
 &x[0] and &x[i+3] are valid and represent the address of 0th and (i+3)th
elements of x.

Accessing value of a variable through pointer:

 Accessing value of a variable through pointer can be done by using unary operator
*(asterisk), usually known as the indirection operator.

 Another name of the indirection operator is the dereferencing operator.

 int volume *p,n;

 volume = 259;

 p= &volume;

 n=*p;

 C Program to illustrate the use of * opeartor.

#include<stdio.h>

void main()

int x=10,y;

int *ptr;

ptr=&x;

y=*ptr;

printf("value of x is:%d",x);

printf("%d is stored at address %u",x,&x);

printf("%d is stored at address %u",*&x,&x);

printf("%d is stored at address %u",*ptr,ptr);

printf("%d is stored at address %u",ptr,&ptr);

printf("%d is stored at address %u",y,&y);

*ptr=20;

printf("Now x=%d",x);

Pointer Arithmetic:

 Pointer variables can be used in expressions. If prt1 and prt2 are declared
Department of Computer Engineering
Aditya Polytechnic Colleges (255, 249, 404), Surampalem Page 19
LECTURE NOTES
EC-405 Programming in C
andinitialized pointers, then the following statements are valid.

 y=*ptr1 * *ptr2;

 same as (*ptr1)*(*ptr2)

 sum=sum+*ptr1;

 z=7*-*ptr2/*ptr1; same as (7*(-(*ptr2)))/*ptr1

 *ptr2=*ptr2+40;

 C allows us to add integers to or substract integers from pointers.


#include<stdio.h>
void main()
int number=50;
int *p;
p=&number;
printf("Address of p variable is %d \n",p);
p=p+3;
printf("After adding by 3 Address of p variable is %d \n",p);
getch();
}
Output: For 64 bit integer variable means 4 bytes
Address of p variable is 3134300
After adding by 3 Address of p variable is 3134312
For 32 bit integer variable will be 2 bytes
Address of p variable is 3134300
After adding by 3 Address of p variable is 3134306
Difference between Address Operator(&) and De-Referencing Operator(*)

S.No Address Operator De-Referencing Operator

1. Address Operator can be denoted by&. De-Referencing Operator can be


denoted by *.

2. The & operator can be called as The * operator can be called as “value at
“address of”. address”.

3. Another name for & opeator is Another name for De-Referencing


address operator. Operator is indirection Operator.

4. The & operator can be used only The * operator can be used by means of
with a simple variable are an array symbolic names.
element.

Department of Computer Engineering


Aditya Polytechnic Colleges (255, 249, 404), Surampalem Page 20
LECTURE NOTES
EC-405 Programming in C
Example: Example:

int number; int number,*ptr;

a=&number; number=200;

ptr=&number;

n=*ptr;

Department of Computer Engineering


Aditya Polytechnic Colleges (255, 249, 404), Surampalem Page 21

You might also like