0% found this document useful (0 votes)
42 views24 pages

PPS Lab Manual (Exp6-10)

Uploaded by

codm2947
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)
42 views24 pages

PPS Lab Manual (Exp6-10)

Uploaded by

codm2947
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/ 24

Ex No: 6

ARRAYS WITH POINTERS


Date:

Pointers

A pointer is a variable whose value is the address of another variable, i.e., direct address
of the memory location.Like any variable or constant,you must declare a pointer before using it
to store any variable address.The general form of a pointer variable declaration is:

type*var-name;

Here,type is the pointer's base type;it must be a valid C data type and var-name is the name of
the pointer variable. The asterisk * used to declare a pointer is the same asterisk used for
multiplication.However,in this statement the asterisk is being used to designate a variable as a
pointer.

Example:

int *ip; /*pointer to an integer*/


double*dp; /*pointer to a double*/
float*fp; /*pointer to a float*/
char *ch /*pointer to a character*/

The actual datatype of the value of all pointers,whether integer,float,character,or otherwise,is


the same, a long hexadecimal number that represents a memory address. The only difference
between pointers of different data types is the data type of the variable or constant that the
pointer points to.

There area few important operations,which we can do with the help of pointers very frequently.
(a) Define a pointer variable
(b) Assign the address of a variable to a pointer and
(c) Access the value at the address available in the pointer variable.

This is done by using unary operator* that returns the value of the variable located at the address
specified by its operand.The following example makes use of these operations−

#include<stdio.h>
intmain()
{
int var=20;/*actual variable declaration*/
int*ip; /*pointer variable declaration*/

ip=&var;/*storeaddressofvarinpointervariable*/

printf("Address Of Var Variable:%x\n",&var); /*address

stored in pointer variable*/

printf("Address Stored in i Variable:%x\n",ip);


/*access the value using the
pointer*/printf("Valueof*ipvariable:%d\n",*ip
);

return0;
}

When the above code is compiled and executed,it produces the following result−

Address of var variable:bffd8b3c


Address stored in ip variable:bffd8b3c
Value of * ip variable:20

Pointer to Array
Use a pointer to an array,and then use that pointer to access the array elements.For example,

#include<stdio.h>

void main()

inta[3]={1,2,3};

int*p=a;
for(inti=0;i<3;i++)
{
printf("%d",*p);
p++;
}
return0;
}
123

Using Array name as pointer in C

Syntax:

*(a+i)// pointer with an array

is means:

a[i]
SORTING NUMBERS IN ASCENDING ORDER

Program:

#include<stdio.h>
int main()
{
intarr[100],n,t;in
t*ptr=arr;
printf("Enter the value of n:");
scanf("%d",&n);
printf("Enter the numbers \n");
for(i=0;i<n;i++){
scanf("%d",(ptr+i));

for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(*(ptr+j)<*(ptr+i))
{
t=*(ptr+i);
*(ptr+i)=*(ptr+j);
*(ptr+j)=t;
}
}
}

for(i=0;i<n;i++)
printf("%d",*(ptr+i));

return0;
}
Ex No: 7
STRINGS
Date:

A string is an array of characters. Any group of characters defined between double quotation marks is
a constant string.

Example:
“Welcome to C”
Character strings are often used to build meaningful and readable programs. The common operations
performed on character strings are:

• Reading and Writing strings


• Combining strings together.
• Copying one string to another
• Comparing strings for equality
• Extracting a portion of a string.

Declaring and Initializing String Variables


The general form of declaration of a string variable is

charstring_name[size];
The size determines the number of characters in the string-name.Example:

charname[30];
charcity[20];

when the compiler assigns a character string to a character array, it automatically supplies a null
character (‘\0’) at the end of the string. Character arrays may be initialized when they are declared.C
permits a character array to be initialized in either of the following two forms:

