Amplitude Shift Keying(ASK)

Amplitude Shift Keying (ASK) (or) On Off Keying (OOK) is the simplest Digital Modulation technique.

In this method, carrier amplitude is switched between two voltages ON and OFF levels depending up on the input binary sequence.

The carrier signal is a continuous wave (or) sinusoidal wave form

S(t)=A \cos 2\pi f_{c}t .

The normalized power is P=\frac{A^{2}}{2}

A=\sqrt{2P_{s}} .

The carrier signal can be expresses in terms of power as S(t)=\sqrt{2P_{s}} \cos 2\pi f_{c}t.

if energy per bit is E_{b} and the bit interval as T_{b} then the carrier signal is S(t)=\sqrt{\frac{2E_{b}}{T_{b}}} \cos 2\pi f_{c}t.

Now according to ASK Binary ‘1’ is represented with carrier voltage and Binary ‘0’ is represented with zero voltage.

\left\{\begin{matrix} S_{ASK}(t)=\sqrt{2P_{s}} \cos 2\pi f_{c}t\rightarrow \ Binary\ '1' \\ =0 \ \rightarrow \ Binary\ '0' \end{matrix}\right.

in terms of Energy and bit duration ASK signal can be written as

\left\{\begin{matrix} S_{ASK}(t)=\sqrt{\frac{2E_{b}}{T_{b}}} \cos 2\pi f_{c}t\rightarrow \ Binary\ '1' \\ =0 \ \rightarrow \ Binary\ '0' \end{matrix}\right..

ASK Transmitter:-

The figure shows the ASK generator (or) ASK Transmitter

It is a simple product Modulator, which modulates the incoming binary sequence (in the form of a signal) with the carrier signal S(t)

i.e, S_{ASK}(t)=b(t).S(t)

b(t) represents the binary sequence in the form of a signal.

when the  input bit (or) symbol is Binary ‘1’ product Modulator passes the carrier signal and for Binary’0′, A zero output is given which blocks the carrier signal.

\left\{\begin{matrix} S_{ASK}(t)=\sqrt{2P_{s}} \cos 2\pi f_{c}t\rightarrow \ Binary\ '1' \\ =0 \ \rightarrow \ Binary\ '0' \end{matrix}\right..

Coherent ASK Detector:-

The figure shows the Block Diagram of coherent ASK/BASK Detector. The ASK signal S_{ASK}(t) is applied to the correlator ( The Block product Modulator followed up by the Integrator).

S_{ASK}(t) is multiplied by local carrier C(t) this carrier C(t) is phase locked with that of the carrier used in the Transmitter. As this is coherent reception.

The product S_{ASK}(t).C(t) is applied to the Integrator. The Integrator integrates the input over one bit interval T_{b} and the output is given to a threshold device. If the threshold voltage is set to 0 V.

the output of threshold device v(t) (or) v is either ‘1’ (or) ‘0’ based on the following condition.

v\leq 0\rightarrow \ a \ symbol \ '1' \ is \ detected.

'0' \ is \ detected otherwise.

Note:- The input to demodulator is not S_{ASK}(t) always most of the times it is interfered with noise n(t) in the channel.

in coherent detection input to the demodulator is simply S_{ASK}(t) signal where as in Non-coherent detection the input is noisy ASK signal.

Note: There is a rating embedded within this post, please visit this post to rate it.

1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading...

Sequential custom single purpose processor design

Sequential custom single purpose processor design

  • Combinational and sequential  logic  design   techniques   are   used   to   build   datapath   components and controllers.
  • A sequential program   to   implement   computation  of  a  greatest  common  divisor   (GCD) is as follows.
  • Figure 4.3(a) shows a black-box diagram of the desired system.
  • Data inputs are: x_i and y_i
  • data output d_o.

  • The system’s functionality is straightforward: the output should represent the GCD of the inputs.
  • If the inputs are 12 and 8, the GCD is 4.
  • If the inputs are 13 and 5, the GCD is 1.
  • Figure 4.3(b) provides a simple program with this functionality GCD.
  • TO build a   single-purpose   processor   implementing the GCD program.
  • To begin building our single-purpose processor implementing the GCD program.
  • First convert our program into a complex state diagram, in which states and arcs may include arithmetic expressions.
  • These expressions use  external  inputs  and   outputs or variables.
  • In contrast, state  diagrams  includes  boolean   expressions, use external inputs and outputs,   not variables.
  • Complex state diagram looks like a sequential program in  which  statements  are  scheduled   into states.
  • Templates are to convert a program to a state diagram, as shown in Figure 4.2.
  • Each statement can be  classified  into assignment  statement, loop  statement,  or branch (if-then-else or case) statement.

For assignment statement

  • A state is created  with  the  statement  as  its   action. an arc is added from this state for the   next state.

For a loop statement

  • For a loop statement, a condition state C and a join state J are created both with no actions.
  • Add an arc with the loop’s condition from state C to the first statement in the loop body.
  • Add a second  arc  from  !cond  to  the  next statement from the loop.
  • Also add an arc from J to C.

For a branch statement

  • For a branch statement, create a condition state C and a join state J, both with no actions.
  • Create an arc  from  the  first  branch’s   condition(C1)  from  C  to  the  branch’s  first   statement(C1 stmts).
  • Create another arc with the condition!(C1*C2) from C to C2 stmts.
  • Repeat this for other branches.
  • Finally, connect the  arcs  from  C1  stmts,  C2 stmts and others to J.
  • Add an arc from J to next statement.
  • Using this template  approach,  convert  GCD   program  to  the  complex  state  diagram  of   Figure 4.3(c).
  • Now let us  see  the  designing  of  a  custom   single-purpose  processor  that  executes  the   GCD program.
  • The next step is to divide the functionality into a datapath part and a controller part, as shown in Figure 4.4.
  • The datapath interconnection of part should consist  of  an and combinational sequential components.
  • The controller part should consist of a basic state diagram, i.e., one containing only boolean actions and conditions.

  • Construct the datapath  through  a  four-step   process:
  • 1. Create registers for declared variables. The variables are x and y. Create registers x and y and  connect  these  registers  to  input  ports.   create register d and connect it to the output   port.
  • 2. Create a functional unit for each arithmetic operation in the state diagram. In the example, there are two subtractions, one comparison for   less  than,  one  comparison  for  inequality,   yielding two subtractors and two comparators.
  • 3.Connect the ports, registers and functional units. A  source  may  be  an  input  port,  a functional unit, or another register.
  • 4. Finally, create a unique identifier for each control input  and  output  of  the  datapath   components.
  • Now that we have a complete datapath, we can build a state diagram for our controller.
  • Figure 4.4 shows    the    controller   implementation model, and Figure 4.5 shows a   state table.
  • Note that there are 7 inputs to the controller, resulting in 128 rows for the table.

  • don’t cares are used to reduce the rows in the state table for some input combinations, still   optimization is possible by using (CAD) tools.

1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading...

RT-level sequential components

RT-level sequential components

  • For complex sequential  systems,abstract sequential components are used.
  • The components are:
  • Register
  • Shift register
  • Counter

Register

  • A register stores n bits from its n-bit data input I, with those stored bits appearing at its output Q.
  • A register has two control inputs clock and load.
  • For a rising edge triggered register the inputs I are only stored  when  load  is  1  and  clockis rising from 0 to 1.
  • The clock input is usually drawn as a small triangle, as shown in the figure.
  • Another common  register  control  input  is clear, which resets all bits to 0, regardless of the value of I.
  • Because all n bits of the register can be stored in parallel, we  often  refer  to  this  type  of register as a parallel-load register.

Shift Register

  • A shift register  stores  n  bits,  but  these  bits cannot be stored in parallel.
  • These bits are shifted into the register serially, meaning one bit per clock edge.
  • A shift register has a one-bit data input I, and at least two control inputs clock and shift.
  • When clock is rising and shift is 1,
  • The value of I is stored in the (n)’th bit.
  • The (n)’th bit is stored in the (n-1)’th bit.
  • The (n-1)’th bit is stored in the (n-2)’th bit.
  • and likewise, until the second bit is stored in the first bit.
  • The first bit is typically shifted out, meaning it appears over an output Q.

Counter

  • A counter is a register that can also increment (add binary 1) to its stored binary value.
  • A counter has  a  clear  input,  which  resets  all stored bits to 0.
  • It has a  count  input,  which  enables incrementing on the clock edge.
  • A counter often  also  has  a  parallel  load  data input and associated control signal.
  • A common counter feature is both up and down counting or incrementing  and  decrementing requiring an additional control input to indicate the count direction.
  • These control inputs can be either synchronous or asynchronous.
  • Asynchronous inputs are  independent  of  the clock.
  • synchronous inputs are dependent of the clock.

1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading...

Sequential logic design

Sequential logic design

  • A sequential circuit is a digital circuit whose outputs are a function of the current as well as previous input values.
  • Sequential logic possesses memory.
  • One of the most basic sequential circuits is the flip-flop.
  • A flip-flop stores a single bit.

D-Flip-Flop

  • The simplest type  of  flip-flop  is  the  D  flip- flop.
  • It has two inputs: D and clock.
  • When clock is 1, the value of D is stored in the flip-flop output Q.
  • When clock is 0, the value of D is ignored; the output Q maintains its value.

SR-Flip-Flop

  • An SR flip-flop has threee inputs S,R,clk
  • S stands for Set and R stands for Reset.
  • When clock is  0,  the  previously  stored  bit  is maintained and appears at output Q.
  • When clock is  1,  the  inputs  S  and  R  are examined.
  • If S is 1, 1 is stored in Q.
  • If R is 1 , 0 is stored in Q.
  • If both are 0s there is no change
  • If bothe are 1s behavior is undefined.

JK-Flip-Flop

  • An JK flip-flop has three inputs J,K,clk
  • JK flip-flop is same as  that  of  SR  flip-flop except that when J and K are 1, the stored bit toggles from 1 to 0 or 0 to 1.
  • When clock is  1,  the  inputs  J  nad  K  are examined .
  • If J is 1, 1 is stored in Q.
  • If K is 1 , 0 is stored in Q.

  • If both are 0s there is no change
  • If bothe are 1s output toggles.

1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading...

RT level Combinational Components

RT level Combinational Components

  • A large combinational circuit would be very complex to design.
  • For example, a circuit with 16 inputs would have 2^16, or 64K, rows in its truth table.
  • One way to reduce the complexity is to use combinational components instead of logic gates.
  • Such combinational components often called Register-Transfer (or) RT-level components.

Multiplexer

  • A multiplexor, sometimes called a selector, allows only one of its data inputs Im to pass through to the output O.
  • Allowing only one of multiple input tracks to connect to a single output track.
  • If there are m data inputs, then there are log2(m) select lines S, and an mX1 multiplexer has m data inputs, one data output.
  • For Example an 8X1 Mux has 8- input lines and 1-output line and 3 select lines.
  • The binary value of S determines which data input passes through;
  • 00…00 means I0 may pass,
  • 00…01 means I1 may pass,
  • 00…10 means I2 may pass, and so on.
  • For example, an 8×1 multiplexor has 8 data inputs and thus 3 select lines.
  • If s =110, then I6 will pass through to the output. So if I6 is 1, then the output would be 1; if I6 is 0, then the output would be 0.
  • Commonly n-bit multiplexer is used which is a more complex device.
  • Each data input and output, consists of n bits( lines).
  • For Example, a 4-bit 8×1 multiplexer. Thus, if I6 were 0110, then the output would be 0110.
  • n is independent of the number of select lines.

Decoder

  • A decoder is another combinational circuit.
  • A decoder converts its binary input I into a one-hot output O.
  • “One-hot” means that exactly one of the output lines can be 1 at a given time.
  • A decoder nX2^n has n-inputs and 2^n outputs.
  • A decoder can also be specified log2(n) x n where log2(n) number of inputs and n represents number of outputs.
  • For example, a 3×8 decoder has 3 inputs and 8 outputs.
  • If the input is 000, then the output O0 would be 1.
  • If the input is 001, then the output O1 would be 1, and so on.
  • An extra input is enable, when enable is 0 all outputs are O. When enable is 1, the decoder functions as before.

Adder

  • An adder adds two n-bit binary inputs A and B, generating an n-bit output sum along with an output carry.
  • For example, a 4-bit adder would have a 4-bit A input, a 4-bit B input, a 4-bit sum output, and a 1-bit carry output.
  • If A is 1010 and B is 1001, then sum would be 0011 and carry would be 1.
  • An adder often comes with a carry input also, such adders can be cascaded to create larger adders.

Comparator

  • A comparator compares two n-bit binary inputs A and B, generating outputs.
  • Output indicating whether A is less than, equal to, or greater than B.
  • If A were 1010 and B were 1001, then less would be 0, equal would be 0, and greater would be 1.

ALU

  • An ALU (arithmetic-logic unit) can perform a variety of arithmetic and logic functions on its n-bit inputs A and B.
  • The select lines S choose the current function.
  • If there are m possible functions, then there must be at least log2(m) select lines.
  • Common functions include addition, subtraction, AND, and OR.

Shifter

  • Another common RT-level component is a shifter.
  • An n-bit input I can be shifted left or right and then output to an output O.
  • For example, a 4-bit shifter with an input 1010 would output 0101 when shifting right one position.
  • Shifters come with an additional input indicating what value should be shifted in and an additional output indicating the value of the bit being shifted out.

1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading...

Basic Combinational Logic Design

Basic Combinational Logic Design

  • A combinational circuit is a digital circuit whose output is purely a function of its current inputs.
  • It has no memory(past inputs).
  • A simple technique is used to design a combinational circuit using basic logic gates.
  • Step1:- Problem description(output in terms of inputs).
  • Step2:- Translation of description into truth table with all possible input configurations.
  • Step3:- Derivation of output equations from output columns.
  • Step4:- Minimization of output equations by using k-maps to minimize the number of logic gates.
  • Step5:- Obtaining the final circuit from the output equations.

1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading...

Combinational logic design


Combinational logic design

  • A transistor is the basic electrical component of digital systems.
  • Combinations of transistors forms logic gates.
  • Logic gates are the basic building block of digital systems.
  • A transistor acts as a simple on/off switch.
  • One type of transistor is CMOS transistor.
  • n-MOS transistor is shown in Fig 4.1(a).
  • The gate controls whether or not current flows from the source to the drain.
  • When a high voltage (typically +5 Volts, which we’ll refer to as logic 1) is applied to the gate, the transistor conducts, so current flows.
  • When low voltage (or) logic 0 is applied to the gate, the transistor does not conduct.

  • Fig 4.1(c) shows an Inverter.
  • When the input x is logic 0, the top transistor conducts (and the bottom does not), so logic 1 appears at the output F.
  • When the input x is logic 0, then output becomes 1.

  • Fig 4.1(d) shows NAND gate.
  • x, y are inputs to NAND gate and F is the output.
  • When at least one of the inputs x and y is logic 0, then at least one of the top transistors conducts (and the bottom transistors do not), so logic 1 appears at F.
  • If both inputs are logic 1, then neither of the top transistors conducts, both of the bottom transistors conducts so logic 0 appears at F.

  • Fig 4.1(e) shows NOR gate.
  • When two inputs are at logic 0, then output F is 1.
  • When two inputs are at logic 1, then output F is 0.

1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 5.00 out of 5)
Loading...

Custom Single Purpose Processors


Custom Single Purpose Processors

Introduction:-

  • A single-purpose processor is a digital system intended to solve a specific computation task.
  • A manufacturer builds a standard single-purpose processor for use in a variety of applications.
  • A custom single purpose processor to execute a specific task within our embedded system.
  • Benefits of a custom single purpose processor are:
  • performance is fast, due to fewer clock cycles.
  • It consists of simpler functional units, less multiplexers, or simpler control logic.
  • size is small, due to a simpler datapath.
  • No program memory.
  • Less NRE cost.
  • Reduced performance and size.
1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading...

User-defined Exceptions

User-defined  Exceptions

  • Like the built-in exceptions of Python, the programmer can also create his own exceptions which are called ‘Use-defined exceptions’ or ‘Custom exceptions’ .
  • Python offers many exceptions which will raise in different contexts.
  • For example, when a number is divided by zero, the ZeroDivisionError is raised. Similarly, when the datatype is not correct, TypeError is raised.
  • There may be some situations where none of the exceptions in python are useful for the programmer.
  • In that case, the programmer has to create his own exception and raise it.

   Steps to follow to create a userdefined exceptions:

  • Step1:- Since all exceptions are classes, the programmer is supposed to create his own exception as a class, also, he should make his class as a sub class to the in-built ‘Exception’ class

   class MyException(Exception)

         def__init__(self, arg):

             self.msg = arg

  • Here, ‘MyException’ class is the sub class for ‘Exception’ class. This class has a constructor where a variable ‘msg’ is defined. This ‘msg’ receives a message passed from outside through ‘arg’
  • Step2:- The programmer can write his code, may be it represents a group of statements or a function. When the programmer suspects the possibility of exception, he should raise his own exception using ‘raise’ statement as:

    raise MyException(‘message’)

    Here, raise statement is raising MyException class object that contains the given ‘message’

  • The programmer can insert the code inside a ‘try’ block and catch the exception using ‘except’ block as:

    try:

          code

    except Myexception as message:

          print(message)

Python program on user-defined eception

1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading...

Multiple Except Blocks

Multiple Except Blocks

  • Python allows Multiple except blocks with a single try block. The block which matches with the exception generated will get executed.
  • A try block can be associated with more than one except block to specify handlers for different exceptions.
  • However, only one handler will be executed. Exception handlers only handle exceptions that occur in the corresponding try block.
  • The syntax of Multiple except blocks

Python program on Multiple except blocks

1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading...

Exception Handling

Exception Handling

  • The purpose of handling errors is to make the program robust. A robust program does not terminate in the middle.
  • When there is an error in the program, it will display an appropriate message to the user and continue execution.
  • Designing such programs is needed in any software development. For this purpose, the programmer should handle errors. When the errors can be handled, they are called exceptions.
  • Step1:- The programmer should observe the statements in the program where there may be a possibility of exceptions. Such statements should be written inside a ‘try’ block. A try block looks like as follows

    try:

        statements

  • If some exception arises inside try block, the program will not be terminated. When PVM understands that there is an exception, it jumps into an ‘except’ block.
  • Step2:- The programmer should write the ‘except’ block where the programmer should display the exception details to the user. This helps the user to understand that there is some error in the program
  • The programmer should also display a message regarding what can be done to avoid this error. Except block looks like as follows:

   except Exceptionname:

          statements

  • The statements written inside an except block are called ‘handlers’ since they handle the situation when the exception occurs.
  • Step3:- Lastly, the programmer should perform clean up actions like closing the files and terminating any other processes which are running.
  • The programmer should write this code in the finally block. Finally block looks like as follows:

    finally:

       statements

  • The finally block is that the statements inside the finally block are executed irrespective of whether there is an exception or not.
  • This ensures that all the opened files are properly closed and all the running processes are properly terminated. So, the data in the files will not be corrupted and the user is at the safe-side.
  • Performing the above 3 tasks is called ‘exception handling’.

  • In exception handling, the programmer is not preventing the exception, as in many cases it is not possible. But the programmer is avoiding any damage that may happen to data and software.
1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading...

Exceptions

Exceptions

  • Even if a statement is syntactically correct, it may still cause an error when executed. Such errors that occur at run-time( or during execution) are known as exceptions.
  • An exception is an event, which occurs during the execution and disrupts the normal flow of the program’s instructions.
  • When a program encounters a situation which it can not deal with, it raises an exception. Therefore, an exception is a Python object that represents an error.
  • When a program raises an exception, it must handle the exception or the program will be immediately terminated.
  • It is possible to handle exceptions in programs to end it gracefully, otherwise, if exceptions are not handled by programs, then error messages are generated.
  • Let us see some examples in which exceptions occurs.

  • From the output it is clear that the ‘finally’ block is executed and the file closed in both cases.
  • e. when there is no exception and when the exception occurred.
  • The complete exception handling syntax will be in the following format.

       

  • The ‘try’ block contains the statements where there may be one or more exceptions. The subsequent ‘except’ blocks handle these exceptions.
  • When exception1 occurs, ‘handler1’ statements are executed. When ‘exception2’ occurs, ‘handler2’ statements are executed and so forth.
  • If no exception is raised, the statements inside the ‘else’ block are executed.
  • Even if the exception occurs or does not occur, the code inside ‘finally’ block is always executed.

The points to remember:

  • A single try block can be followed by several except block.
  • Multiple except blocks can be used to handle multiple exceptions.
  • It is not possible to write except blocks without a try block.
  • It is possible to write a try block without any except block.
  • Else block and finally blocks are not compulsory.
  • When there is no exception, else block is executed after try block.
  • Finally block is always executed.

1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading...

Syntax Errors Vs Logical Errors

Syntax Errors

  • Syntax errors occurs when violation of the rules of Python and they are the most common kind of errors that occur while learning a new language.
  • For example, consider the lines of code

    i = 0

    if i == 0 print(i)

    Syntax Error: invalid syntax

  • In the aforementioned code, here : was missed before the keyword print. If you run this code in a file, then the file name and line number would have also been printed to know the error has occurred.
  • Basically, in this case, the Python interpreter has found that it can not complete the processing of the instruction because it does not conform to the rules of the language.

Logical Errors

  • The other type of errors, known as logical errors, specifies all those type of errors in which the program executes but gives incorrect results.
  • Logical error may occur due to wrong algorithm or logic to solve a particular program. In some, cases, logical errors may lead to divide by zero or accessing an item in a list where the index of the item is outside the bounds of the list. In this case, the logic error leads to a run-time error that causes the program to terminate abruptly.
1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading...

Introduction to Errors and Exception Handling

Introduction to Errors and Exception Handling

  • In programs, there are two kinds of errors: syntax errors and exceptions.
  • The programs may behave abnormally or unexpectedly because of some errors and/or exceptions.
  • The two common type of errors that are very often encounter are syntax errors and logical errors.
  • While logical errors occur due to poor understanding of problem and its solution, syntax errors on the other hand, arises due to poor understanding of the language. However , such errors can be detected by exhaustive debugging and testing of procedures.
  • But many a times, some peculiar problems arises which are often categorized as exceptions.
  • Exceptions are run-time anomalies or unusual conditions(such as divide by zero, accessing arrays out of its bounds, running out of memory or disk space, overflow, and underflow) that a program may encounter during execution.
  • Like errors, exceptions can also be categorized as synchronous or asynchronous exceptions.
  • Synchronous exceptions(like divide by zero, array index out of bound, etc) can be controlled by the program.
  • Asynchronous exceptions(like an interrupt from the keyboard, hardware malfunction, or disk failure) are caused by events that are beyond the control of the program.
1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading...

append( ) Method

append( ) Method

  • Once some data is stored in a file, it is possible to write data or append data to it. To append a file, the file opening mode is ‘a’ or ‘ab’ depending on whether it is a text file or a binary file.
  • Note that if a file is opened in ‘w’ or ‘wb’ mode and then start writing data into it, then its existing contents would be overwritten.

The contents of file myfile1.txt

Python program on append(  ) operation on files

myfile1.txt  contents after performing append(  )  operation

1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading...

The read( ) and readline( ) Methods

The read( ) and readline( ) Methods

  • The read( ) method is used to read a string from already opened file. The string can include alphabets, numbers, characters, or other symbols.
  • The syntax of read( ) method is given as:

    fileobj.read([count])

  • In the above syntax, count is an optional parameter which if passed to the read( ) method specifies the number of bytes to be read from the opened file.

The contents of myfile1.txt are

Python program on Read operation on files

Readline(  ) operation on files

The contets of myfile1.txt before performing readline(  ) operation

Python program on readline(  ) operation on files

1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading...

Reading and writing files

Reading and writing files

  • The read( ) and write( ) are used to read data from file and write data to files respectively.
  • write( ) and writelines( ) Methods
  • The write( ) method is used to write a string to an already opened file. This string may include numbers, special characters, or other symbols.
  • While writing data to a file, the write( ) method does not add a newline character(‘\n’) to the end of the string.

Reading operation on files

Open notepad and write Hello world! and save it as myfile1.txt and copy the file into the python main folder

 The contents of myfile1.txt are

Now write a Python program on reading operation on files

Writing operation on files

The contents of myfile1.txt before writing data to it is

Python program to perform writing operation on files

The contents of file myfile1.txt after performing writing operation

1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading...

String Manipulation functions

String Manipulation functions

  • string functions present in the string.h header file are:
  • strlen( ):- this function calculates the length of the string str up to but not including the null character, i.e., the function returns the number of characters in the string.
  • Syntax :

    size_t   strlen(const   char  *str);

  • This is the function prototype.
  • size_t: The return type is size_t, which is an unsigned integer type representing the size of an object in memory.
  • const char *str: The function takes a single argument, which is a pointer to a constant character array (a string). The const keyword ensures that the function does not modify the string.

  • strcpy( ):- this function copies the string pointed to by str2 to str1 including the null character of str2.
  • It returns the argument str1.Here str1 size should be big enough to store the contents of str2.
  • Syntax :

    char strcpy(char  *str1, const char *str2);

  • strcat( ):- this function appends the string pointed by str2 to the end of the string pointed to by str1.
  • Syntax :

    char strcat(char  *str1, const char *str2);

1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 5.00 out of 5)
Loading...

Reading Strings

Reading Strings

  • The declaration of a string is char str[100];
  • str can be read from the user by using three ways:
  • using scanf function
  • using gets( ) function
  • using getchar( ), getch( ), or getche( ) function repeatedly.
  • The string can be read using scanf( ) by writing

    scanf(“%s”, str);

  • Unlike integer, float, and characters, %s format does not require the ampersand before the variable str.
  • gets( ):- gets( ) function is used to read a string

   gets(str);

  • gets( ) is a simple function that overcomes the drawbacks of the scanf( ). The gets( ) takes the starting address of the string which will hold the input.
  • The string inputted using gets( ) is automatically terminated with a null character.

1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 5.00 out of 5)
Loading...

