PPS Lab Manual (Exp6-10)
PPS Lab Manual (Exp6-10)
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:
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*/
return0;
}
When the above code is compiled and executed,it produces the following result−
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
Syntax:
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:
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’};
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();
}
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();
}
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.
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=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();
}
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);
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();
}
User-DefinedFunctions
C functions can be classified into two categories, namely, library functions and
user-defined functions.Advantages of user-defined functions are
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)
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
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();
}
Algorithm:
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.
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.
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.
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.
print(value1,value2...,sep='',end='\n',file=sys.stdout,flush=False)
where,
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
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
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);
ABCABCABC
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.
%[flags][width][.precision]type
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:
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,
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)