staticcharcity[9]=“NEWYORK”;
staticcharcity[9]={‘N’,’E’,’W’,’‘,‘Y’,’O’,’R’,’K’,’\0’};

C also permits us to initialize a character array without specifying the number of elements.In such
cases,the size of the array will be determined automatically,based on the number of elements
initialized.

Example:
static charcity[]={‘N’,’E’,’W’,’‘,‘Y’,’O’,’R’,’K’,’\0’};

defines the array city as a nine element array.


Reading Strings from Terminal Reading
Words
The familiar input functions can f can be used with %s format specification to read in a string of
characters.

Example:
charcity[20];scanf(“%s”,city)
;

The problem with the scanf function is that it terminates its input on the first whitespace it
finds.Therefore,if the following line of text is types in at the terminal,

NEW YORK

Then only the string “NEW” will be read into the array city, since the blank space after the word
“NEW” will terminate the string.

ExampleProgram:
#include<stdio.h>
#include<conio.h>
main()
{
charname[30];
clrscr();
printf(“EntertheName:”);
scanf(“%s”,name);
printf(“Name:%s”,name);
getch();
}

Reading a Line of Text


An entire line of text can be read and stored in an array using gerchar() function.The reading is
terminated when the new line character (‘\n’) is entered and the null character is the n inserted at the
end of the string.

Example:#include<stdio.h>
#include<conio.h>
main()
{
charname[30],c;
inti=0;
clrscr();
printf(“EntertheName:”);
do
{
c=getchar();
name[i]=c;
i++;
}while(c!=’\n’);
i--;
name[i]=’\0’;
printf(“Name:%s”,name);
getch();
}

Writing Strings to Screen


The printf function with %s format is used to print strings to the screen.The format %s can be used to
display an array of characters that is terminated by the null character.

Example:
printf(“%s”,name);

We can also specify the precision with which the array is displayed.For instance,the specification
%10.4

indicates that the first four characters are to be printed in a field width of 10 columns.

Example Program: Coping one string into another


#include<stdio.h>
#include<conio.h>main
()
{
ints1[30],s2[30],i=0;
clrscr();
printf(“EntertheString:”);
scanf(“%s”,s1);
do
{
s2[i]=s1[i];
i++;
}while(s1[i-1]!=’\0’);
printf(“\nS1:%s”,s1);
printf(“\nS2:%s”,s2);
getch();
}
Arithmetic Operations on Characters
C allows us to manipulate characters the same way we do with numbers.Whenever a character
constant or character variable is used in an expression, it is automatically converted into an integer
value by the system.The integer value depends on the local character set of the system.

For example,if the machine uses the


ASCII representation,then,

x=’a’;printf(“%d”,x)
will display the number 97 on the screen.
It is also possible to perform arithmetic operations on the character constants and variables.For example,

x=’z’-1;
is a valid statement. In ASCII,the value of ‘z’ is 122 and therefore, the statement will assign the value
121 to the variable x.We may also use character constants in relational expressions.
For example,the expression

ch>=’A’&& ch<=’Z’

would test whether the character contained in the variable ch is an upper-case letter.We can convert a
character digit to its equivalent integer value using the following relationship:

x=ch-‘0’;

where x is defined as an integer variable and ch contains the character digit,For example,let us
assume that the ch contains the digit ’7’,Then,

x=ASCII value of‘7’–ASCIIvalueof‘0’


=55–48
=7
The C library supports a function that converts a string of digits into their integer values.The function
takes the form

x=atoi(string);

x is an integer variable and string is a character array containing a string of digits.Consider the following
segment of a program:
int year;
char no[]=”2007”;year=at o i(no);
no is a string variable which is assigned the string constant “2007”. The function at o i converts the
string “2007” to its numeric equivalent 2007 and assigns it to the integer variable year.
Example program:
#include<stdio.h>
#include<conio.h>
main()
{
charno[]=”2007”;
inty;
y=atoi(no);
clrscr();
printf(“\nYear:%d”,y);
getch();
}