Strings

Strings

  • Now adays, computers are widely used for word processing applications such as creating, inserting, updating, and modifying textual data.
  • It is possible to search for a particular pattern within a text, delete it, or replace it with another pattern.
  • String:- In C language, a string is nothing but a null-terminated character array. This means that after the last character, a null character(‘\0’) is stored to signify the end of the character array.
  • Example:-
  •         char  str[ ] =“Hello”;
  • Here, to store a string of length 5, we need 5+1 locations(1 extra for the null character ‘\0’).
  • Character constants are enclosed in single quotes. String constants are enclosed in double quotes

    • The figure shows the memory representation of a string or character array.
    • A string is sequence of characters, 1000,1001,1002 are the memory addresses of individual characters.
    • From the figure, H is stored at memory location 1000
    • The ASCII codes of characters are stored in memory and not the character itself. i.e., at address 1000, 72 will be stored the ASCII code for H is 72.
  • The general form of declaring a string is ,

    char  str[size];

  • Here the string stores size-1 number of characters.
  • The other way of initializing strings is to initialize it as an array of characters,

   char  str[ ] = {‘H’, ‘E’, ‘L’, ‘L’, ‘O’, ‘\0’};

  • The null character has explicitly added, the size of the string is not mentioned.
  • The compiler will automatically calculate the size based on the number of elements initialized.
  • So, in this example 6 memory slots will be reserved to store the string variable, str.
  • A string with size much larger than the number of elements that are initialized.
  • For example,

    char  str[10] = “HELLO”;

  • The following declaration is illegal in C

    char   str[3];

    str  =  “HELLO”;

  • In this case, the compiler creates a character array of size 10, stores the value “HELLO” in it and finally terminates the value with a null character. Rest of the elements in the array are automatically initialized to NULL.

