Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
36 views

C Programming Lab Notes

It's good for use for 1st year btech students of ang college of engineering

Uploaded by

Anusree Kalkaran
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
36 views

C Programming Lab Notes

It's good for use for 1st year btech students of ang college of engineering

Uploaded by

Anusree Kalkaran
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 30
NISHI KUMAR] | 2101149434 APPLIED PYTHON PROGRAMMING LAB PYTHON: Python is a general-purpose interpreted, interactive, object-oriented, and high-level programming language. It was created by Guido van Rossum during 1985- 1990. Like Perl, Python source code is also available under the GNU General Public License (GPL). Features of Python 1. Easy to code: It's syntax is closer to English language 2. Free and Open source: Python language is freely available at the official website. It’s source code is also available to the public. Object Oriented Language: Python supports object oriented programming and concepts of Classes and encapsulation. High Level Language: When we write programs in python, we do not need to remember the System architecture,nor we need to manage the memory. . Extensible: We can write us some Python code into C or C++ language and also we can compile that code in C/C++ language Portable: If we have python code for windows and if we want to run this code on other platforms such as Linux,Unix and Mac then we do not need to change it,we can run this code on any platform Interpreted Language: There is no need to compile python code and this makes it easier to debug our code. The source code of python is converted into an immediate form called bytecode. 8, Lange Standard Library: Python has a large standard library which provides a rich set of module and functions so you do not have to write your own code for every single thing, 9, Dynamically typed Language: The type (for example- int, double, long, etc.) for a variable is decided at run time not in advance because of this feature we don’t need to specify the type of variable. B.Tech 1" Year | ECE 1 INTUHCEH © scanned ith oxen scar NisHi KUMARI | 2101140434 CYCLE-1 1. Downloading and installing Python and modules a) Python 3 on Linux ‘Aim: To download and install Python on Linux Software Required: internet 2. Python 3.x Software Procedure: Python comes preinstalled on most of the Linux distributions 11, we can simply check the Python Version which is already installed on your system by running the python -V or python ~version command on your terminal. 2, When Python is not already installed: The output will be something like this- 3. When Python is already Installed : The output will be something like this- Python x.x.x For Example: Python 3.7.1- 4, Install Python on Linux from Package Manager i) The following command could be used to install the latest version of Python on almost every Linux system. B.Tech 1" Year | ECE INTUHCEH © seamed oeSaner NISHI KUMARI |2101: ii) Also, you can mention the particular version of Python you want to install shown below : il) Type Y and press Enter to continue. The Package manager will download and install the python for you. Result: Hence, Python 3 is downloaded and installed on Linux. b) Python 3 on Windows Aim: To download and install Python 3 on Windows. Software Required: 1. Internet 2. Python 3.x Software Procedure: Installing Python on Windows: It takes a series of few easy steps. Step 1 - Select Version of Python to Install Step 2 - Download Python Executable Installer from the Website www.oython.org Step 3 - Run Executable Installer Step 4 ~ Verify Python is installed on Windows B.Tech 1" Year | ECE 3 100434 INTUHCEH © scanned ith oxen scar NisHi KUMARI | 2101140434 | Foleo) Python Releases for Windows Install Python 3.10.5 (64-bit) Sele ata Now instal Python with detaut stings. or roote Customise to enable or cade fetus python [Dinsal launcher fora user (recommended windows [ZAea Python 3.10 to PATH Result: Hence, Python 3 is downloaded and installed on Windows. B.Tech 1" Year | ECE 4 INTUHCEH © seamed oeSaner NisHI KUMARI | 2101140434 ©) pip3 on Windows and Linux: ‘Aim: To download and install pip3 on Windows and Linux. Software Required: L.Internet 2. Web Browser Procedure: Installing pip3 on Windows: i) To install or upgrade pip3 in a Windows environment thet already has Python3 installed ii) Download the latest version of get-pip.py from https://bootstrap.pypa.io/ i) You can also use the curl command to download get-pip.py:curl Db00' sof iv) CD into the directory where get-pip.py was downloaded, and enter the following command to install pip3 and its dependencies: python3 get-pip.py vv You can verify that pip3 is installed by navigating to the default pip3 installation directory, eg, C:\python38\scripts\, and enter: pip3 version Install pip3 Ubuntu and Debian Linux: i) Enter the following command to update Linux: sudo apt update ii) Enter the following command to install pip3: sudo apt install python3-pip ii) The above command will aso install all pip3 dependencies. iv) To find the location where pip3 installs packages in Ubuntu Linux, enter: which pip3 vv) Output should be similar to: /ust/bin/pip3 Result: Hence, pip3 is downloaded and installed on Widows and linux. 4) Installing numpy and scipy: ‘Aim: To download and install numpy and scipy Software Required: 1. Internet 2.Web browser B.Tech 1" Year 5 INTUHCEH © seamed oeSaner NisHI KUMARI | 2101140434 Procedure: Step 1: Check Python Version Before you can install NumPy, you need to know which Python version you have. This programming language comes preinstalled on most operating systems (except Windows; you will need to install Python on Windows manually). Most likely, you have Python 2 or Python 3 installed, or even both versions. To check whether you have Python 2, run the command: python -V For example: python3 Step 2: Install Pip The easiest way to install NumPy is by using Pip. Pip a package manager for installing and managing Python software packages. Finally, verify you have successfully installed Pip by typing pip -V and/or pip3 -V in the terminal window. Step 3: Install NumPy With Pip set up, you can use its command line for installing NumPy, Install NumPy with Python 2 by typing: pip install numpy Pip downloads the NumPy package and notifies you it has been successfully installed. To install NumPy with the package manager for Python 3, run: pip3 install numpy . As this is 2 newer version of Python, the Numpy version also differs as you can seein the image below. BeTech 1" Year | ECE 6 INTUHCEH © scanned ith oxen scar NisHI KUMARI | 2101140434 east Poetry cerres eT aN Cre eer Ts) Step 4: Verify NumPy Installation Use the show command to verify whether NumPy is now part of you Python packages: pip show Numpy ‘And for Pip3 type: pip3 show numpy The output should confirm you have NumPy, which version you are using, as well as where the Package is stored. Step 5: Import the NumPy Package Aiter installing NumPy you can import the package and set an alias for it. To do so, move to ‘the python prompt by typing one of the following commands: (Once you are in the python or python3 prompt you can import the new package and add an alias for it (in the example below itis np) Install SciPy using the pip command Python consists of pip command which is an official package installer. It is a package manager, we can install, delete, or update any package. We need to install pip for using pip command.once the requirement is satisfied we can use the pip command in terminal. First, we open the command prompt. We then use the following pip command, B.Tech 1" Year |ECE 7 INTUHCEH © seamed oeSaner NISHI KUMARI | 210110434 install scip We can then enter the python interpreter and import Scipy using following commands: python import scipy as sp We can perform the version check using the following command: sp.version.version Using SciPy package manager Basically, a package manager comprises a set of tools. Its used for automatically installing packages and then updating and deleting them. The downfall of using package managers is that they consist of older versions and does not contain many upgrade options. Result: Hence, numpy and scipy is installed, ) Installing jupyterlab: Aim: To download and install jupyterlab. Software Required: 1. Internet B.Tech 1" Year |ECE 8 INTUHCEH © scanned ith oxen scar Procedure: Installing jupyter notebook on windows i) Open the command prompt il) Type the syntax as follows: pip install jupyter ill) The jupyter notebook is successfully installed iv) Now to open the jupyter notebook follow the syntax: Jupyter notebook _ v) Now we can work on jupyter notebook Result: Hence, jupyterlab is installed B.Tech 1" Year | ECE 9 NISHI KUMARI | 210110434 INTUHCEH © Scamet INISHI KUMARI | 2101140434 2. Introduction to Python3 a) Printing your biodata on the screen : To print my biodata on the screen Software Required: 1. Jupyter Notebook 2. Latest version of python Program: name = input("Enter your name: ") dls = input("Enter your class: ") n= input("Enter your roll no.:") sec = input("Enter your section: ") lg = input("Enter your college: print("Name: "name) print("Class: ",cls) print("Roll No.: ",en) print( "Section: ",sec) print("College: "cig) Output: Result: Hence, Biodata is printed on the screen. BeTech 1" Year | ECE 10 INTUHCEH © Seaman oeSaner b) Printing all the primes less than a given number ‘Aim: To print all the primes less than a given number. Software Required: 1. Jupyter Notebook 2. Latest version of Python Program: nsint(input( Enter n:‘) x-list(range(1,n+1)) for jin range(2.n+1} for in range(2,) iff%i==0) xremoveti) break print(List of primes less than Output Result: Hence, all the primes less than a given number is printed. B.Tech 1" Year | ECE 1 NisHI KUMARI | 2101140434 INTUHCEH © seamed oeSaner NISHI KUMARI | 210110434 €) Finding all the factors of a number and show whether it is a perfect number, i.e, the sum of all its factors (excluding the number itself) is equal to the number itself ‘Aim: To find all the factors of a number and to show whether itis a perfect number or not Software Required: 1. Jupyter Notebook 2. Latest version of Python Procedure: int{input("Enter the number: ")) result=0 print("Factors of ",n," are: for iin range(1,n): print() for jin range(1,n) if(n%j == 0} result = result + print(n, end="") print({True: "is a Perfect number", False: "is not a Perfect number"} [result Output: Result: Hence, the factors of a number is found and checked whether it is perfect number or not. 2 INTUHCEH © seamed oeSaner B.Tech 1° Year | ECE NISHI KUMARI | 2101140434 3. Defining and Using Functions a) Write a function to read data from a file and display it on the screen ‘Aim: To write a funcion to read data from a file nd display it on the screen. Software Required: 1 Jupyter Notebook 2. Latest version of Python Progra file = opent'tap.txt','w') file.write(beautiful’) file.close() def file(tap) with openitap,'r') as f text = fread) print{text) tap = input( Enter file name with .txt extension’) file(tap) Output: Enter file nane with .trt extension beautiful Result: Hence, data is read from a file and displayed it on the screen. B.Tech 1" Year | ECE 3 INTUHCEH o 'b) Define a boolean function is_palindrome() ‘Aim: To define a boolean function is_palindrome(). Software Required: 1. Jupyter Notebook 2. Latest version of Python Program: name = input'Enter string: ') def is_palindrome(name}: lion = name[::-1] if name == lion: return True else return False is_palindrome(name) Output Result: Hence, 2 boolean function is_palindrome() is defined B.Tech 1" Year | ECE 14 NiSHI KUMARI | 2101140434 INTUHCEH © seamed oeSaner NISHI KUMARI | 2101140434 c) Write a function collatz(x) which does the followi Return the number of steps it takes for x= 1 ‘Aim: To write a collatz(x) function ( ifxis odd then x=3x+1 ; if x is even then x=x/2). Software Required: 1. Jupyter Notebook 2. Latest version of Python Program: def collatz(n): count = 0 while ni if n%2==0 nen/2 else: n= (3*n}+1 count+=1 print(n) return count; 3t{input(Enter a number: ')) res = collata(n) print(f'The number of steps is {res}") Output: Result: Hence, collatz(x) function is coded. xis odd, x = 3x +1; if xis even,then x=x/2. B.Tech 1" Year | ECE 15 INTUHCEH o NISHI KUMARI | 210110434 4) Write a function N(m, s) = exp(-(x-m)2/(2s2))/sqrt(2n)s that computes the Normal distribution ‘Aim: To write 2 function that computes the Normal distribution. Software Required: 1. Jupyter Notebook 2. Latest version of Python Program: import matplotiib.pyplot as pit import numpy as np def normal_distribution(m,s}: xenp.linspace(1,100,100) pit. plotinp.exp(-(x-m)**2/(2*s**2))/(np.sqrt(2*np. pits), linewidt pit.show() m=float(input{"Enter the values of m:")) s=fioat(input("Enter the values of s here m>s:")) normal_distribution(m,s) Output: Result: Hence, a function is written that computes Normal distribution. B.Tech 1" Year | ECE 16 INTUHCEH o NISHI KUMARI | 2101140434 4, The package numpy a) Creating a matrix of given order m xn Aim: To create a matrix of given order m xn. Software Required: 1. Jupyter Notebook 2. Latest version of Python Program: import numpy as np m linput(’Enter row size) nsint{input('Enter column size:')) matrix=np.random.random|size=(m,n)) print(matrix) Output: enter row size: [3] Enter colum size: [2] [0.665758 0.95126172] [e.s663772_ 0122334640) [e:76821895 0136576806] Result: Hence, a matrix of given order m x nis created. B.Tech 1" Year | ECE uv INTUHCEH © seamed th ean NISHI KUMARI | 210110434 b) Creating a matrix containing random numbers in the range 1 to 99999 ‘Aim: To create a matrix containing random numbers in the range 1 to 99999. Software Required: 1. Jupyter Notebook 2. Latest version of Python Program: Import numpy as np m=int(input('Enter row size:)) int{input('Enter column size:’)) matrix=np.random.randint(1,99999,size=(m,n)) print(matrix) Output [20se5 13177 [39663 97302] [75822 29555 [a7621 35962, Result: Hence, a matrix containing random numbers in the range 1 to 99999 is created, B.Tech 1" Year | ECE 18 INTUHCEH © seamed oeSaner NISHI KUMARI | 210110434 ©) Write a program that adds,subtracts and multiplies two matrices.Provide an interface such that, based on the prompt, the function (addition, subtraction, multiplication) should be performed Aim: To write a program that adds,subtracts and multiplies two matrices. Software required: 1. Jupyter Notebook 2. Latest version of Python Program: import numpy as np miint{input('Enter row size) t(input('Enter column size:')) matrixi=np.random.randint(1,10,size=(m1,n1)) print(matrixt) import numpy as np m2zint(input(‘Enter row size’) n2=int{input('Enter column size:')) ‘matrix2=np.random.randint(1,10,size=(m2,n2)) print(matrix2) print(' add=matrix1¢matrix2 subtract=matrix1-matrix2 multiplication=matrixi.dot(matrix2) print('L.add 2.subtract 3.multiplication’) azint(input("Enter a number:’)) ifasst: print(add) elif: print(subtract) elif a B.Tech 1" Year | ECE 19 INTUHCEH © seamed oeSaner NISHI KUMARI | 2102140434 print(multiplication) Output: Result: Hence, a program that adds,subtracts and multiplies two matrices is written. B.Tech 1" Year | ECE 20 INTUHCEH © seamed oeSaner NISHI KUMARI | 210110434 4d) Write a program to solve a system of n linear equations in n variables using matrix inverse ‘Aim: To write a program to solve a system of n linear equations in n variables using matrix Inverse. Software Required: 1 Jupyter Notebook 2. Latest version of Python Program: import numpy as np meint{input('Enter row sizes’) 1(input( Enter column size) if (m==n}: print("Enter all the values of‘ itemt=tist(map|intinput() split())) ‘Acnp.atray(item1).reshape(m,n) print("matrix=\n",A) print("Enter al the values of '8 item2=list(map(int,input().split())) B=np.arraylitem2).reshape(row,1) print("matrix=\n",8) Ainverse=np.linalg.inv(a) X-Ainverse.dot(B) print("X=",X) else print("Linear equations are not solvable") B.Tech 1" Year | ECE a INTUHCEH © seamed oeSaner NISHI KUMARI [2101140434 Output: Enter colum size:[2 Cd {0 2] tt enter all the values of *a {04 taj Result: Hence, a program to solve a system of n linear equations in n variables using matrix Inverse is written, B.Tech 1" Year | ECE 2 INTUHCEH © seamed oeSaner NISHI KUMARI | 2101140434 5, The package scipy and pyplot a) Finding if two sets of data have the same mean value ‘Aim: To find if two sets of data have the same mean value . Software Required: 1. Jupyter Notebook 2. Latest version of Python Program: import numpy as np print("Enter all the values of list1 separated by space:") list=list(map(int,input().split())) print("Enter all the values of list2 separated by space:") list2=list(map(int,input().split())) print(listt) print(list2) meani=np.mean(list1) mean2=np.mean(list2) print(meani) print(mean2) print("The two lists have the same mean value") else: print("The two lists don't hve same mean value") Output: enter all the values of list? separated by space | [eons Epa 5h fe The two lists have the same mean value Result: Hence, if two sets of data have the seme mean value is checked. B.Tech 1" Year | ECE 2B INTUHCEH © scanned tn onEN Scanner NISHI KUMARI | 210110434 b) Plotting data read from a file Aim: To plot a data read from a file Software Required: 1. Jupyter Notebook 2. Latest version of Python Program: import pandas as pd from matplotlib import pyplot as pit filename=input("Enter filename with extension:") f=pd.read_excel(filename) print(df) figure=pit figure(figsize=(10,5)) xedf[{fruit!] yedff'quantity’] plt.bar(x,y,width=0.4) pltxlabel( fruit) pltylabel( quantity’) plttitle(’Bar Graph’) plt.show() Output: inter File rane with extenslenci Users Geskton beektop sample excel lex fruit quantity 2 orange pple ° 6 B.Tech 1" Year | ECE 2 INTUHCEH o NISHI KUMARI | 210110434 Bar Graph Result: Hence, a data from a ile is plotted. B.Tech 1" Year | ECE 25 INTUHCEH © scanned ith oxen scar d) Plotting a histogram of a given data set ‘Aim: To plot a data read from a file Software Required: 1. Jupyter Notebook 2. Latest version of Python Program: import numpy as np from matplotlib import pyplot as pit print("Take 20 random integers in the range of 1 to 200") Xenp.random.randint(1,200,20) print(x) NISHI KUMARI | 210110434 figure=plt.hist(X,edgecolor='black’,color="pink’Jinewidth=2, bins=(0,20,40,60,80,100,120,140, 160,180,200)) pit.title('Histogram') pit.show() Output: Result: Hence, histogram is plotted from a given data set. B.Tech 1" Year | ECE 27 INTUHCEH o NISHI KUMARI | 2101140434 6. The strings package a) Read text from a file and print the number of lines, words and characters ‘Aim: To read text from a file and print the number of lines, words and characters. Software Required: 1. Jupyter Notebook 2. Latest version of Python Program: feinput("Enter file name with .txt extension:") file=open(f,'r') ko w=0 0 for line in file: bet for word in line.split) for char in word: ce print(f"™" no. of lines are {I} no. of words are (w) no. of char are {c} file.close() Output: Enter file rane with txt extension: [Eapsb no, of lines are 1 no. of words are 3 no, oF char Result: Hence, the text is read from a file and the number of lines, words and characters are printed. B.Tech 1" Year | ECE 2 INTUHCEH © seamed th ean NISHI KUMARI | 2102140434 b) Read text from a file and return a list ofall n letter words beginning with a vowel ‘Aim: To read text from a file and return a lst of all n letter words beginning with a vowel. Software Required: 4. Jupyter Notebook 2. Latest version of Python Program: jput("Enter file name with .txt extension:") file-open(f,'r’) isint(input("Enter the length of the word:" v) for line in file hea for word in line split(): jlen(word) if if word startswith(a): print(word) Result: Hence, text is read from a file and a list of all n letter words beginning with a vowel is returned. B.Tech 1" Year | ECE 28 INTUHCEH © seamed oeSaner NISHI KUMARI | 210110434 4d) Plot a histogram of words according to their length from text read from a file ‘Aim: To plot a histogram of words according to their length from text read from a file. Software Required 4. Jupyter Notebook 2. Latest version of Python Program: from matplotlib import pyplot as plt filename=input(Enter file name with .txt extension’) words=[] word_count=| with open(filename,'r')asf for line inf: words.extend(line.split()) for word in words: word_count.append(len(word)) print("The list of length of words read from file’ word_count) figure=plt.figure(figsize=(10,5)) plt-hist(word_count,edgecolor=black’ Jinewidth=1,rwidth=3) plt.xticks{ticks=10,1,2,3,4,5,6,7,8)) plt.yticks(ticks=[0,1,2,3,4,5]) pit.title('words') plt.xlabel('length of words’) plt.ylabell'number of words') pit. show() B.Tech 1" Year | ECE 30 INTUHCEH o NISHI KUMARI | 2101140434 Output: Enter file nate with txt extension: [Fg] he List of length of words read fron file [35 2 4) 4, 2 3 5 2s 3] Result: Hence, a histogram of words according to their length from text read from a file is plotted, B.Tech 1" Year | ECE 31 INTUHCEH © scanned ith oxen scar

You might also like