String Handling Functions


C library supports a large number of string-handling functions that can be used to carry out
many of the string manipulations.The most commonly used string handling functions are:
strcat() -Concatena tes two strings
strcmp() -Compares two strings
strcpy() -Copies one string over another
strlen() -Finds the length of a string

strcat() Function
The strcat() function joins two strings together. It takes the following

form:strcat(string1,string2);

string1 and string2 are character arrays.When the function str c at is executed, string2 is appended to
string1.The string at string2 remains unchanged.For example,consider the following three strings:
s1=”VERY”;s2=”GOOD”;
strcat(s1,s2);
strcat function may also append a string constant to a string variable.

Example:
strcat(s1,”GOOD”);
C permits nesting of str c at functions. For example, the statement str c
at(str c at(s1,s2),s3);
concatenates all the three strings together.The resultant string is stored in s1.

Example Program:
#include<stdio.h>
#include<conio.h>
#include<string.h>
main()
{
chars1[20],s2[20];
clrscr();
printf(“Enter the First String:”);
scanf(“%s”,s1);
printf(“Enter the Second String:”);
scanf(“%s”,s2);
strcat(s1,s2)
printf(“\ns1:%s”,s1);
printf(“\ns2:%s”,s2);
getch();
}
strcmp() Function
Thestrcmp() function compares two strings identified by the arguments and has a value0 if they are
equal. If they are not, it has the numeric difference between the first non matching characters in the
strings.It takes the form:

strcmp(string1,string2);

string1 and string2 may be string variables or string constants.


Example:
strcmp(s1,s2);strcmp(s1,”GOOD”); strcmp(“ROM”,“RAM”);

The statement,
strcmp(“their”,“there”);

will return a value of-9 which is the numeric difference between ASCII “i” and ASCII “r”.That is“i”
minus “r”in ASCII code is-9. If the value is negative,string1 is alphabetically above string2.

Example Program:
#include<stdio.h>
#include<conio.h>
#include<string.h>
main()
{
chars1[20],s2[20];
intn;
clrscr();
printf(“Enter the First String:”);
scanf(“%s”,s1);
printf(“Enter the Second String:”);
scanf(“%s”,s2);
n=strcmp(s1,s2)if(n=)
printf(“\n%s=%s”,s1,s2)elsei>0)
printf(“\n%s>%s”,s1,s2);
else
printf(“\n%s<%s”,s1,s2);
getch();
}

strcpy() Function
The strcpy() function works almost like a string-assignment operator.It takes the form

strcpy(string1,string2);

and assigns the contents of string2 to string1.string2 may be a character array variable or a string
constant.For example,the statement

strcpy(city,”CHENNAI”);

will assign the string“CHENNAI”to the string variable city.Similarly,the statement strcpy(city1,city2);
will assign the contents of the string variable city2 to the string variable city1.

Example Program:
#include<stdio.h>
#include<conio.h>
#include<string.h>
main()
{
chars1[20],s2[20];
clrscr();
printf(“Enter the First String:”);
scanf(“%s”,s1);
printf(“Enter the Second String:”);
scanf(“%s”,s2);
strcpy(s1,s2)

©M.Anand59
printf(“\ns1:%” ”,s1);
printf(“\ns2:%s”,s2);
getch();
}
strlen() Function
The Strlen() function counts and returns the number of characters in a string.n = strlen(string);

where n is an integer variable which receives the value of the length of the string.

Example Program:
#include<stdio.h>
#include<conio.h>
#include<string.h>
main()
{
chars1[20],s2[20];
intn;
clrscr();
printf(“Enter the First String:”);
scanf(“%s”,s1);
printf(“Enter the Second String:”);
scanf(“%s”,s2);
n=strlen(s1);
printf(“\n Length of s1:%d”,n);
printf(“\n Length Of 2:%s”,strlen(s2));
getch();
}

Program: Sorting names in ascending order