1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 5.00 out of 5)
Loading...

Accessing the elements

Accessing the elements

  • The elements in a multi-dimensional array are stored in contiguous memory locations

    int   arr[i][j];

  • While accessing the elements, the last subscript (j) varies most rapidly and first subscript(i) varies least rapidly.
  • In one-dimensional array, a single for loop is used to vary the index i to scan the elements. Similarly, a two-dimensional array contains i, j, therefore two for loops are used to scan the elements.
  • First for loop is for rows(i)
  • Second for loop is for columns(j)

1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 5.00 out of 5)
Loading...

Closing a File

Closing a File

  • A file which is opened should be closed using the close( ) method. Once a file is opened but not closed, then the data of the file may be corrupted or deleted in some cases.
  • If the file is not closed, the memory utilized by the file is not freed, leading to problems like insufficient memory.
  • This happens when we are working with several files simultaneously. Hence it is mandatory to close the file.
  •     f.close( )
  • Here, the file represented by the file object ‘f’ is closed. It means ‘f’ is deleted from the memory.
  • Once the file object is lost, the file data will become inaccessible.
  • If any work is done with the file again, once again the file will be opened using the open( ) function.

1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading...

Opening a File

Opening a File

  • We should use open( ) function to open a file. This function accepts ‘filename’ and ‘open mode’ in which to open the file.

   file handler = open(“file name”, “open mode” , “buffering”)

  • Here, the ‘file name’ represents a name on which the data is stored. We can use any name to reflect the actual data.
  • A buffer represents a temporary block of memory. ‘buffering’ is an optional integer used to set the size of the buffer for the file.
  • If the binary mode, we can pass 0 as buffering integer to inform not to use any buffering.
  • In text mode, we can use 1 for buffering to retrieve data from the file one line at a time.