Example Program:
#include<stdio.h>
#include<conio.h>
#include<string.h>
main()
{
char name[30][20],t[20];
int i,j,n;
clrscr();
printf(“Enter total number of names:”);
scanf(“%d”,&n);
printf(“Enter the names \n”);for(i=0;i<n;i++)
scanf(“%s”,name[i]);
for(i=0;i<n;i++)
for(j=i+1;j<n;j++)
if(strcmp(name[i],name[j])>0)
{
strcpy(t,name[i]);
strcpy(name[i],name[j]);
strcpy(name[i],t);
}
for(i=0;i<n;i++)
printf(“\n%s”,name[i]);
getch();
}
Ex No: 8
FUNCTIONS
Date:

User-DefinedFunctions
C functions can be classified into two categories, namely, library functions and
user-defined functions.Advantages of user-defined functions are

1. It facilitate stop-down modular programming as shown in the following figure.


2. The length of a source program can be reduced by using functions at appropriate places.
3. It is easy to locate and isolate a faulty function for further investigations.
4. A function may be used by many other programs.

The Form of C Functions


The general form of function is

Argument List:
The argument list contains valid variable names separated by commas.The list must be
surrounded by parentheses.The argument variables receive values from the calling
function.Some examples of functions with arguments are:
quadratic(a,b,c)sq
uare(x)

ReturnValues and theirTypes


A function may or may not send back any value to the calling function.If it does, it is
done through the return statement.There turn statement can take one of the following forms
Calling a Function
A function can be called by simply using the function name in a statement.
Example: main()
{
intp;p=mul(5,2);
printf(“%d”,p);
}

Recursion
Calling a function with in the same function is called recursion.
Example:#include<stdio.h>
#include<conio.h>
main()
{
printf(“\n Welcome to C”);
main();
}

When executed, this program will produce an output something like this:

Welcome to C
Welcome to C
Welcome to C
Welcome t

Execution is terminated abruptly;otherwise the execution will continue indefinitely.

ARITHMETIC OPERATIONS USING FUNCTION

Aim:
Program to perform arithmetic operations using function.

Algorithm:
Step1:Read a,b
Step2:Call add(a,b)
Step3:Call sub(a,b)
Step4:Call mul(a,b)
Step5:Call div(a,b)
Step6:Stop
Function add(integer a,integer b)
Print a+b
End
Function sub(integer a,integer b)
Print a-b
End
Function mul(integer a,integer b)
Print a*b
End
Function div(integer a,integer b)
Print a/b
End

Program:
#include<stdio.h>
#include<conio.h>
void add(inta,intb)
{
printf("\n%d+%d=%d",a,b,a+b);
}
void sub(inta,intb)
{
printf("\n%d-%d=%d",a,b,a-b);
}
void mul(inta,intb)
{
printf("\n%d*%d=%d",a,b,a*b);
}
void div(inta,intb)
{
printf("\n%d/%d=%f",a,b,(float)a/b);
}

main()
{
inta,b;
clrscr();
printf("Enter the numbers ");
scanf("%d%d",&a,&b);
add(a,b);
sub(a,b);
mul(a,b);
div(a,b);
getch();
}

FACTORIAL USING RECURSION

Aim:Program to find factorial using recursion.

Algorithm:

Step 1: Read the value of n


Step 2: Print fact(n)
Step 3: Stop

Function fact(integer n) Step 1: if n=1 then return 1


Step 2: else return n*fact(n-1) End

Program:
#include<stdio.h>
#include<conio.h>
long int fact(int n)
{
if (n==1) return 1;
else
return(n*fact(n-1));
}
main()
{
int n;
clrscr();
printf("Enter the value of n: ");
scanf("%d",&n);
printf("Factorial value is %ld",fact(n));
getch();
}
Ex No:
9 ARRAYS AND FUNCTIONS
Date:

In C programming, we can pass an entire array to functions, to pass the array declare a
formal parameter in one of following three ways and all three declaration methods produce
similar results because each tells the compiler that an integer pointer is going to be
received.Similarly,you can pass multi-dimensional arrays as formal parameters.

Way-1
Formal parameters as a pointer:

void my Function(int*param){
.
.
.
}

Way-2
Formal parameters as a sized array:

void my Function(intparam[10]){
.
.
.
}

Way-3
Formal parameters as an unsized array:

void my Function(intparam[]){
.
.
.
}
SUM OF N NUMBERS BY PASSING ARRAYS TO FUNCTION

Program:

#include<stdio.h>
int find Sum (int a[], int n)
{
ints=0;
for(i=0;i<n;i++)
{
s+=a
returns;
}
int main()
{
int arr[100],n,sum;
printf("Enter the value of n:");
scanf("%d",&n);
printf("Enter the numbers \n");
for(i=0;i<n;i++){
scanf("%d",arr[i]);sum=findS
um(arr,n);
printf(“The sum is %d”,sum);
return 0;
}
Ex No: 10
INPUT, OUTPUT IN PYTHON
Date:

Introduction to Python
The Python programming language was developed in the 1980's by Guido Van Rossumat Centrum
Wiskunde& Informatica (CWI) in Netherlands as a successor to the ABC language(itself inspired by
SETL) capable of exception handling and interfacing with the Amoeba operating system.

Python is an Interpreted,Interactive,Object Oriented Programming Language.Python provides


Exception Handling, Dynamic Typing, Dynamic Data Types, Classes, many built-in functions and
modules.Python is used to develop both Web Applications and Desktop Applications.Python is used
in Artificial Intelligence,Scientific Computing and Data Analytics.Python standard libraries support
XML,HTML, Email, IMAP etc.. Python is used to control Firmware updates in Network
Programming.

The Instructions(called as source code)written in Python programming language can be executed in


two modes:

1. Interactive mode:In this mode,lines of code is directly written and executed in the
Python interpreter shell,which instantaneously provide the results.
2. Normal or script mode:In this mode the source code is saved to a file with.py
extension,and the file is executed by the Python interpreter.

Input and Output Statements


In Python, the input() function is used to read input from the user. The syntax for input() function is:
input([prompt])

Here,the optional prompt string will be printed to the console for the user to input a value.The prompt
string is used to indicate the type of value to be entered by the user.

Reading String Inputs

name=input("EnteryourName:")
print("UserName:",name)

Output:
EnteryourName:Raj Kumar
UserName:Raj Kumar

To take only specified data type input from the user,mention the datatype before the input.
Example:
a = int(input("Enter an integer:")

Output Statement:

The print() function is used to print the values to the standard output.It takes zero or more number of
expressions separated by comma (,).The print() function converts those expressions into strings and
writes the result to standard output which then displays the result on screen.

The general syntax of print() function is:

print(value1,value2...,sep='',end='\n',file=sys.stdout,flush=False)

where,

value1,value2...,value-n These are the actual data values to printed.

sep - This is the separator used between each value. If there is no separator, then by default
whitespace is taken.

end - This is the character which gets printed after all values have been printed. The new line
character '\n' is the default.

file - This argument specifies where the output needs to be printed. The screen is the standard output
by default

Example-1:
print("Hi", "Hello", "Python") #will print output as follows

Hi Hello Python

Example-2:
a=10
b=50
print("A value is",a,"and","B value is",b) #will print output as follows

A value is10 and B value is 50

The above print() statement consists of both strings and integer values.
More on print(...) function:
With comma (,) as a separator: When two or more strings are given as parameters to a print(...)
function with a comma (,) as a separator, the strings are appended with a space and printed.

For example:

print("I","Love","Python")will

generate the output as

I Love Python

With space as a separator: When two or more strings are given as parameters to a print(...)function
with space as a separator,the strings are appended without a space between them.

For example:

print("I""Love""Python")will generate

the output as

I Love Python

With repeat character (*): We can print a string n times by using the repeat character (*) as shown
below:

print("ABC"*3);

will generate the output as

ABCABCABC

Output Formatting in Python

1. Python uses C-style string formatting to create new, formatted strings. The % operator also called
as 'string modulo operator' is used to format a set of variables enclosed in a "tuple" (a fixed size
list),together with a format string,which contains normal text together with"argument
specifiers",special symbols like %s and %d.

The general syntax for a format placeholder is:

%[flags][width][.precision]type

The following are some basic argument specifiers:


%s-String(or any object with a string representation,like numbers)
%d-Integers
%f-Floating point numbers
%.<number of digits>f-Floating point numbers with a fixed amount of digits for the decimal part.
%xor%X-Integers in hexadecimal representation(uppercase/lowercase)
%o-Octal representation

Example1:If we consider a single variable called 'name' with a username init,and if we would like to
print a greeting to that user,then:

name="Raj Kumar"
print("Goodmorning,%s!"%name)#This statement prints"Good morning,Raj Kumar!"

Output:
Good morning,Raj Kumar!

Example2: If we consider more than one variable,we must use a tuples of the variables as shown below:

a=10
b=20
str="Hello"
print("Thevalueofa= %d,b=%dandstr=%s"%(a,b,str))

Output:
The value of a=10,b=20 and str=Hello

Example3:

print("Total number of votes:%4d,Women votes:%2d"%(480,70))

Output:
Total number of votes:_480,Women votes:70 #Observe leading blanks space left before the first value
and no leading blank space before the second value
The first placeholder %4d is used for the first component of our tuple, i.e. 480. This number will be
printed with 4 characters. As 480 consists only of three digits, the output is padded with 1 leading
blank.
The second placeholder %2d is used for the second component of our tuple, i.e. 70. This number will
be printed with2 characters.As 70 consists two digits, the output does not have any leading blank sas
both the blanks are occupied by the digits.

The output can also be presented in a more elegant way using the str.format()
This Style Of String Formatting Eliminates The Usage Of%operator(string modulo operator).
The General Syntax Of Str.format() function is:
{}{}.format(value1,value2,...,valuen)
where,

{}{}are placeholders created by the user in the string.

value1,value2,...,value n They could be variables,integers,floating-point numbers,strings,character set c.

Note:The Number Of Values Passed As Arguments In.format(arg1,arg2..)method should always be


equal to the number of placeholders{}created by the user in the string.

The Following Are Some Basic Argument Specifiers:

{}-String(or any object with a string representation,like numbers)


{0:<number of digits>d}-Integers
{0:.<number of digits>f}-Floating point numbers with a fixed amount of digits for the decimal part.
{0:X}or{0:x}-Integers in hex representation(uppercase/lowercase)
{0:o}-Octal representation

Click on button to know about string formatting using format method in Python

Example1:

a=10
b=20
str="Hello"
print("The value of a={},b={}and str={}".format(a,b,str))Output:
The value of a=10,b=20 and str=Hello

Here the curly braces {} are used as placeholders in the format string. We can as well use the tuple
indices within each of the curly braces which correspond to its respective value in the argument list
of format as shown below.

Example2:

a=10
b=20
str="Hello"
print("Thevalueofa={0},b={1}andstr={2}".format(a,b,str))Output:
The value of a=10,b=20 and str=Hello

Here,the index 0 corresponds to the variable represented by a.Likewise the indices 1 and 2 for b and
str.

Program:
#take float number from the usernume =
float

(input("Enter a value:"))
print("%.2f"%num)print("%.6f"%num)
#print up to 2 decimal points#print

up to 6 decimal points

num1=int(input("Enter b value:"))
print("%d"%num1)print("%2
d"%num1)print("%3d"%num
1)

print("The given number in octal form is:%o" % num1)


print("The given number in hex form is:%X" % num1)

You might also like