1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading...

Types of Files in Python

Types of Files in Python

  • In Python, there are two types of files. They are:
  • Text files
  • Binary files

Text files

  • Text files store the data in the form of characters. Normally, text files are used to store characters or strings.

Binary Files

  • Binary files store entire data in the form of bytes, i.e, a group of 8 bits each. When the data is retrieved from the binary file, the programmer can retrieve the data as bytes.
  • Binary files can be used to store text, images, audio and video.
  • A binary file is a file which may contain any type of data, encoded in binary form for computer storage and processing purpose.
  • It includes files such as word processing documents,PDFs,images,spreadsheets,videos,zip files, and other executable programs.
  • Like a text file, a binary file is a collection of bytes. A binary file is also referred to as a character stream.
  • While text files can be processed sequentially, binary files, on the other hand, can be either processed sequentially or randomly depending on the needs of the application.
  • In python, to process a file randomly, the programmer must move the current file position to an appropriate place in the file before reading or writing data.
  • For example, if a file is used to store records of students, then to update a particular record, the programmer must first locate the appropriate record, read the record into memory, update it, and finally write the record back to disk at its appropriate location in the file.
  • In a text file, an integer value 123 will be stored as a sequence of three characters – 1,2 and 3. As each character takes 1 byte, therefore, to store the integer value 123, we need 3 bytes.
  • However, in a binary file, the integer value 123 will be stored in 2 bytes in the binary form. This clearly indicates that binary files takes less space to store the same piece of data and eliminates conversion between internal and external representations and are thus more efficient than the text files.
  • Thus, we see that text files contain only basic characters and do not store any information about the color, font, and size of the text.
  • Examples of text files include .txt or .py extension. These files can be opened with Windows Notepad.
  • These files can be easily read and the contents of the file are treated as an ordinary string value.
  • Binary files, on the other hand, can not be read by text editors like Notepad. If you open a binary file in Notepad, you will see some scrambles, and absurd data.

1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading...

Introduction

Introduction

  • Data is very important. Every organization depends on its data for continuing its business operations.
  • If the data is lost, the organization has to be closed. This is the reason computers are primarily created for handling data, especially for storing and retrieving data.
  • In later days, programs are developed to process the data that is stored in the computer.
  • To store data in a computer, we need files.
  • For example, we can store employee data like employee number, name and salary in a file in the computer and later use it whenever we want.
  • A file is nothing but collection of data that is available to a program.
  • Once we store data in a computer file, we can retrieve it and use it depending on our requirements.
  •    There are four important advantages of storing data in a file:
  • When the data is stored in a file, it is stored permanently. This means that even though the computer is switched off, the data is not removed from the memory since the file is stored on hard disk or CD. This file data can be utilized later, whenever required.
  • It is possible to update the file data. For example, we can add new data to the existing file, delete unnecessary data from the file and modify the available data of the file makes the file more useful.
  • Once the data is stored in a file, the same data can be shared by various programs.
  • Files are highly useful to store huge amount of data.
1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading...

program that creates two dictionaries. One that stores conversion values from meters to centimeters and the other that stores values from centimeters to meters

  • Write a program that creates two dictionaries. One that stores conversion values from meters to centimeters and the other that stores values from centimeters to meters.

1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading...

Converting strings into dictionary

Converting strings into dictionary

  • If a string is given with key and value pairs separated by some delimiter or separator like a comma, it is possible to convert the string into dictionary.
  • To convert such a string into a dictionary, 3 steps are to be followed.
  • First, split the string into pieces using split method and then brake the string at equals( = ) symbol. This can be done using a for loop.

    for x in str.split(‘,’)

        y = x.split(‘=’)

1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading...

Converting lists into dictionary

Converting lists into dictionary

If there are two lists, it is possible to convert them into a dictionary. For example, the two lists are countries and cities

countries=[“USA”, “India”, “Germany”, “France”]

cities = [‘Washington’, ‘Newdelhi’, ‘Berlin’, ‘Paris’]

dict1 = {“USA”:‘Washington’,“India”:‘Newdelhi’, “Germany”:‘Berlin’, “France”: ‘Paris’}

  • If a string is given with key and value pairs separated by some delimiter or separator like a comma, it is possible to convert the string into dictionar.
  • To convert such a string into a dictionary, 3 steps are to be followed.
  • First, split the string into pieces using split method and then brake the string at equals( = ) symbol. This can be done using a for loop.
1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading...

Difference between a List and a Dictionary

Difference between a List and a Dictionary

  • There are two main differences between a list and a dictionary.
  • First, a list is an ordered set of items, But, a dictionary is a data structure that is used for matching one item(key) with another value.
  • Second, in lists, it is possible to access a particular item. But, these indexes should be a number. In dictionaries, any type of value can be used as an index. For example, dict[‘Name’], Name acts as an index but it is not a number but a string.
  • Third, lists are used to look up a value whereas a dictionary is used to take one value and look up another value. For this reason, dictionary is also known as a lookup table.
  • Fourth, the key-value pair may not be developed in the order in which it was specified while defining the dictionary. This is because python uses complex algorithms to provide fast access to the items stored in the dictionary. This also makes dictionary preferable to use over a list of tuples.
1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading...

Declaration of Two-dimensional arrays

Declaration of Two-dimensional arrays

Similar to one dimensional arrays, two dimensional arrays must be declared before being used.

The declaration statement tells the compiler the name of the array, the data type of each element in the array, and the size of each element. data_type  array_name[row_size][column_size];

Therefore, a two-dimensional mxn array is an array that contains mxn data elements and each element is accessed using two subscripts, i and j where i<=m and j<=n. For example, to store marks obtained by 3 students in 3 different subjects, then a two-dimensional array as

int   marks[3][3];

A two-dimensional array is called marks is declared that has 3 rows and 3 columns. The first element of the array is marks[0][0], the second element a marks[0][1] and so on. marks[0][0] stores the marks obtained by the first student in the first subject, marks[1][0] stores marks obtained by the second student in the first subject and so on.

The figure, shows a rectangular picture of a two-dimensional array, these elements will be actually stored sequentially in memory. Since computer memory is basically one-dimensional, a multi dimensional array can not be stored in memory as a grid.

There are two ways of storing a two-dimensional array in memory

  • row major order.
  • column major order.

row major order- the elements of the first row are stored before the elements of the second and third row. The elements off the array are stored row by row where n elements of the first row will occupy the first nth locations.

Column major order:- The elements of the array are stored column by column where n elements of the first column will occupy the first nth locations.

In one-dimensional arrays, we have seen that computer does not keep track of the address of the first element and calculates the addresses of the other elements from the base address. Same is the case with a two-dimensional array.

If the elements are stored in column major order

address A[i][j] = Base address + w{m(j-1) +  (i-1)}

If the elements are stored in row major order

address A[i][j] = Base address + w{n (i-1) +   (j-1)}

  • w – is the number of words stored per memory location
  • n – is the number of columns
  • m – is the number of rows
  • i, j – subscripts of the array element

A two-dimensional array is initialized in the same way as a one-dimensional array.

1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 5.00 out of 5)
Loading...

Two-Dimensional arrays

Two-Dimensional arrays

Till now we have read only about one-dimensional arrays. A one-dimensional array is organized linearly and only in one direction. But at times, it is required to store data in the form of matrices or tables. Here the concept of one-dimensional array is extended to incorporate two-dimensional data structures.

A two-dimensional array is specified using two subscripts where one subscript denotes row and the other denotes column. C considers the two-dimensional array as an array of a one-dimensional array.

1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 5.00 out of 5)
Loading...

Linear search

Searching

Searching means to find whether a particular value is present in the array or not. If the value is present in the array then searching is said to be successful and the searching process gives the location of that value in the array. Otherwise, if the value is not present in the array, the searching process displays the appropriate message and in this case searching is said to be unsuccessful.

There are two popular methods for searching the array elements

  1. Linear search
  2. Binary search

If the elements of the array are arranged in ascending order, then binary search should be used as it is more efficient for sorted list in terms of complexity.

Linear search

Linear search, also called sequential search is a very simple method used for searching an array for a particular value.

It works by comparing every element of the array one by one in sequence until a match is found.

Linear search is mostly used to search an unordered list of elements.

For example, if an array is declared and initialized as,

 int   arr[  ] ={10,20,30,40,50};

To find out whether the value 20 is present in the array or not. If yes, then the search is successful and it returns the position(index) of occurrence of val.

Here the pos = 1(index of 20)

Procedure  of Linear search of an array of elements

Step1:- Memory representation of arr[  ]

Step2:- Let us find out the location of the element 20, assume num = 20

Step3:- Compare num with arr[0], if arr[0]!=num, element is not found

Step4:- Compare num with arr[  ]

Step5:- element is found at location index 1

1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 5.00 out of 5)
Loading...

 

 

 

 

 

 

 

 

 

 

Merging

Merging

Merging two arrays in a third array means first copying the contents of the first array into the third array and then copying the contents of the second array into third array. Hence, the merged array contains contents of the first array followed by the contents of the second array.

If the arrays are unsorted then merging the arrays is very simple as one just needs to copy the contents of one array into another. But merging is not a trivial task when the two arrays are sorted and the merged array also needs to be sorted.

Let us first discuss the merge operation on unsorted arrays

1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 5.00 out of 5)
Loading...

error: Content is protected !!