This document provides an overview of the CS110 Computational Engineering course at IIT M. The course is an introduction to problem solving using computers. It will cover programming in C, numerical methods exercises, problem solving, and simulators. Students will be evaluated based on quizzes, programming assignments, and an exam. The course will include both theory lectures and hands-on lab sessions for programming.
1. Autoencoders are unsupervised neural networks that are useful for dimensionality reduction and clustering. They learn an efficient coding of the input in an unsupervised manner.
2. Deep autoencoders, also known as stacked autoencoders, are autoencoders with multiple hidden layers that can learn hierarchical representations of the data. They are trained layer-by-layer to learn increasingly higher level features.
3. Variational autoencoders are a type of autoencoder that are probabilistic models, with the encoder output being the parameters of an assumed distribution such as Gaussian. They can generate new samples from the learned distribution.
The document discusses algorithms for solving the range minimum query (RMQ) problem. It first reduces RMQ to the lowest common ancestor (LCA) problem in trees. It then presents several algorithms for solving RMQ, including:
1. A trivial preprocessing algorithm that requires O(n^2) time and O(1) query time
2. The sparse table (ST) algorithm that requires O(n log n) preprocessing time and O(1) query time
3. An improved algorithm that partitions the array into blocks and requires O(n) preprocessing time and O(1) query time for queries spanning multiple blocks
4. A general O(n) time solution that builds a Cartesian tree from
The document describes the sequence-to-sequence (seq2seq) model with an encoder-decoder architecture. It explains that the seq2seq model uses two recurrent neural networks - an encoder RNN that processes the input sequence into a fixed-length context vector, and a decoder RNN that generates the output sequence from the context vector. It provides details on how the encoder, decoder, and training process work in the seq2seq model.
Gradient
Based Learning Applied to Document Recognition
Y
. LeCun , L. Bottou , Y. Bengio and P. Haffner
Proceedings of the IEEE, 86(11
):2278 ----‐2324 , November 1998
This document discusses different number systems including decimal, binary, octal, and hexadecimal. It covers how to represent and convert between these systems. The key points covered are:
- Decimal uses base 10, binary uses base 2, octal uses base 8, and hexadecimal uses base 16
- Each system uses different symbols to represent quantities, from 0-9 for decimal and additional symbols for other systems
- Conversion between systems can be done by dividing or multiplying by the base and tracking remainders or places
- Fractions can be represented by breaking the number into a whole and fractional part in the target base
https://telecombcn-dl.github.io/2017-dlai/
Deep learning technologies are at the core of the current revolution in artificial intelligence for multimedia data analysis. The convergence of large-scale annotated datasets and affordable GPU hardware has allowed the training of neural networks for data analysis tasks which were previously addressed with hand-crafted features. Architectures such as convolutional neural networks, recurrent neural networks or Q-nets for reinforcement learning have shaped a brand new scenario in signal processing. This course will cover the basic principles of deep learning from both an algorithmic and computational perspectives.
https://telecombcn-dl.github.io/2017-dlai/
Deep learning technologies are at the core of the current revolution in artificial intelligence for multimedia data analysis. The convergence of large-scale annotated datasets and affordable GPU hardware has allowed the training of neural networks for data analysis tasks which were previously addressed with hand-crafted features. Architectures such as convolutional neural networks, recurrent neural networks or Q-nets for reinforcement learning have shaped a brand new scenario in signal processing. This course will cover the basic principles of deep learning from both an algorithmic and computational perspectives.
Recurrent Neural Networks (RNNs) continue to show outstanding performance in sequence modeling tasks. However, training RNNs on long sequences often face challenges like slow inference, vanishing gradients and difficulty in capturing long term dependencies. In backpropagation through time settings, these issues are tightly coupled with the large, sequential computational graph resulting from unfolding the RNN in time. We introduce the Skip RNN model which extends existing RNN models by learning to skip state updates and shortens the effective size of the computational graph. This model can also be encouraged to perform fewer state updates through a budget constraint. We evaluate the proposed model on various tasks and show how it can reduce the number of required RNN updates while preserving, and sometimes even improving, the performance of the baseline RNN models.
1. Autoencoders are unsupervised neural networks that are useful for dimensionality reduction and clustering. They learn an efficient coding of the input in an unsupervised manner.
2. Deep autoencoders, also known as stacked autoencoders, are autoencoders with multiple hidden layers that can learn hierarchical representations of the data. They are trained layer-by-layer to learn increasingly higher level features.
3. Variational autoencoders are a type of autoencoder that are probabilistic models, with the encoder output being the parameters of an assumed distribution such as Gaussian. They can generate new samples from the learned distribution.
The document discusses algorithms for solving the range minimum query (RMQ) problem. It first reduces RMQ to the lowest common ancestor (LCA) problem in trees. It then presents several algorithms for solving RMQ, including:
1. A trivial preprocessing algorithm that requires O(n^2) time and O(1) query time
2. The sparse table (ST) algorithm that requires O(n log n) preprocessing time and O(1) query time
3. An improved algorithm that partitions the array into blocks and requires O(n) preprocessing time and O(1) query time for queries spanning multiple blocks
4. A general O(n) time solution that builds a Cartesian tree from
The document describes the sequence-to-sequence (seq2seq) model with an encoder-decoder architecture. It explains that the seq2seq model uses two recurrent neural networks - an encoder RNN that processes the input sequence into a fixed-length context vector, and a decoder RNN that generates the output sequence from the context vector. It provides details on how the encoder, decoder, and training process work in the seq2seq model.
Gradient
Based Learning Applied to Document Recognition
Y
. LeCun , L. Bottou , Y. Bengio and P. Haffner
Proceedings of the IEEE, 86(11
):2278 ----‐2324 , November 1998
This document discusses different number systems including decimal, binary, octal, and hexadecimal. It covers how to represent and convert between these systems. The key points covered are:
- Decimal uses base 10, binary uses base 2, octal uses base 8, and hexadecimal uses base 16
- Each system uses different symbols to represent quantities, from 0-9 for decimal and additional symbols for other systems
- Conversion between systems can be done by dividing or multiplying by the base and tracking remainders or places
- Fractions can be represented by breaking the number into a whole and fractional part in the target base
https://telecombcn-dl.github.io/2017-dlai/
Deep learning technologies are at the core of the current revolution in artificial intelligence for multimedia data analysis. The convergence of large-scale annotated datasets and affordable GPU hardware has allowed the training of neural networks for data analysis tasks which were previously addressed with hand-crafted features. Architectures such as convolutional neural networks, recurrent neural networks or Q-nets for reinforcement learning have shaped a brand new scenario in signal processing. This course will cover the basic principles of deep learning from both an algorithmic and computational perspectives.
https://telecombcn-dl.github.io/2017-dlai/
Deep learning technologies are at the core of the current revolution in artificial intelligence for multimedia data analysis. The convergence of large-scale annotated datasets and affordable GPU hardware has allowed the training of neural networks for data analysis tasks which were previously addressed with hand-crafted features. Architectures such as convolutional neural networks, recurrent neural networks or Q-nets for reinforcement learning have shaped a brand new scenario in signal processing. This course will cover the basic principles of deep learning from both an algorithmic and computational perspectives.
Recurrent Neural Networks (RNNs) continue to show outstanding performance in sequence modeling tasks. However, training RNNs on long sequences often face challenges like slow inference, vanishing gradients and difficulty in capturing long term dependencies. In backpropagation through time settings, these issues are tightly coupled with the large, sequential computational graph resulting from unfolding the RNN in time. We introduce the Skip RNN model which extends existing RNN models by learning to skip state updates and shortens the effective size of the computational graph. This model can also be encouraged to perform fewer state updates through a budget constraint. We evaluate the proposed model on various tasks and show how it can reduce the number of required RNN updates while preserving, and sometimes even improving, the performance of the baseline RNN models.
https://telecombcn-dl.github.io/2017-dlai/
Deep learning technologies are at the core of the current revolution in artificial intelligence for multimedia data analysis. The convergence of large-scale annotated datasets and affordable GPU hardware has allowed the training of neural networks for data analysis tasks which were previously addressed with hand-crafted features. Architectures such as convolutional neural networks, recurrent neural networks or Q-nets for reinforcement learning have shaped a brand new scenario in signal processing. This course will cover the basic principles of deep learning from both an algorithmic and computational perspectives.
[Paper reading] L-SHAPLEY AND C-SHAPLEY: EFFICIENT MODEL INTERPRETATION FOR S...Daiki Tanaka
This document proposes two new algorithms, L-SHAPLEY and C-SHAPLEY, for interpreting black-box machine learning models in an instance-wise and model-agnostic manner. L-SHAPLEY and C-SHAPLEY are approximations of the SHAPLEY value that take graph structure between features into account to improve computational efficiency. The algorithms were evaluated on text and image classification tasks and were shown to outperform baselines like KERNELSHAP and LIME, providing more accurate feature importance scores according to both automatic metrics and human evaluation.
Introduction For seq2seq(sequence to sequence) and RNNHye-min Ahn
This is my slides for introducing sequence to sequence model and Recurrent Neural Network(RNN) to my laboratory colleagues.
Hyemin Ahn, @CPSLAB, Seoul National University (SNU)
https://telecombcn-dl.github.io/2017-dlai/
Deep learning technologies are at the core of the current revolution in artificial intelligence for multimedia data analysis. The convergence of large-scale annotated datasets and affordable GPU hardware has allowed the training of neural networks for data analysis tasks which were previously addressed with hand-crafted features. Architectures such as convolutional neural networks, recurrent neural networks or Q-nets for reinforcement learning have shaped a brand new scenario in signal processing. This course will cover the basic principles of deep learning from both an algorithmic and computational perspectives.
https://telecombcn-dl.github.io/2018-dlai/
Deep learning technologies are at the core of the current revolution in artificial intelligence for multimedia data analysis. The convergence of large-scale annotated datasets and affordable GPU hardware has allowed the training of neural networks for data analysis tasks which were previously addressed with hand-crafted features. Architectures such as convolutional neural networks, recurrent neural networks or Q-nets for reinforcement learning have shaped a brand new scenario in signal processing. This course will cover the basic principles of deep learning from both an algorithmic and computational perspectives.
This document summarizes a MatLab workshop covering various topics:
- MatLab Central, an official user community for asking and answering questions
- Cipher systems for encrypting text by shifting letters
- Least squares methods for fitting linear models to noisy data
- Dynamic code generation to display customized text
- Techniques for accelerating MatLab code such as vectorization and memory preallocation
The workshop emphasized best practices like utilizing help functions, saving intermediate work, and having fun with programming.
https://telecombcn-dl.github.io/2018-dlai/
Deep learning technologies are at the core of the current revolution in artificial intelligence for multimedia data analysis. The convergence of large-scale annotated datasets and affordable GPU hardware has allowed the training of neural networks for data analysis tasks which were previously addressed with hand-crafted features. Architectures such as convolutional neural networks, recurrent neural networks or Q-nets for reinforcement learning have shaped a brand new scenario in signal processing. This course will cover the basic principles of deep learning from both an algorithmic and computational perspectives.
The document discusses various time complexities of programming constructs like for loops, nested for loops, and inserting elements into data structures like lists and binary trees. It provides examples to explain concepts like big O notation, logarithmic time, and quadratic time complexity. Dynamic programming and backtracking algorithms are introduced as approaches to solve problems optimally with examples for the subset sum problem.
Animashree Anandkumar, Electrical Engineering and CS Dept, UC Irvine at MLcon...MLconf
Anima Anandkumar is a faculty at the EECS Dept. at U.C.Irvine since August 2010. Her research interests are in the area of large-scale machine learning and high-dimensional statistics. She received her B.Tech in Electrical Engineering from IIT Madras in 2004 and her PhD from Cornell University in 2009. She has been a visiting faculty at Microsoft Research New England in 2012 and a postdoctoral researcher at the Stochastic Systems Group at MIT between 2009-2010. She is the recipient of the Microsoft Faculty Fellowship, ARO Young Investigator Award, NSF CAREER Award, and IBM Fran Allen PhD fellowship.
the slides are aimed to give a brief introductory base to Neural Networks and its architectures. it covers logistic regression, shallow neural networks and deep neural networks. the slides were presented in Deep Learning IndabaX Sudan.
This document provides an overview of common number systems including decimal, binary, octal, and hexadecimal. It discusses how to convert between these different number systems by using place value and properties of their respective bases. Techniques for converting include dividing or multiplying by the base while tracking remainders. Examples are provided for converting between the different systems. Later sections cover additional topics like binary operations, fractions and conversions between decimal and binary fractions.
https://telecombcn-dl.github.io/2017-dlai/
Deep learning technologies are at the core of the current revolution in artificial intelligence for multimedia data analysis. The convergence of large-scale annotated datasets and affordable GPU hardware has allowed the training of neural networks for data analysis tasks which were previously addressed with hand-crafted features. Architectures such as convolutional neural networks, recurrent neural networks or Q-nets for reinforcement learning have shaped a brand new scenario in signal processing. This course will cover the basic principles of deep learning from both an algorithmic and computational perspectives.
The Munich LSTM-RNN Approach to the MediaEval 2014 “Emotion in Music” Taskmultimediaeval
In this paper we describe TUM's approach for the MediaEval's Emotion in Music" task. The goal of this task is to automatically estimate the emotions expressed by music (in terms of Arousal and Valence) in a time-continuous fashion. Our system consists of Long-Short Term Memory Recurrent Neural Networks (LSTM-RNN) for dynamic Arousal and Valence regression. We used two different sets of acoustic and psychoacoustic features that have been previously proven as effective for emotion prediction in music and speech. The best model yielded an average Pearson's correlation coeficient of 0.354 (Arousal) and 0.198 (Valence), and an average Root Mean Squared Error of 0.102 (Arousal) and 0.079 (Valence).
http://ceur-ws.org/Vol-1263/mediaeval2014_submission_7.pdf
SYSTEM IDENTIFICATION USING CEREBELLAR MODEL ARITHMETIC COMPUTERTarun Kumar
The field of identification is rather complex. This complexity is due to the variety of applications, goals, conditions, etc. Exact
specifications of final aim to be attained, analysis of available precision, etc. are some of the basic requirements to guide the work. In
this paper we used CMAC look up table for identification of both linear and non-linear systems. It deals with the basic CMAC
architectures, its capability and shows the motivations why CMAC net can be used for system identification. CMAC network has
hundreds of thousands of adjustable weights that can be trained to approximate non-linearities which are not explicitly written out or
even known. Its associative memory has a built in generalization. We have shown that due to its extremely fast mapping and training
operations, it is suitable for real time applications.
This document provides an overview of different number systems including decimal, binary, octal, and hexadecimal. It discusses how to convert between these number systems by using place value and properties of their respective bases. Techniques for converting include dividing or multiplying by the base while tracking remainders. Examples are provided for converting between the different number systems. Common powers and their prefixes for different bases are also defined. The document concludes with discussions of binary addition and multiplication.
This document describes a parallel algorithm for computing prefix sums and merging sorted arrays. It presents:
1) A parallel prefix algorithm that computes prefix sums in O(log n) time using O(n) processors by performing prefix computations in parallel across a binary tree representation.
2) A parallel merging algorithm that partitions input arrays into blocks of size O(log n), ranks block elements in parallel, and sequentially merges matching blocks, achieving O(log n) time and O(n) processors.
3) An analysis showing the parallel prefix algorithm runs in O(log n) time using O(n) processors, and two sorted arrays can be merged in O(log n) time using O(n
This document provides an introduction to a computer architecture and organization course. It discusses the history of computer architecture from Charles Babbage's Analytical Engine in the 1830s to modern computing devices. It also outlines the course structure, which will cover fundamental building blocks, data representation, fixed and floating point systems, and memory systems organization through lectures, problem sets, labs, and a final exam.
The document discusses the evolution of computers from ancient calculating devices like the abacus to modern computers. It covers early mechanical calculating devices developed between 3000 BC to the 18th century like the abacus, Napier's bones, Pascaline, and Leibnitz's calculator. It then discusses programmable mechanical computers like Jacquard's loom and pioneering electromechanical computers like Babbage's difference engine and analytical engine. The document concludes with a discussion of important milestones in modern computer development such as the Mark 1, Von Neumann architecture, ENIAC, EDVAC and the concept of generations of computers.
[Paper Reading] Attention is All You NeedDaiki Tanaka
The document summarizes the "Attention Is All You Need" paper, which introduced the Transformer model for natural language processing. The Transformer uses attention mechanisms rather than recurrent or convolutional layers, allowing for more parallelization. It achieved state-of-the-art results in machine translation tasks using techniques like multi-head attention, positional encoding, and beam search decoding. The paper demonstrated the Transformer's ability to draw global dependencies between input and output with constant computational complexity.
This document provides an overview of the CS101 Introduction to Computing course. It discusses the course contents and structure, which will cover fundamental computing concepts, web page development, and productivity software over 15 weeks. Students will complete assignments, a midterm exam, and a final exam. The first assignment requires students to email the instructor about their future plans and post a message on the course message board about customizing the class material. Upcoming lectures will discuss the history of computing from Babbage's Analytical Engine to modern computers.
This document provides an overview of a course on computer fundamentals. The course aims to give students an understanding of how computers work at the assembly level and introduce assembly language programming. Topics covered include the fetch-execute cycle, memory hierarchy, CPU components like the ALU and registers, number representation, and arithmetic and logical instructions. The course outline provides context on the history of computing and early computer designs to prepare students for future operating systems courses.
Hardware Acceleration for Machine LearningCastLabKAIST
This document provides an overview of a lecture on hardware acceleration for machine learning. The lecture will cover deep neural network models like convolutional neural networks and recurrent neural networks. It will also discuss various hardware accelerators developed for machine learning, including those designed for mobile/edge and cloud computing environments. The instructor's background and the agenda topics are also outlined.
https://telecombcn-dl.github.io/2017-dlai/
Deep learning technologies are at the core of the current revolution in artificial intelligence for multimedia data analysis. The convergence of large-scale annotated datasets and affordable GPU hardware has allowed the training of neural networks for data analysis tasks which were previously addressed with hand-crafted features. Architectures such as convolutional neural networks, recurrent neural networks or Q-nets for reinforcement learning have shaped a brand new scenario in signal processing. This course will cover the basic principles of deep learning from both an algorithmic and computational perspectives.
[Paper reading] L-SHAPLEY AND C-SHAPLEY: EFFICIENT MODEL INTERPRETATION FOR S...Daiki Tanaka
This document proposes two new algorithms, L-SHAPLEY and C-SHAPLEY, for interpreting black-box machine learning models in an instance-wise and model-agnostic manner. L-SHAPLEY and C-SHAPLEY are approximations of the SHAPLEY value that take graph structure between features into account to improve computational efficiency. The algorithms were evaluated on text and image classification tasks and were shown to outperform baselines like KERNELSHAP and LIME, providing more accurate feature importance scores according to both automatic metrics and human evaluation.
Introduction For seq2seq(sequence to sequence) and RNNHye-min Ahn
This is my slides for introducing sequence to sequence model and Recurrent Neural Network(RNN) to my laboratory colleagues.
Hyemin Ahn, @CPSLAB, Seoul National University (SNU)
https://telecombcn-dl.github.io/2017-dlai/
Deep learning technologies are at the core of the current revolution in artificial intelligence for multimedia data analysis. The convergence of large-scale annotated datasets and affordable GPU hardware has allowed the training of neural networks for data analysis tasks which were previously addressed with hand-crafted features. Architectures such as convolutional neural networks, recurrent neural networks or Q-nets for reinforcement learning have shaped a brand new scenario in signal processing. This course will cover the basic principles of deep learning from both an algorithmic and computational perspectives.
https://telecombcn-dl.github.io/2018-dlai/
Deep learning technologies are at the core of the current revolution in artificial intelligence for multimedia data analysis. The convergence of large-scale annotated datasets and affordable GPU hardware has allowed the training of neural networks for data analysis tasks which were previously addressed with hand-crafted features. Architectures such as convolutional neural networks, recurrent neural networks or Q-nets for reinforcement learning have shaped a brand new scenario in signal processing. This course will cover the basic principles of deep learning from both an algorithmic and computational perspectives.
This document summarizes a MatLab workshop covering various topics:
- MatLab Central, an official user community for asking and answering questions
- Cipher systems for encrypting text by shifting letters
- Least squares methods for fitting linear models to noisy data
- Dynamic code generation to display customized text
- Techniques for accelerating MatLab code such as vectorization and memory preallocation
The workshop emphasized best practices like utilizing help functions, saving intermediate work, and having fun with programming.
https://telecombcn-dl.github.io/2018-dlai/
Deep learning technologies are at the core of the current revolution in artificial intelligence for multimedia data analysis. The convergence of large-scale annotated datasets and affordable GPU hardware has allowed the training of neural networks for data analysis tasks which were previously addressed with hand-crafted features. Architectures such as convolutional neural networks, recurrent neural networks or Q-nets for reinforcement learning have shaped a brand new scenario in signal processing. This course will cover the basic principles of deep learning from both an algorithmic and computational perspectives.
The document discusses various time complexities of programming constructs like for loops, nested for loops, and inserting elements into data structures like lists and binary trees. It provides examples to explain concepts like big O notation, logarithmic time, and quadratic time complexity. Dynamic programming and backtracking algorithms are introduced as approaches to solve problems optimally with examples for the subset sum problem.
Animashree Anandkumar, Electrical Engineering and CS Dept, UC Irvine at MLcon...MLconf
Anima Anandkumar is a faculty at the EECS Dept. at U.C.Irvine since August 2010. Her research interests are in the area of large-scale machine learning and high-dimensional statistics. She received her B.Tech in Electrical Engineering from IIT Madras in 2004 and her PhD from Cornell University in 2009. She has been a visiting faculty at Microsoft Research New England in 2012 and a postdoctoral researcher at the Stochastic Systems Group at MIT between 2009-2010. She is the recipient of the Microsoft Faculty Fellowship, ARO Young Investigator Award, NSF CAREER Award, and IBM Fran Allen PhD fellowship.
the slides are aimed to give a brief introductory base to Neural Networks and its architectures. it covers logistic regression, shallow neural networks and deep neural networks. the slides were presented in Deep Learning IndabaX Sudan.
This document provides an overview of common number systems including decimal, binary, octal, and hexadecimal. It discusses how to convert between these different number systems by using place value and properties of their respective bases. Techniques for converting include dividing or multiplying by the base while tracking remainders. Examples are provided for converting between the different systems. Later sections cover additional topics like binary operations, fractions and conversions between decimal and binary fractions.
https://telecombcn-dl.github.io/2017-dlai/
Deep learning technologies are at the core of the current revolution in artificial intelligence for multimedia data analysis. The convergence of large-scale annotated datasets and affordable GPU hardware has allowed the training of neural networks for data analysis tasks which were previously addressed with hand-crafted features. Architectures such as convolutional neural networks, recurrent neural networks or Q-nets for reinforcement learning have shaped a brand new scenario in signal processing. This course will cover the basic principles of deep learning from both an algorithmic and computational perspectives.
The Munich LSTM-RNN Approach to the MediaEval 2014 “Emotion in Music” Taskmultimediaeval
In this paper we describe TUM's approach for the MediaEval's Emotion in Music" task. The goal of this task is to automatically estimate the emotions expressed by music (in terms of Arousal and Valence) in a time-continuous fashion. Our system consists of Long-Short Term Memory Recurrent Neural Networks (LSTM-RNN) for dynamic Arousal and Valence regression. We used two different sets of acoustic and psychoacoustic features that have been previously proven as effective for emotion prediction in music and speech. The best model yielded an average Pearson's correlation coeficient of 0.354 (Arousal) and 0.198 (Valence), and an average Root Mean Squared Error of 0.102 (Arousal) and 0.079 (Valence).
http://ceur-ws.org/Vol-1263/mediaeval2014_submission_7.pdf
SYSTEM IDENTIFICATION USING CEREBELLAR MODEL ARITHMETIC COMPUTERTarun Kumar
The field of identification is rather complex. This complexity is due to the variety of applications, goals, conditions, etc. Exact
specifications of final aim to be attained, analysis of available precision, etc. are some of the basic requirements to guide the work. In
this paper we used CMAC look up table for identification of both linear and non-linear systems. It deals with the basic CMAC
architectures, its capability and shows the motivations why CMAC net can be used for system identification. CMAC network has
hundreds of thousands of adjustable weights that can be trained to approximate non-linearities which are not explicitly written out or
even known. Its associative memory has a built in generalization. We have shown that due to its extremely fast mapping and training
operations, it is suitable for real time applications.
This document provides an overview of different number systems including decimal, binary, octal, and hexadecimal. It discusses how to convert between these number systems by using place value and properties of their respective bases. Techniques for converting include dividing or multiplying by the base while tracking remainders. Examples are provided for converting between the different number systems. Common powers and their prefixes for different bases are also defined. The document concludes with discussions of binary addition and multiplication.
This document describes a parallel algorithm for computing prefix sums and merging sorted arrays. It presents:
1) A parallel prefix algorithm that computes prefix sums in O(log n) time using O(n) processors by performing prefix computations in parallel across a binary tree representation.
2) A parallel merging algorithm that partitions input arrays into blocks of size O(log n), ranks block elements in parallel, and sequentially merges matching blocks, achieving O(log n) time and O(n) processors.
3) An analysis showing the parallel prefix algorithm runs in O(log n) time using O(n) processors, and two sorted arrays can be merged in O(log n) time using O(n
This document provides an introduction to a computer architecture and organization course. It discusses the history of computer architecture from Charles Babbage's Analytical Engine in the 1830s to modern computing devices. It also outlines the course structure, which will cover fundamental building blocks, data representation, fixed and floating point systems, and memory systems organization through lectures, problem sets, labs, and a final exam.
The document discusses the evolution of computers from ancient calculating devices like the abacus to modern computers. It covers early mechanical calculating devices developed between 3000 BC to the 18th century like the abacus, Napier's bones, Pascaline, and Leibnitz's calculator. It then discusses programmable mechanical computers like Jacquard's loom and pioneering electromechanical computers like Babbage's difference engine and analytical engine. The document concludes with a discussion of important milestones in modern computer development such as the Mark 1, Von Neumann architecture, ENIAC, EDVAC and the concept of generations of computers.
[Paper Reading] Attention is All You NeedDaiki Tanaka
The document summarizes the "Attention Is All You Need" paper, which introduced the Transformer model for natural language processing. The Transformer uses attention mechanisms rather than recurrent or convolutional layers, allowing for more parallelization. It achieved state-of-the-art results in machine translation tasks using techniques like multi-head attention, positional encoding, and beam search decoding. The paper demonstrated the Transformer's ability to draw global dependencies between input and output with constant computational complexity.
This document provides an overview of the CS101 Introduction to Computing course. It discusses the course contents and structure, which will cover fundamental computing concepts, web page development, and productivity software over 15 weeks. Students will complete assignments, a midterm exam, and a final exam. The first assignment requires students to email the instructor about their future plans and post a message on the course message board about customizing the class material. Upcoming lectures will discuss the history of computing from Babbage's Analytical Engine to modern computers.
This document provides an overview of a course on computer fundamentals. The course aims to give students an understanding of how computers work at the assembly level and introduce assembly language programming. Topics covered include the fetch-execute cycle, memory hierarchy, CPU components like the ALU and registers, number representation, and arithmetic and logical instructions. The course outline provides context on the history of computing and early computer designs to prepare students for future operating systems courses.
Hardware Acceleration for Machine LearningCastLabKAIST
This document provides an overview of a lecture on hardware acceleration for machine learning. The lecture will cover deep neural network models like convolutional neural networks and recurrent neural networks. It will also discuss various hardware accelerators developed for machine learning, including those designed for mobile/edge and cloud computing environments. The instructor's background and the agenda topics are also outlined.
Evaluation of programs codes using machine learningVivek Maskara
This document discusses using machine learning to detect copied code submissions. It proposes using unsupervised learning via k-means clustering and dimensionality reduction with principal component analysis (PCA) to group similar codes and reduce complexity from O(n^2) to O(n). Key steps include extracting features from codes, applying PCA to reduce dimensions, running k-means to cluster codes, and detecting copies between clusters. This approach could help identify cheating in online programming contests and evaluate student code submissions.
The document summarizes the evolution of information technology (IT) from the 1970s to present day. It covers the evolution of computers from early mechanical devices like the abacus to modern integrated circuits. It also discusses the evolution of storage technologies from punched cards to cloud storage. Finally, it outlines the evolution of software, including operating systems from UNIX to Windows, programming languages from machine code to artificial intelligence languages, and general software applications.
This document provides an introduction to computer vision with convoluted neural networks. It discusses what computer vision aims to address, provides a brief overview of neural networks and their basic building blocks. It then covers the history and evolution of convolutional neural networks, how and why they work on digital images, their limitations, and applications like object detection. Examples are provided of early CNNs from the 1980s and 1990s and recent advancements through the 2010s that improved accuracy, including deeper networks, inception modules, residual connections, and efforts to increase performance like MobileNets. Training deep CNNs requires large datasets and may take weeks, but pre-trained networks can be fine-tuned for new tasks.
Introduction to computer vision with Convoluted Neural NetworksMarcinJedyk
Introduction to computer vision with Convoluted Neural Networks - going over history of CNNs, describing basic concepts such as convolution and discussing applications of computer vision and image recognition technologies
Event description:
Why Tangent Works chooses Julia: The Two Language Problem
TIM: Automatic Model Building for Energy Industry
Julia and its major differences to other technical computing languages (R, Matlab, ...)
- Why is vectorized code fast?
- Why is it not as fast as it could be?
Speaker:
Ján Dolinský, Tangent Works (www.tangent.works)
Language of the event: Julia, Slovak & English
------------------------------------
PyData Bratislava [Python Data Enthusiasts and Users, Data Scientists & Statisticians of all levels from Slovakia]
------------------------------------
--
This meetup group is for Data Scientists, Statisticians, Economists and Data Enthusiasts using Python for data analysis and data visualization. The goals are to provide Python enthusiasts a place to share ideas and learn from each other about how best to apply the language and tools to ever-evolving challenges in the vast realm of data management, processing, analytics, and visualization.
--
PyData is a group for users and developers of data analysis tools to share ideas and learn from each other. We gather to discuss how best to apply Python tools, as well as those using R and Julia, to meet the evolving challenges in data management, processing, analytics, and visualization. PyData groups, events, and conferences aim to provide a venue for users acrossall the various domains of data analysis to share their experiences and their techniques. PyData is organized by NumFOCUS.org, a 501(c)3 non-profit in the United States.
------------------------------------
Our Facebook group here: https://www.facebook.com/groups/1813599648877946/
Our Twitter account here: https://twitter.com/PyDataBA
Our LinkedIn group here: https://www.linkedin.com/groups/13506080
All materials from previous meetups on GitHub here: https://github.com/GapData/PyDataBratislava
Recordings of previous meetups on our YouTube here: https://www.youtube.com/watch?v=XYpKpmapqjI&list=PLISV6olKXnd9pE-KPtPgwwLe6qPXvb9K7
------------------------------------
Organizers:
GapData Institute (https://www.gapdata.org/) (GDI) is a nonprofit nonpartisan research institution harnessing power of data & wisdom of economics for public good.
|| Data. Think. Change. ||
--
NumFOCUS (http://www.numfocus.org/) is a 501(c)(3) nonprofit that supports and promotes world-class, innovative, open source scientific computing. The mission of NumFOCUS is to promote sustainable high-level programming languages, open code development, and reproducible scientific research. We accomplish this mission through our educational programs and events as well as through fiscal sponsorship of open source data science projects. We aim to increase collaboration and communication within the scientific computing community.
This document provides an introduction and overview of NS2 (Network Simulator 2). It discusses that NS2 is an open-source discrete event network simulator used to simulate TCP/IP networks. It describes the architecture of NS2 which uses C++ for internal operations and OTCL as the user interface. It also discusses the advantages of using Linux over Windows for NS2 and provides some basic Linux commands.
This document provides an introduction and overview of key concepts in software development and data structures. It discusses the software development process, performance analysis using Big O notation, abstract data types, and introduces common data structures. Some key topics covered include specification and design of problems, implementation principles, testing and debugging, complexity analysis, preconditions and postconditions, and object-oriented programming as it relates to data structures.
C++ Is One Of The widely used programming language. Here is the complete presentation PPT notes of C++ programming language. hope it will be helpful to you.
Programming for Problem Solving Unit 1Dhiviya Rose
The document discusses a course on programming for problem solving that covers the history and evolution of computers from the abacus to modern machines, different types and generations of computers, number systems including binary, octal, decimal, and hexadecimal, and how to convert between number systems. It also provides an outline of topics to be covered in the course like computer organization, C programming basics, arrays and strings, functions and pointers, structures and unions.
Allan Menezes has over 30 years of experience in programming, mathematics, and computer science. He has a BSc in computer science and mathematics as well as an MMath from the University of Waterloo. His skills include programming in C, C++, Java, and XML as well as designing Linux clusters and supercomputers. Currently, he is pursuing an MSc in pure mathematics from the University of Toronto while working as a calculus TA.
Obtain an overview of computer science
• Become familiar with the definition of computer, its history and
the various classifications of computers.
• Learn about the various types of computers
This document provides information about a programming course titled "Programming for Problem Solving" taught by Mr. Vivek Parashar at Amity School of Engineering & Technology. It includes details about the course code, credit units, objectives, learning outcomes, syllabus, textbooks, and expectations for students. The course is intended to teach students programming in C language and problem solving techniques through various modules covering topics like arrays, functions, recursion, structures, pointers, and file handling.
Deep Implicit Layers: Learning Structured Problems with Neural NetworksSangwoo Mo
Deep implicit layers allow neural networks to solve structured problems by following algorithmic rules. They include layers for convex optimization, discrete optimization, differential equations, and more. The forward pass runs an algorithm, while the backward pass computes gradients using algorithmic properties like KKT conditions. This enables problems like structured prediction, meta-learning, and time series modeling to be solved reliably with neural networks by respecting their underlying structure.
This document provides an overview of VLSI physical design automation. It begins with introducing the intended audience for VLSI CAD, which includes VLSI students, circuit designers, process engineers, and those interested in solving hard computational problems. The objectives of VLSI layout design are then outlined, which are to review fabrication materials and processes, understand the basic algorithm concepts used in layout design, and learn about state-of-the-art academic and commercial physical design automation techniques. The document then describes the basic steps in the physical design cycle, including partitioning, floorplanning, placement, routing, and compaction. Circuit partitioning is discussed in more detail, including definitions, formulations, representation, iterative algorithms like Kernighan-Lin, and other
Similar to Lec1- CS110 Computational Engineering (20)
The document discusses pointers and arrays in C programming. It provides examples of code using pointers to access array elements and pass arrays to functions. Key points covered include: pointers can return arrays from functions; pointers and arrays are equivalent (pointer to first element acts as array name); and dynamic memory allocation using malloc allows arrays of variable length.
This document discusses pointers in C programming. It covers:
- Pointers store memory addresses of variables rather than the variable's value. For example, int *p stores the address of an integer variable.
- Arrays are passed by reference in C, so changing an array element inside a function modifies the original array in the calling function.
- Multidimensional arrays can be passed to functions using pointers to the array and its dimensions. This allows the function to modify the original multidimensional array.
This document discusses function calls in C programming. It explains that functions help break programs into basic units and allow programs to run with less memory but slower. Functions communicate through arguments and return values. Arguments are passed by value by default, meaning the function gets copies of the original values rather than the original variables. Arguments can also be passed by reference using pointers. Examples demonstrate recursive functions like calculating factorials iteratively and recursively, and how tail recursion optimizes recursion.
This document discusses solutions to creative problems using functions. It presents four creative questions that involve using a black box function to multiply matrices in different ways. The black box functions take matrices as input and output their product or square. The questions demonstrate how to use the black box functions to multiply two arbitrary matrices by decomposing the matrices in ways compatible with the black box functions. It also discusses general concepts of using functions to break down large tasks, hide implementation details, and build on existing functionality through modular programming.
This document contains notes from a lecture on data input/output (I/O) in C programming. It discusses:
- Lab assignments for an RFID course being allocated to different days of the week, with no re-allocations after a certain date.
- The printf() function for formatted output, covering format specifiers, minimum field widths, floating point precision, uppercase conversion, and interesting prefixes.
- Input functions like gets() and fgets(), and output functions like puts() and fputs().
- Opening and writing to binary files for more efficient storage of data types like integers compared to text files.
- A creative problem about using a "black box" that multiplies
The document discusses various input/output functions in C including character I/O functions like getchar() and putchar(), string I/O functions like gets() and puts(), and general I/O functions like printf() and scanf(). It provides examples of using these functions to read keyboard input, write output to the screen, read from and write to files. The document also covers format specifiers that can be used with scanf() to read different data types from the input and control skipping or suppressing assignment of certain values.
This document discusses various operators and expressions in programming languages. It covers arithmetic, relational, logical, and assignment operators. It explains operator precedence and provides examples of using different operators on integer, floating point, and character data types. Type conversions and casts are also described. Conditional expressions and tricks with logical operators are explained. Finally, a creative question is posed about using a "black box" to multiply matrices.
This document provides a summary of a lecture on arrays in C. It discusses loops like for, while, and do-while and how to determine the final condition. It then outlines 3 problems for a lab work assignment on strings: 1) determining the length of a string using a while loop, 2) checking if a string is a palindrome by comparing it reversed, and 3) reversing a string without using a temporary array. The document provides examples and pseudocode for implementing the solutions.
This document summarizes different methods for solving the celebrity problem of identifying a celebrity (if one exists) among a group of people by asking questions of the form "does A know B?". It begins by outlining a naive method that asks all n(n-1) possible questions. It then presents a better solution that iteratively eliminates people, requiring only 3n-3 questions. Finally, it describes the best solution that groups people into pairs, requiring only n-1 questions by treating the problem as a binary tree. The document explains this best solution in detail and notes that no algorithm can solve the problem using fewer than n-1 questions.
This document summarizes a lecture on arrays in C. It discusses:
- Arrays can store multiple values of the same type sequentially in memory (e.g. an array of integers)
- Strings are arrays of characters that end with a null terminator
- Common string functions like strcpy(), strlen(), and strcat()
- Arrays use contiguous memory locations, so an element's address can be calculated from the base address
- Multi-dimensional arrays can model matrices by using an array of arrays
- An example is provided to find a "celebrity" (someone known by all but knowing no one) in a group, which takes 3(n-1) questions
This document summarizes a lecture on data types in C. It discusses built-in data types like int, char, float, and double. It explains how these types can vary in size depending on the architecture and compiler. It also covers integer variations like signed, unsigned, long, and short. The lecture defines constants, escape sequences, and ASCII values. It provides an example program to print the sizes of different data types. It asks questions to test understanding of valid identifiers, keywords, scanf/printf behavior, and debugging strategies.
Today's lecture covered revision, writing binary numbers in order quickly, and two's complement arithmetic. It also presented a creative exercise problem about finding a celebrity at a party who is known by everyone but knows no one, with the goal being to reduce the number of yes/no questions asked from the trivial n(n-1) solution. The lecture notes provided the celebrity problem but did not give the optimized solution.
This document summarizes the contents of the CS110 lecture on modeling computation. It discusses solving quadratic equations, including calculating discriminants and square roots. It provides sample code for solving quadratic equations and multiplying polynomials. It also presents an algorithm for designing a communication pattern such that all people can share information in log2n steps.
This document provides an overview and summary of CS110 Models of Computing Lecture 4. It discusses more concepts in C programming like writing readable code, additional programming constructs, and complex problem solving. It also covers desirable program characteristics like integrity, clarity, simplicity, efficiency, modularity, and generality. Finally, it discusses key concepts in computing like the C preprocessor, data types in C, strings, identifiers, keywords, variables, and how integers are represented using binary. It provides examples to illustrate these concepts.
CS110 lecture covered the start of the CS110 lab, assignments for the course including programming assignments, and an overview of the Towers of Hanoi problem. Students are divided into batches based on their RFID for their lab days. The first assignment involves editing a letter using Unix commands, and the second introduces the "Hello World" program. The Towers of Hanoi problem was explained, showing its recursive solution and that the number of moves required is 2^n - 1 for n disks.
This lecture discusses the history and evolution of computing hardware from early mechanical calculators and looms to modern computers. It describes Charles Babbage's analytical engine, considered the first general-purpose computer. The lecture outlines the development of hardware components like the CPU and memory and how early computers like ENIAC used vacuum tubes. It explains the basic structure of a computer as having a processor and memory, with programs stored as instructions and data. The lecture also introduces the concept of variables, data types, and how instructions operate on data through examples.
This document provides information about the CS110: Computational Engineering course. It includes details about lectures, instructors, timings, labs, and lab instructors. Lectures are on Mondays from 11 AM, Tuesdays from 10 AM, and Thursdays from 8 AM. Labs are on Fridays from 6 PM at the DCF department. The course uses RFID cards for attendance tracking. Evaluation includes quizzes, assignments, and an end of semester exam. Students are encouraged to provide feedback.
Pointer arithmetic allows pointer variables to be manipulated using arithmetic operations. Some key rules include:
1. A pointer variable can be assigned the address of an ordinary variable using the & operator. Casting is possible between different pointer types.
2. A pointer variable can be assigned the value of another pointer variable if they are of the same type.
3. A pointer variable can be assigned the null value NULL.
When manipulating pointers, the type of the pointer variable determines the amount of increment or decrement from arithmetic operations like ++. Pointers can only be subtracted if they point to elements within the same array.
This document discusses Android, an open source mobile operating system developed by Google and the Open Handset Alliance. It provides an overview of Android features such as its application framework, virtual machine, browser, graphics APIs, databases, codecs, and support for Bluetooth, wireless networks and sensors. Challenges of developing for Android like limited hardware and intermittent networks are outlined. Opportunities in the growing mobile market are highlighted, along with examples of possible Android applications like augmented reality, games, and distributed computing. Project suggestions are given including web scrapers, asynchronous games, and location-aware planners.
The document summarizes vulnerabilities in the Android operating system. It describes Android's architecture, including its Linux kernel base and use of the Dalvik virtual machine. It then outlines several known vulnerabilities, such as issues in processing GIF, PNG, and BMP images that can allow arbitrary code execution. General mobile device vulnerabilities like Bluetooth exploits are also discussed. The document concludes by noting that while Android's open nature can enable vulnerabilities, it also allows for a strong community to address issues over time.
This slide is special for master students (MIBS & MIFB) in UUM. Also useful for readers who are interested in the topic of contemporary Islamic banking.
Thinking of getting a dog? Be aware that breeds like Pit Bulls, Rottweilers, and German Shepherds can be loyal and dangerous. Proper training and socialization are crucial to preventing aggressive behaviors. Ensure safety by understanding their needs and always supervising interactions. Stay safe, and enjoy your furry friends!
हिंदी वर्णमाला पीपीटी, hindi alphabet PPT presentation, hindi varnamala PPT, Hindi Varnamala pdf, हिंदी स्वर, हिंदी व्यंजन, sikhiye hindi varnmala, dr. mulla adam ali, hindi language and literature, hindi alphabet with drawing, hindi alphabet pdf, hindi varnamala for childrens, hindi language, hindi varnamala practice for kids, https://www.drmullaadamali.com
Physiology and chemistry of skin and pigmentation, hairs, scalp, lips and nail, Cleansing cream, Lotions, Face powders, Face packs, Lipsticks, Bath products, soaps and baby product,
Preparation and standardization of the following : Tonic, Bleaches, Dentifrices and Mouth washes & Tooth Pastes, Cosmetics for Nails.
বাংলাদেশের অর্থনৈতিক সমীক্ষা ২০২৪ [Bangladesh Economic Review 2024 Bangla.pdf] কম্পিউটার , ট্যাব ও স্মার্ট ফোন ভার্সন সহ সম্পূর্ণ বাংলা ই-বুক বা pdf বই " সুচিপত্র ...বুকমার্ক মেনু 🔖 ও হাইপার লিংক মেনু 📝👆 যুক্ত ..
আমাদের সবার জন্য খুব খুব গুরুত্বপূর্ণ একটি বই ..বিসিএস, ব্যাংক, ইউনিভার্সিটি ভর্তি ও যে কোন প্রতিযোগিতা মূলক পরীক্ষার জন্য এর খুব ইম্পরট্যান্ট একটি বিষয় ...তাছাড়া বাংলাদেশের সাম্প্রতিক যে কোন ডাটা বা তথ্য এই বইতে পাবেন ...
তাই একজন নাগরিক হিসাবে এই তথ্য গুলো আপনার জানা প্রয়োজন ...।
বিসিএস ও ব্যাংক এর লিখিত পরীক্ষা ...+এছাড়া মাধ্যমিক ও উচ্চমাধ্যমিকের স্টুডেন্টদের জন্য অনেক কাজে আসবে ...
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...PECB
Denis is a dynamic and results-driven Chief Information Officer (CIO) with a distinguished career spanning information systems analysis and technical project management. With a proven track record of spearheading the design and delivery of cutting-edge Information Management solutions, he has consistently elevated business operations, streamlined reporting functions, and maximized process efficiency.
Certified as an ISO/IEC 27001: Information Security Management Systems (ISMS) Lead Implementer, Data Protection Officer, and Cyber Risks Analyst, Denis brings a heightened focus on data security, privacy, and cyber resilience to every endeavor.
His expertise extends across a diverse spectrum of reporting, database, and web development applications, underpinned by an exceptional grasp of data storage and virtualization technologies. His proficiency in application testing, database administration, and data cleansing ensures seamless execution of complex projects.
What sets Denis apart is his comprehensive understanding of Business and Systems Analysis technologies, honed through involvement in all phases of the Software Development Lifecycle (SDLC). From meticulous requirements gathering to precise analysis, innovative design, rigorous development, thorough testing, and successful implementation, he has consistently delivered exceptional results.
Throughout his career, he has taken on multifaceted roles, from leading technical project management teams to owning solutions that drive operational excellence. His conscientious and proactive approach is unwavering, whether he is working independently or collaboratively within a team. His ability to connect with colleagues on a personal level underscores his commitment to fostering a harmonious and productive workplace environment.
Date: May 29, 2024
Tags: Information Security, ISO/IEC 27001, ISO/IEC 42001, Artificial Intelligence, GDPR
-------------------------------------------------------------------------------
Find out more about ISO training and certification services
Training: ISO/IEC 27001 Information Security Management System - EN | PECB
ISO/IEC 42001 Artificial Intelligence Management System - EN | PECB
General Data Protection Regulation (GDPR) - Training Courses - EN | PECB
Webinars: https://pecb.com/webinars
Article: https://pecb.com/article
-------------------------------------------------------------------------------
For more information about PECB:
Website: https://pecb.com/
LinkedIn: https://www.linkedin.com/company/pecb/
Facebook: https://www.facebook.com/PECBInternational/
Slideshare: http://www.slideshare.net/PECBCERTIFICATION
The simplified electron and muon model, Oscillating Spacetime: The Foundation...RitikBhardwaj56
Discover the Simplified Electron and Muon Model: A New Wave-Based Approach to Understanding Particles delves into a groundbreaking theory that presents electrons and muons as rotating soliton waves within oscillating spacetime. Geared towards students, researchers, and science buffs, this book breaks down complex ideas into simple explanations. It covers topics such as electron waves, temporal dynamics, and the implications of this model on particle physics. With clear illustrations and easy-to-follow explanations, readers will gain a new outlook on the universe's fundamental nature.
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...Dr. Vinod Kumar Kanvaria
Exploiting Artificial Intelligence for Empowering Researchers and Faculty,
International FDP on Fundamentals of Research in Social Sciences
at Integral University, Lucknow, 06.06.2024
By Dr. Vinod Kumar Kanvaria
1. CS110
Computational Engineering
An Introduction to
Problem Solving using Computers
V. Kamakoti
Course Material – P.Sreenivasa Kumar, N.S.Narayanaswamy, Deepak Khemani, V. Kamakoti– CS&E, IIT M
1
2. Common uses of a Computer
• As a tool for storing and retrieving information
– Extracting and storing information regarding students
entering IIT
• As a tool for providing services to customers
– Billing, banking, reservation
• As a calculator capable of user-defined operations
– Designing circuits layouts
– Designing structures
– Non-destructive testing and simulation
PSK, NSN, DK, VK – CS&E, IIT M
2
3. Course Outline
• Introduction to Computing
• Programming (in C)
• Exercises and examples are from the
mathematical area of Numerical Methods.
• Problem solving using computers.
• Simulators
– Theory (different ways of simulation)
– Practice (Programs that simulate, say queues)
PSK, NSN, DK, VK – CS&E, IIT M
3
4. Evaluation
• Two Quizzes – 25
– Quiz 1, programming in C with some numerical methods
– Quiz 2, Numerical Methods and programming
• Programming Assignment – 25
• End of Semester Exam – 50
– Quiz 1 + Quiz2 + Simulation
• Attendance – taken in the class + Lab.
– Sit according to the roll numbers
– Report tampering of the stickers to the TAs
• Timing slots
– Monday, Tuesday (Theory) and Thursday (Programming for
next week)
PSK, NSN, DK, VK – CS&E, IIT M
4
5. Lab work
• Instruction on Thursdays in regular class hours
• Programming - Two hours per week
– 6.00 to 8.00 PM
– Monday to Friday
– 50 students per batch
– Individual work - no groups
– Venue - Department Computing Facility of CSE
Dept.
• Attendance compulsory for lab too!!
PSK, NSN, DK, VK – CS&E, IIT M
5
6. Every Lecture - Before and After
• Sit in the place marked for you else you will be
marked absent.
• Attendance will be taken by the TAs 10 minutes
after the commencement of the class.
• Please switch off your mobile phones
• Collect the feedback form from the TA at the
start of every lecture and return the same at the
end of every lecture
PSK, NSN, DK, VK – CS&E, IIT M
6
7. Lab work
• Please be available at the DCF of CSE
Department at least 10 minutes before the start of
the lab on the day allotted day.
• Purchase a 100 page (minimum) bound notebook
which will be your record notebook.
• Bring the record notebook to every lab class.
PSK, NSN, DK, VK – CS&E, IIT M
7
8. What is this CS110 about?
• Computer and its components
• Computing – personal, distributed, parallel
• Programming Languages
• Problem Solving and Limitations of a Computer
PSK, NSN, DK, VK – CS&E, IIT M
8
9. What IS a computer?
•
•
•
•
•
•
•
A computer is a machine
Something that operates mechanically
But it is a flexible machine
Its behaviour is controlled by a program
A program is like a spell cast on a machine
Programmers are like wizards
Programs reside in the memory of the machine
– Charles Babbage (1791-1871)
– “The stored program concept”
PSK, NSN, DK, VK – CS&E, IIT M
9
10. Early Computing Hardware
The Slide rule
The Chinese Abacus
The gear replaced the beads in
early mechanical calculators
“History of computing hardware”
From Wikipedia, the free encyclopedia
PSK, NSN, DK, VK – CS&E, IIT M
10
12. The Difference Engine
Part of Babbage's difference
engine, assembled after his
death by Babbage's son, using
parts found in his laboratory.
The London Science Museum's
replica Difference Engine, built
from Babbage's design.
PSK, NSN, DK, VK – CS&E, IIT M
12
13. The First Programmer
Augusta Ada King, Countess of
Lovelace (December 10, 1815 –
November 27, 1852), born Augusta
Ada Byron, is mainly known for
having written a description of
Charles Babbage's early mechanical
general-purpose computer, the
analytical engine.
The programming language ADA is named after her.
PSK, NSN, DK, VK – CS&E, IIT M
13
14. ENIAC – the first electronic computer
Physically, ENIAC was
massive compared to modern
PC standards. It contained
17,468 vacuum tubes, 7,200
crystal diodes, 1,500 relays,
70,000 resistors, 10,000
capacitors and around 5
million hand-soldered joints.
It weighed 30 short tons (27 t),
was roughly 8 feet (2.4 m) by
3 feet (0.9 m) by 100 feet (30
m), took up 1800 square feet
(167 m²), and consumed 150
kW of power.
PSK, NSN, DK, VK – CS&E, IIT M
14
16. The computing machine
PROCESSOR
MEMORY
01234…….
(say) 256 MEGABYTES
The computer is made up of a processor and a memory. The memory
can be thought of as a series of locations to store information.
PSK, NSN, DK, VK – CS&E, IIT M
16
17. The computing machine
PROCESSOR
MEMORY
01234…….
program
256 MEGABYTES
data
The processor treats part of the information in memory as instructions,
and a part of it as data. A program is a sequence of instructions
assembled for some given task. Most instructions operate on data. Some
instructions control the flow of the operations. It is even possible to treat
programs as data. By doing so a program could even modify itself.
PSK, NSN, DK, VK – CS&E, IIT M
17
18. Random numbers
Q: If the computer is a machine how can it generate
random numbers?
A: It cannot generate truly random numbers but
what we call as pseudo random numbers.
• The sequence generated will have periodicity, but
the period can be made arbitrarily large.
– Mersenne Twister algorithm (1997) has a period of
(219937 -1) iterations.
– Question: How big is 2100 ?
PSK, NSN, DK, VK – CS&E, IIT M
18
19. The middle-square method
John von Neumann devised the method
in 1946.
Take any number, square it, remove the
middle digits of the resulting number
as your "random number", then use
that number as the seed for the next
iteration. For example, squaring the
number "1111" yields "1234321",
which can be written as "01234321",
an 8-digit number being the square of
a 4-digit number. This gives "2343"
as the "random" number. Repeating
this procedure gives "4896" as the
next result, and so on. Von Neumann
used 10 digit numbers, but the
process was the same.
Considered by many to be the
greatest scientist of the 20th
century!
PSK, NSN, DK, VK – CS&E, IIT M
19
20. Variables
• Each memory location is given a name.
• The name is the variable that refers to the data
stored in that location.
• Variables have types that define the interpretation
data.
– e.g. integers (1, 14, 25649), or characters (a, f, G, H)
• All data is represented as binary strings. That is,
it is a sequence of 0’s and 1’s, of a predetermined
size – “word”. A byte is made of 8 bits.
PSK, NSN, DK, VK – CS&E, IIT M
20
21. Instructions
• Instructions take data stored in variables as
arguments.
• Some instructions do some operation on the data
and store it back in some variable.
• The instruction “XX+1” on integer type says
that “Take the integer stored in X, add 1 to it, and
store it back in (location) X”..
• Other instructions tell the processor to do
something. For example, “jump” to a particular
instruction next, or to exit
PSK, NSN, DK, VK – CS&E, IIT M
21
22. Programs
• A program is a sequence of instructions.
• Normally the processor works as follows,
– Step A: pick next instruction in the sequence
– Step B: get data for the instruction to operate upon
– Step C: execute instruction on data (or “jump”)
– Step D: store results in designated location (variable)
– Step E: go to Step A
• Such programs are known as imperative
programs.
PSK, NSN, DK, VK – CS&E, IIT M
22
23. Programming paradigms
• Imperative programs are sequences of instructions. They
are abstractions of how the von Neumann machine
operates.
• Pascal, C, Fortran
• Object Oriented Programming Systems (OOPS) model
the domain into objects and interactions between them.
• Simula, CLOS, C++, Java
• Logic programs use logical inference as the basis of
computation.
• Prolog
• Functional programs take a mathematical approach of
functions.
• LISP, ML, Haskell
PSK, NSN, DK, VK – CS&E, IIT M
23
24. A Limitation – Computer Arithmetic
• Number of digits that can be stored is limited
• Causes serious problem.
Consider a computer that can store
Sign, 3 digits and a decimal point.
Sign and decimal point are optional
example : 212., -212., -21.2, -2.12, -.212
PSK, NSN, DK, VK – CS&E, IIT M
24
25. More Examples
• 113. + -111. = 2.00
• 2.00 + 7.51 = 9.51
• -111. + 7.51 = -103.49 (exact arithmetic)
But the computer can store only 3 digits.
So it rounds –103.49 to –103. (as a rule)
This is a very important thing to know as a
System designer. Why?
PSK, NSN, DK, VK – CS&E, IIT M
25
27. Conclusion
• Computer is fast but restricted
• So we must learn to use its speed
• And manage its restrictions
PSK, NSN, DK, VK – CS&E, IIT M
27
28. Books
• C How to Program, Deitel and Deitel
• C – The programming Language, Kernighan and
Ritchie
• Unix – The Programming Environment,
Kernighan and Pike
• Numerical Recipes in C - Surf the website
www.library.cornell.edu/nr/bookcpdf.html
Make sure your machine has Adobe Acrobat
Reader
PSK, NSN, DK, VK – CS&E, IIT M
28
29. Review
Computers:
- almost everywhere these days
- banks, shops, railway reservations,
internet/web
- engineering applications
VLSI chip design, machine design (CAD/CAM),
structural analysis, process control etc etc
- doing without computers - unimaginable
Computer Software:
- collection of instructions to the computer
PSK, NSN, DK, VK – CS&E, IIT M
29
30. Software
Very critical component in a computer application
Considerable complexity
– large collection of programs
– subdivided into modules with specific purposes
– developed by a team of individuals
– involves - system design, choice of algorithms,
choice of data structures, language of
implementation, testing, maintenance
PSK, NSN, DK, VK – CS&E, IIT M
30
32. The Blocks, Their Functions
• Input unit
Takes inputs from the external world via
variety of input devices- keyboard, mouse,
temperature sensors, odometers, wireless
Devices etc.
• Output Unit
Sends information (after retrieving, processing)
to output devices –monitors/displays, projectors,
audio devices, switches, relays, gearbox etc.
PSK, NSN, DK, VK – CS&E, IIT M
32
33. More (try more filename on your unix/linux machine)
• Memory
Place where information is stored.
Primary memory – Electronic devices, used
primarily by other such devices, for temporary storage.
Characterized by their speedy response.
Secondary Memory – Devices for Long term storage.
Contained well tuned mechanical components,
magnetic storage media – floppies, hard disks.
Compact Disks use optical technology. Used to store
user data (programs, inputs, results etc.), also used
extensively during computation.
PSK, NSN, DK, VK – CS&E, IIT M
33
34. Some More (Commands are in /bin, /usr/bin. Use ls)
• System Bus
Essentially a set of wires, used by the
other units to communicate with each other.
transfer data at a very high rate
• ALU – Arithmetic and Logic Unit
Processes data- add, subtract
Decides – after comparing with another
value, for example
PSK, NSN, DK, VK – CS&E, IIT M
34
35. Finally (check man cp, man mv, man ls, man –k search string)
• Control Unit
Controls the interaction among other units.
Knows each unit by its name, responds to
requests fairly, reacts quickly on certain
critical events. Gives up control
periodically in the interest of the system.
Together with the ALU is called the CPU.
PSK, NSN, DK, VK – CS&E, IIT M
35
36. THE CPU (editors vi, emacs used to create text)
•
•
•
•
•
Can fetch an instruction from memory
Execute the instruction
Store the result in memory
A program – a set of instructions
An instruction has the following structure
Operation, operands, destination
• A simple operation – creating variables
Create a /* labels a memory location using the letter a*/
Very important abstraction – use of alphanumeric strings
To represent data. Simplifies the usage of a computer.
PSK, NSN, DK, VK – CS&E, IIT M
36
37. Compilers
Human friendly languages source code
Source code in a
Higher Level Language
Source code in a
Higher Level Language
Compiler
Compiler
Assembly language code
Assembler, linker, loader
machine language code
Machine understandable language
PSK, NSN, DK, VK – CS&E, IIT M
37
38. Assembly language
• an x86/IA-32 processor can execute the
following binary instruction as expressed in
machine language:
Binary: 10110000 01100001
mov al, 061h
– Move the hexadecimal value 61 (97 decimal) into the
processor register named "al".
– assembly language representation is easier to
remember (more mnemonic)
From Wikipedia
PSK, NSN, DK, VK – CS&E, IIT M
38
39. Higher Level Languages
• Higher level instructions = many assembly
instructions
• For example “X = Y + Z” could require the
following sequence
– Fetch into R1 contents of Y
– Fetch into R2 contents of Z
– Add contents of R1 and R2 and store it in R1
– Move contents of R1 into location named X
• HLLs can be at many levels
PSK, NSN, DK, VK – CS&E, IIT M
39
40. The C programming language
C Language is • an imperative general-purpose language
• used extensively in the development of UNIX
• extremely effective and expressive
• not a “very high level” nor a “big” language
• has compact syntax, modern control flow and
data structures and a rich a set of operators
• extensive collections of library functions
PSK, NSN, DK, VK – CS&E, IIT M
40
41. Origins of C
•Developed by Dennis Ritchie at Bell Labs
– first implemented on DEC PDP-11 in 1972
•Based on two existing languages
– BCPL and B languages
– BCPL: Martin Richards, 1967 - systems
programming
– B: Ken Thomson, 1970 - early versions of UNIX
The C Programming Language- Kernighan, Ritchie, 1978
•ANSI C: a standard adopted in 1990
– unambiguous, machine-independent definition of C
The C Programming Language (2nd edition)- Kernighan,
Ritchie, 1988
PSK, NSN, DK, VK – CS&E, IIT M
41
42. Developing and using a C program
A C program typically goes through six phases
1. Editor: the program is created and stored on disk
– vi and emacs are popular editors on UNIX
– usually part of IDE on windows platforms
2. Preprocessor: handles preprocessor directives
– include other files, macro expansions etc
3. Compiler: translates the program
– into machine language code or object code
– stores on disk
PSK, NSN, DK, VK – CS&E, IIT M
42
43. Other phases
4. Linker: combines
– the object code of the program
– object code of library functions and other functions
creates an executable image with no “holes”
5. Loader:
– transfers the executable image to the memory
6. Execute:
– computer carries out the instructions of the program
PSK, NSN, DK, VK – CS&E, IIT M
43
44. Programs = solutions
• A program is a sequence of instructions
– This is from the perspective of the machine or the
compiler!
• A program is a (frozen) solution
– From the perspective of a human a program is a
representation of a solution devised by the human.
Once frozen (or written and compiled) it can be
executed by the computer – much faster, and as many
times as you want.
PSK, NSN, DK, VK – CS&E, IIT M
44
45. Programming = Problem Solving
• Software development involves the following
– A study of the problem (requirements analysis)
– A description of the solution (specification)
– Devising the solution (design)
– Writing the program (coding)
– Testing
• The critical part is the solution design. One must
work out the steps of solving the problem,
analyse the steps, and then code them into a
programming language.
PSK, NSN, DK, VK – CS&E, IIT M
45
46. A tiny program
A comment
/* A first program in C */
#include <stdio.h>
Library of standard input output
functions
main( )
Every C program starts
{
execution with this
printf(“Hello, World! n”);
function.
}
Statement & terminator
Body of the function
- enclosed in braces
PSK, NSN, DK, VK – CS&E, IIT M
Escape sequence - newline
printf - a function from C Standard library stdio.h
- prints a char string on the standard output46
47. Programming Basics
(vi, emacs for programs)
• A variable – changes value during the execution of a
program.
• A variable has a name, e.g. – name, value, speed,
revspersec etc.
• Always referred to by its name
• The computation/computer uses its value or the address
of the location corresponding to the variable name.
• &name denotes the address of name, &value, &speed
etc.
• Note: physical address changes from one run of the
program to another.
PSK, NSN, DK, VK – CS&E, IIT M
47
48. Variables and constants
Names
- made up of letters and digits
underscore ( _ ) : recommended for long names
case sensitive : LaTeX and LateX are different
maximum size: 31 chars ( 6 chars for external names)
- first character must be a letter
avoid underscore as the first letter ( some library fns use it)
- choose meaningful and self-documenting names
for constants as well as variables
- keywords - if, for, else, float etc - reserved
PSK, NSN, DK, VK – CS&E, IIT M
48
49. Assignments and variables(what is a debugger)
• The value of a variable is modified due to an
assignment.
• The modified value could be result of an
evaluation, or could be a constant, or the value
of another variable.
• The LHS is variable to be modified and the RHS
is the value to be assigned.
• So RHS is evaluated first and then assignment
performed.
• a = b+1, a=c, a=5, a=a+1, a = a*a
PSK, NSN, DK, VK – CS&E, IIT M
49
50. Variable Declaration
(declaring variables, actually)
•
•
•
•
Need to declare variables.
A declaration: type variablename;
Types : int, float, char
int x; contents of the location corresponding to
x is treated as an integer. Number of bytes
assigned to a variable depends on its type.
• Assigning types helps write more correct
programs. Automatic type checking can catch
errors like integer = char +char;
PSK, NSN, DK, VK – CS&E, IIT M
50
51. Variables need Declaration
1
2
3
4
5
6
7
8
9
Another simple C program
#include<stdio.h>
A function
main()
from stdio.h
{int int_size;
int chr_size;
int flt_size;
int_size = sizeof(int); chr_size =sizeof(char);
flt_size = sizeof(float);
printf(“int, char, and float use %d %d and %d bytesn”,
int_size, chr_size; flt_size);
}
PSK, NSN, DK, VK – CS&E, IIT M
51
52. Exercise
• Type the above program using the vi editor.
• Compile it using cc
• Run the a.out file
• Write a program that outputs the coefficients of
a quadratic and prints out its roots
PSK, NSN, DK, VK – CS&E, IIT M
52
53. Modifying Variables
(rm with –i option)
• Each C program is a sequence of modification
of variable values
• A modification can happen due to operations
like +, -, /, *, etc.
• Also due to some functions provided by the
system like sizeof, sin etc.
• Also due to some functions (another part of your
program) created by the programmer.
PSK, NSN, DK, VK – CS&E, IIT M
53
54. An addition program
#include <stdio.h>
main( )
Declarations, must precede use
{
int operand1, operand2, sum;
“ %d ” - conversion
specifier
printf(“Enter first operandn”);
scanf(“%d”, &operand1);
d - decimal
printf(“Enter second operandn”);
& - address of operand1
scanf(“%d”, &operand2);
sum = operand1 + operand2;
assignment
printf(“The sum is %dn”, sum);
return 0;
Returning a 0 is used to
}
signify normal termination
PSK, NSN, DK, VK – CS&E, IIT M
54
55. Arithmetic operators in C
Four basic operators
+, – , ∗ , /
addition, subtraction, multiplication and division
applicable to integers and floating point numbers
integer division - fractional part of result truncated
12/ 5 2,
5/9 0
modulus operator : %
x % y : gives the remainder after x is divided by y
applicable only for integers, not to float/double
PSK, NSN, DK, VK – CS&E, IIT M
55
56. Order of evaluation (operator precedence)
first
parenthesized subexpessions
- innermost first
second
∗ , / and % - left to right
third
+ and –
- left to right
a+b∗ c∗d%e –f/g
4 1 2 3 6 5
a + ((( b ∗ c ) ∗ d ) % e ) – (f / g )
good practice -- use parentheses rather than rely on
precedence rules -- better readability
PSK, NSN, DK, VK – CS&E, IIT M
56
57. Precedence – another example
Value = a * (b+c) % 5 + x / (3 + p) – r - j
Evaluation order –
1. (b+c) and (3+p) : due to brackets
2. * and % and / have same precedence: a(b+c) is
evaluated first, then mod 5. Also, x/(3+p).
3. Finally, the additions and subtractions are
done from the left to right.
4. Finally, the assignment of the RHS to LHS is
done. = is the operator that violates the left to
right rule
PSK, NSN, DK, VK – CS&E, IIT M
57
58. Relational and logical operators
A logical variable can have two values
{true, false} or {t,f} or {1,0}
!
unary logical negation operator
< , <= , > , >=
comparison operators
= = , !=
equality and inequality
&&
logical AND operator
||
logical OR operator
logical operators return true/false
order of evaluation - as given above
note: assignment ( = ) equality ( = = )
PSK, NSN, DK, VK – CS&E, IIT M
58
59. Increment and decrement operators
unusual operators - prefix or postfix
only to variables
+ + adds 1 to its operand
– – subtracts 1 from its operand
N++ increments N after its use
++N increments N before its use
N = 4 ; X = N++; Y = ++N;
X = 4 , Y = 6 and N = 6 after the execution
PSK, NSN, DK, VK – CS&E, IIT M
59
60. Assignment statement/expression
• Form:variable-name = expression
total = test1_marks + test2_marks + end_sem_marks;
int i; float x;
i = x; fractional part of x is dropped
x = i; i is converted into a float
• Multiple assignment:
x=y=z=a+b
x = ( y = ( z = a + b) )
PSK, NSN, DK, VK – CS&E, IIT M
60
61. Assignment operators
expression
n = n + 10;
abbreviated form: n += 10; assignment operator
most binary operators: corr. assignment operator
X op= expr
X = X op (expr)
op : +, – , ∗, / , %
conciseness
PSK, NSN, DK, VK – CS&E, IIT M
61
62. Output Statement
printf(format-string, var1, var2, …, varn);
format-string indicates:
how many variables to expect
type of the variables
how many columns to use for printing them
any character string to be printed
–
sometimes this would be the only output
enclosed in double quotes
PSK, NSN, DK, VK – CS&E, IIT M
62
63. Examples - output
int x; float y;
x = 20; y = – 16.7889;
printf(“Value x = %d and value y = %9.3fn”, x, y);
‘%d’, ‘%9.3f’ : conversion specifiers
‘d’, ‘f’:conversion characters
The output:
Value x = 20 and value y = –16.789
- blank space (9 spaces)
PSK, NSN, DK, VK – CS&E, IIT M
63
64. General form
General conversion specifier: %w.p c
w : total width of the field,
p : precision (digits after decimal point)
c : conversion character
Conversion Characters:
d - signed decimal integer
u - unsigned decimal integer
o - unsigned octal value
x - unsigned hexadecimal value
f - real decimal in fractional notation
e - real decimal in exponent form
PSK, NSN, DK, VK – CS&E, IIT M
optional
64
65. Input Statement
scanf(format-string, &var1, &var2, …, &varn);
Format String:
types of the data items to be stored in var1 etc
enclosed in double quotes
Example: scanf(“%d%f ”, &marks, &aveMarks );
data line : 16 14.75
scanf skips spaces and scans more than one line
to read the specified number of values
PSK, NSN, DK, VK – CS&E, IIT M
65
66. Conversion Specifiers for “scanf”
d
u
o
x
f
e
c
s
-
read a signed decimal integer
read an unsigned decimal integer
read an unsigned octal value
read an unsigned hexadecimal value
read a real decimal in fractional notation
read a real decimal in exponent form
read a single character
read a string of characters
PSK, NSN, DK, VK – CS&E, IIT M
66
68. Quadratic (continued)
(use vi to create files)
printf(“2nd coefficient a – “);
scanf(“%f”, &coeff_2);
printf(“3rd coefficient a – “);
scanf(“%f”, &coeff_3);
/* printf and scanf are input-output functions*/
discrim = pow(coeff_2,2) – 4* coeff_1 * coeff_3;
/* pow and sqrt are math functions */
denom = 2*coeff_1;
root_1 = (-b + sqrt(discrim))/denom;
root_2 = (-b – sqrt(discrim))/denom;
PSK, NSN, DK, VK – CS&E, IIT M
b2 – 4ac
68
69. Finally
(see http://www.gnu.org)
printf(“the roots were %f %f n”, root_1, root_2);
}
Exercise:
Modify the program so that the quadratic is also
output.
Summary: Variables are modified as the program
runs.
PSK, NSN, DK, VK – CS&E, IIT M
69
70. Problem Solving withVariables
• Write a program that will take two degree 5
polynomials as input and print out their product.
• ISSUES - How does one specify the inputs the
program?
• Indeed, what are the inputs? – coefficients from
each polynomial. Six from each.
• We need 12 Input variables.
• Similarly we need 12 Output variables
PSK, NSN, DK, VK – CS&E, IIT M
70
71. Another exercise (www.howstuffworks.com)
• Write a program that takes as input 5 digit
numbers and prints them out in English.
• Example: 512 – Five Hundred and Twelve
Solve the problem first, identify input variables,
Output variables, intermediate variables.
What values are taken by the intermediate
variables, how they are calculated from input
values, and output variables.
PSK, NSN, DK, VK – CS&E, IIT M
71
72. Decisions with Variables
• If b^2 – 4ac negative, then we should report that
the quadratic has no real roots.
• This displays the need for taking logical
decisions during problem solving.
• The if-else programming construct provides the
facility to make logical decisions.
• Rules for usage – otherwise called syntax are
if (condition is true){ evaluate this part }
else {evaluate this part}
PSK, NSN, DK, VK – CS&E, IIT M
72
73. Conditions
• They are specified using relational and equality
operators
• Relational - >, <, >=, <=
• Equality ==, !=
• Usage : for a,b values or variables a > b, a < b,
a >= b, a <= b, a == b, a != b.
• A condition is satisfied or met, if the relational
operator, or equality is satisfied.
• For a = 3, and b = 5, a < b, a <= b, and a != b are
met.
PSK, NSN, DK, VK – CS&E, IIT M
73
74. Completing the program
if (discrim < 0)
{
printf(“no real roots, only complexn”);
exit(1);
Terminates execution and
returns argument (1)
}
else
{root_1 = (-coeff_1 + sqrt(discrim))/denom;
root_2 = (-coeff_2 - sqrt(discrim))/denom;
}
PSK, NSN, DK, VK – CS&E, IIT M
74
75. Statements
Statement: a logical unit of instruction/command
Program : declarations and one or more statements
assignment statement
selection statement
repetitive statements
function calls etc.
All statements are terminated by semicolon ( ; )
Note: In C, semi-colon is a statement terminator
rather than a separator!
PSK, NSN, DK, VK – CS&E, IIT M
75
76. Assignment statement
General Form:
variable “ = ” expression | constant “;”
The declared type of the variable : should match
the type of the result of expression/constant
Multiple Assignment:
var1 = var2 = var3 = expression;
var1 = (var2 = (var3 = expression));
Assignment operator associates right-to-left.
PSK, NSN, DK, VK – CS&E, IIT M
76
77. Compound Statements
A group of declarations and statements collected
into a single logical unit surrounded by braces
– a block or a compound statement
“scope” of the variable declarations
- part of the program where they are applicable
- the compound statement
– variables come into existence just after decl.,
– continue to exist till end of the block.
– unrelated to variables of the same name outside the
block
– block-structured fashion
PSK, NSN, DK, VK – CS&E, IIT M
77
78. An Example
{ int i, j, k;
i = 1; j =2; k =3;
if ( expr ) {
int i, k;
}
…
}
PSK, NSN, DK, VK – CS&E, IIT M
This i and k and the previously
declared i and k are different.
Not a good programming style.
Note: No semicolon after }
A compound statement can appear
wherever a single statement may appear
78
79. Selection Statements
Three forms
single selection:
if ( att < 75 ) grade = “W”;
Note: There is no
then reserved word
double selection:
if (marks < 40 ) passed = 0;
else passed = 1;
/* false = 0 */
/* true = 1 */
multiple selection:
switch statement - to be discussed later
PSK, NSN, DK, VK – CS&E, IIT M
79
80. If Statement
if (<expression>) <stmt1> [ else <stmt2>]
Semantics:
optional
Expression evaluates to “true”
– stmt1 will be executed
Expression evaluates to “false”
– stmt2 will be executed
Else part is optional
Expression is “true” -- stmt1 is executed
Otherwise the if statement has no effect
PSK, NSN, DK, VK – CS&E, IIT M
80
81. Grading Example
Below 50: D; 50 to 59: C ; 60 to 75: B; 75 above: A
int marks; char grade;
…
Note the semicolon
if (marks <= 50) grade = ‘D’; before else !
else if (marks <= 59) grade = ‘C’;
else if (marks <=75) grade = ‘B’;
else grade = ‘A’;
…
Unless braces are used, an else part
goes with the nearest else-less if stmt
PSK, NSN, DK, VK – CS&E, IIT M
81
82. Caution in use of “else”
if ( marks > 40)
/* WRONG */
if ( marks > 75 ) printf(“you got distinction”);
else printf(“Sorry you must repeat the course”);
/*RIGHT*/
if ( marks > 40) {
if ( marks > 75 ) printf(“you got distinction”);
}
else printf(“Sorry you must repeat the course”);
PSK, NSN, DK, VK – CS&E, IIT M
82
83. Switch Statement
A multi-way decision statement
Syntax:
switch ( expression ) {
case const-expr : statements
case const-expr : statements
…
[ default: statements ]
}
PSK, NSN, DK, VK – CS&E, IIT M
83
84. Counting Evens and Odds
int num, eCount = 0, oCount = 0;
Counts the number of
scanf (“%d”, &num);
even and odd integers
in the input.
while (num >= 0) {
Terminated by giving a
switch (num%2) {
negative number
case 0 : eCount++; break;
case 1 : oCount++; break;
}
Defensive programming !
scanf (“%d”, &num);
}
printf( “Even: %d ,Odd: %dn”, eCount, oCount);
PSK, NSN, DK, VK – CS&E, IIT M
84
85. Fall Through’s
Switch Statement:
Execution starts at the matching case
And falls through the following case statements
Unless prevented explicitly by break statement
Useful for specifying one action for several
cases
Break Statement:
control passes to the first statement after switch
A feature requiring exercise of caution
PSK, NSN, DK, VK – CS&E, IIT M
85
86. Repetitive Statements
A very important type of statement
iterating or repeating a set of operations
- a very common requirement in algorithms
C offers three iterative constructs
the for construct
the while … construct
the do … while construct
PSK, NSN, DK, VK – CS&E, IIT M
86
87. Programming problems
• Write a program to check if a given number is
prime. (can this be done without using a logical
decision?)
• Write a program to count the number of digits in
a given number. Your answer should contain
two parts, number of digits before and after the
decimal. (can you do this only with assignments
to variables, and decisions?)
PSK, NSN, DK, VK – CS&E, IIT M
87
88. Exercise in using printf
(try banner word)
Write a program that takes a keystroke as input, and
displays the corresponding character in large using *.
Use this program to display words and sentences.
This is an assignment to be Graded by the TAs. Will
be evaluated before quiz2.
Tips: Find out the options with printf: how to move the
cursor to a predefined point.
How do you distinguish one keystroke from the other?
Find out about ASCII codes.
Explore procedures/subroutines/functions
(more will be taught about this later)
PSK, NSN, DK, VK – CS&E, IIT M
88
89. The while construct
General form:
while ( <expr> ) <statement>
Semantics:
repeat: Evaluate the “expr”.
If the “expr” is true
execute the “statement”
else exit the loop.
Obviously the “expr” must be modified in the loop!
PSK, NSN, DK, VK – CS&E, IIT M
89
90. Repetition Structure - While
Syntax – while (condition is true){ evaluate this piece of
code}
Print powers of 2 till 2N
#include<stdio.h>
#include<math.h>
main()
{ int n, counter, value;
printf(“ value for n – “);
scanf(“%d”, &n);
counter = 0;
value = 1;
contd..
PSK, NSN, DK, VK – CS&E, IIT M
90
91. Program using while
counter = 0;
/*repeated*/
value = 1;
/*repeated*/
printf(“current value is %d n”, value);
while (counter <= n)
{value = 2 * value;
printf(“current value is %d n”, value);
counter = counter + 1;
}
}
Exercise: try this program and identify problems
PSK, NSN, DK, VK – CS&E, IIT M
91
92. More on Loops
• Two kinds – sentinel-controlled and counter
controlled.
• Counter – loop runs till counter reaches its limit.
Use it when the number of repetitions is known.
• Sentinel – loop runs till a certain condition is
encountered. Example – a n is encountered in
the input. Use it when the number of
repetitions is a property of the input and not of
the problem being solved.
PSK, NSN, DK, VK – CS&E, IIT M
92
93. For loops
Counter controlled repetitions needs –
- Initial value,
- modification of counter: +i, -i, any another at
arithmetic based modification which is based on the
problem, and
- Final value.
For repetition structure provides for the programmer to
specify all these.
Ofcourse, everything that is provided by the for can be
achieved by using while.
Use of for makes the program error free
PSK, NSN, DK, VK – CS&E, IIT M
93
94. The for construct
General form:
for ( expr1; expr2; expr3)
statement
Semantics:
evaluate “expr1” - initialization operation(s)
repeat - evaluate expression “expr2” and
if “expr2” is true
execute “statement” and “expr3”
else stop and exit the loop
PSK, NSN, DK, VK – CS&E, IIT M
94
95. Example
Replace our previous program by the following
For(counter = 0; counter <=n; counter=counter+1)
{if (counter == 0) printf(“value is %d n”,1);
else
{value = 2 * value;
printf(value is %d n”, value);
}
}
Observe: a mistake in the earlier program is gone.
PSK, NSN, DK, VK – CS&E, IIT M
95
96. Simple example of for statement
Compute the sum of the first 20 odd numbers
int i, j, sum;
Set j to the first odd number
sum = 0;
i : Loop control variable
j = 1;
Termination condition
for ( i = 1; i <= 20; i++)
{ sum += j;
Increment sum by the ith odd number
j += 2;
Set j to the next odd number
}
The for construct expr1, expr2, expr3
-- involving the loop control variable only
PSK, NSN, DK, VK – CS&E, IIT M
96
97. Calculating the compound interest
Principal:1000/-; rate of interest: 5% (p.a); period: 10 yrs
#include <stdio.h>
#include <math.h>
Character string
main( ) {
int year; double amount, principal = 1000.0, rate = .05;
printf(“%4s%21sn”, “year”, “Amount in the deposit”);
for (year = 1; year < = 10; year++) {
amount = principal * pow(1.0 + rate, year);
printf(“%4d%21.2fn”, year, amount);
}
}
PSK, NSN, DK, VK – CS&E, IIT M
97
98. Example for while construct
Print the reverse of a given integer:
234 → 432
Method: Till the number becomes a zero,
extract the last digit
- number modulo 10
make it the next digit of the result
- multiply the current result by 10 and
add the new digit
PSK, NSN, DK, VK – CS&E, IIT M
98
99. An Example
x is the given number
y is the number being computed
y=0
y = 0*10 + 2 = 2
y = 2*10 + 4 = 24
y = 24*10 + 3 = 243
y = 243*10 + 6 = 2436
y = 2436*10 + 5 = 24365
PSK, NSN, DK, VK – CS&E, IIT M
x = 56342
x = 5634
x = 563
x = 56
x=5
x=0
Termnation condition:
Stop when x becomes zero
99
100. Reversing a number
main( ){
int x = 0; int y = 0;
printf("input an integer :n");
scanf("%d", &x);
while(x > 0){
y = 10*y + ( x % 10 );
Remember integer division
x = (x / 10);
truncates the quotient
}
printf("The reversed number is %d n", y);
}
PSK, NSN, DK, VK – CS&E, IIT M
100
101. Perfect number detection
Perfect : sum of proper divisors add up to the number.
main ( ){
d<n will also do, but would
int d = 2, n, sum = 1;
do unnecessary work
scanf(“%d”, &n);
while ( d < = (n/2) ) {
if ( n % d = = 0 ) sum += d;
d++;
}
if (sum = = n)
printf (“Given number %d is perfect”, n);
else printf(“Given number %d is not perfect”, n);
}
PSK, NSN, DK, VK – CS&E, IIT M
101
102. The do while construct
for and while check termination condition before
each evaluation of the loop body
Sometimes - execute the statement and
check for condition
general form:
do < statement> while <expr>
Semantics:
execute the “statement” and check “expr”
if “expr” is true, re-execute the stmt else exit
PSK, NSN, DK, VK – CS&E, IIT M
102
103. Square root of a number
main( ) {
How do you solve the equation “x = n2” ?
int n; float prevGuess, currGuess, error, sqRoot;
scanf(“%d”, &n);
currGuess = (float) n / 2 ; error = 0.0001;
do {
prevGuess = currGuess;
currGuess = ( prevGuess + n / prevGuess) / 2;
} while (fabs (prevGuess – currGuess) > error);
sqRoot = currGuess; printf(“%f”, sqRoot);
}
PSK, NSN, DK, VK – CS&E, IIT M
103
104. Newton–Raphson method
Here, f ' denotes the derivative of the
function f. Then by simple algebra
we can derive
From
http://en.wikipedia.org/wiki/Newton's_method
PSK, NSN, DK, VK – CS&E, IIT M
104
105. Sequence and Selection Structures
t
If Structure
f
Single Entry
Single Exit
f
Sequence
Structure
PSK, NSN, DK, VK – CS&E, IIT M
t
If/Else Structure
105
107. Structured Programming
To produce program that are
– easier to develop, understand, test, modify
– easier to get correctness proof
Rules
1 Begin with the “simplest flowchart”.
2 Any action box can be replaced by two action boxes
in sequence.
3 Any action box can be replaced by any elementary
structures (sequence, if, if/else, switch, while,
do/while or for ).
4 Rules 2 and 3 can be applied as many times as
required and in any order.
PSK, NSN, DK, VK – CS&E, IIT M
107
109. exercises
Write a program that reads in the entries of a 3 by
3 matrix, and prints it out in the form of a
matrix. The entries could be floating point
entries too.
Write a program that reads in orders of two
matrices and decides whether two such matrices
can be multiplied. Print out the decision.
Write a program that reads in two matrices, and
multiplies them. Your output should be the two
matrices and the resulting product matrix.
PSK, NSN, DK, VK – CS&E, IIT M
109
110. Switch Selection Structure
In place of the else if for a multiway selection
Syntax – if (condition_1){execute these}
else if (condition_2) {execute these}
else if (condition_3) {execute these}
and so on…..
Switch replaces else if for a very special case
Syntax – switch(expression){
case const-expr: statements
case const-expr: statements
PSK, NSN, DK, VK – CS&E, IIT M
110
111. Example(kernighan & ritchie, p.59)
#include<stdio.h>
An array of ten integers
main()
{ int c, i, nwhite, nother, ndigit[10];
nwhite = nother = 0;
for(i=0;i<10;i++) ndigit[i]=0;
while((c = getchar()) ! = EOF){
switch(c){
case’0’:case’1’:case’2’:case’3’:case’4’:case’5’:
case’6’:case’7’:case’8’:case’9’: ndigit[c-’0’]++;
break;
PSK, NSN, DK, VK – CS&E, IIT M
111
113. Break and Continue
break breaks out of the innermost loop or switch
statement in which it occurs
continue starts the next iteration of the loop in
which it occurs.
More on this later.
PSK, NSN, DK, VK – CS&E, IIT M
113
114. More Exercises
Sort an array of numbers into ascending order.
Assuming that arrays are expensive, your
program should use only one array: read in the
values into an array, sort in place, and print out
the array.
Matrix Sorting – The input is a matrix. Identify a
sequence of column interchanges such that in
the resulting matrix the rows are all sorted in
ascending order. Can every matrix be sorted?
PSK, NSN, DK, VK – CS&E, IIT M
114
115. Exercise – week starting Feb 5
Read a text file and report the following,
1. The total number of non-white characters
2. The total number of words
3. The average length of a word
4. The mode length of a word
5. The total number of lines
6. The average length of a line
7. The length of the longest line
Any assumptions your program makes must be stated
in the comments. What if lines are logical ending with
appropriate punctuation?
PSK, NSN, DK, VK – CS&E, IIT M
115
116. An Array
• A data structure containing items of
same data type
• Declaration: array name, storage reservation
int marks[7] = {22,15,75,56,10,33,45};
- a contiguous group of memory locations
named “marks” for holding 7 integer items
- elements/components - variables
marks[0], marks[1], … , marks[6]
marks[i] i - position / subscript (0 ≤ i ≤ 6)
- the value of marks[2] is 75
- new values can be assigned to elements
marks[3] = 36;
PSK, NSN, DK, VK – CS&E, IIT M
22
0
15
1
75
2
56
3
10
4
33
5
45
6
116
117. Example using arrays
Read five numbers into an array and compute their average
numbers[] is initialized
#include <stdio.h>
during declaration
int main( ){
int numbers[5] = {1,3,2,6,-5};
int sum = 0, i;
float average;
for ( i = 0; i < 5; i++)
sum = sum + numbers[i];
average = (float) sum/5;
printf(“The average of numbers is: %f”, average);
return 0; /* should be there in all programs */
}
PSK, NSN, DK, VK – CS&E, IIT M
117
118. Example using arrays (Read values from keyboard)
Read ten numbers into an array and compute their average
#include <stdio.h>
int main( ){
int numbers[10], sum = 0, i;
float average;
for ( i = 0; i < 10; i++)
scanf(“%d”, &numbers[i]);
for ( i = 0; i < 10; i++)
sum = sum + numbers[i];
average = (float) sum/10;
printf(“The average of numbers is: %f”, average);
return 0; /* should be there in all programs */
}
PSK, NSN, DK, VK – CS&E, IIT M
118
119. Polynomial Evaluation
Evaluate
p(x) = anxn + an-1xn-1 + an-2xn-2 + … a1x + a0
at a given x value.
Computing each term and summing up
n + (n-1) + (n-2) + … + 1 + 0 = n(n+1)/2 multiplications
and n additions
Improved Method – Horner’s Method:
p(x) = a0 + x(a1 + x(a2 + x(a3 + … + x(an-1 + xan))))
for instance, p(x) = 10x3 + 4x2 + 5x + 2
= 2 + x(5 + x(4 + 10x))
n multiplications and n additions – will run faster!
PSK, NSN, DK, VK – CS&E, IIT M
119
120. Program for Polynomial Evaluation
#include <stdio.h>
main( ){
int coeff[20], n, x, value, i; /*max. no. of coeff ’s is 20 : a0 to a19 */
scanf(“%d%d”, &n, &x); /*read degree and evaluation point*/
for(i = 0; i <= n; i++)
scanf(“%d”, &coeff[i]);
/* read in the coefficients */
value = coeff[n];
/* an */
for(i = (n-1); i >= 0; i--)
/* evaluate p(x) */
value = x*value + coeff[i];
printf(“The value of p(x) at x = %d is %dn”, x, value);
}
PSK, NSN, DK, VK – CS&E, IIT M
120
121. Multi-dimensional Arrays
Arrays with two or more dimensions can be defined
A[4][3]
0
1
2
0
0
2
3
2
1
2
1
0
1
1
B[2][4][3]
2
0
3
0
PSK, NSN, DK, VK – CS&E, IIT M
1
121
122. Two Dimensional Arrays
Declaration: int A[4][3] : 4 rows and 3 columns, 4 × 3 array
Elements: A[i][j] - element in row i and column j of array A
A[4][3]
0
1
2
0
1
2
3
PSK, NSN, DK, VK – CS&E, IIT M
Note: rows/columns numbered from 0
Storage: row-major ordering
elements of row 0,
elements of row 1, etc
Initialization:
int A[4][3]={{4,5,6},{0,3,5},{1,7,8},{ 2,0,1}};
122
124. Matrix Operations
An m-by-n matrix: M: m rows and n columns
Rows : 1, 2, … , m and Columns : 1, 2, … , n
M(i,j) : element in ith row, jth column, 1 ≤ i ≤ m, 1 ≤ j ≤ n
Array indexes in C start with 0.
We use (m+1) × (n+1) array and ignore cells (0,i),(j,0)
Programs can use natural convention - easier to
understand
Should perform :
Read; Write; Initiliazation; Multiplication;
PSK, NSN, DK, VK – CS&E, IIT M
124
125. Matrix Multiplication : Outline
main(){
1. declare all variables required
2. read in Matrix A
3. read in Matrix B
4. check if A and B are compatible to be multiplied
5. initialize Matrix C to have zeroes to begin with
6. multiply A and B to give C
7. print Matrix C
}
Of course, all the steps above have to
follow C language’s syntax rules
PSK, NSN, DK, VK – CS&E, IIT M
125
126. Using Matrix Operations : Read a Matrix
main(){
int a[11][11], b[11][11], c[11][11]; / *max size 10 by 10 */
int i,j,k;
int aRows, aCols, bRows, bCols, cRows, cCols;
scanf("%d%d", &aRows, &aCols);
for(int i = 1; i <= aRows; i++)
for(int j = 1; j <= aCols; j++)
scanf("%d", &a[i][j]);
/*continued on next slide */
PSK, NSN, DK, VK – CS&E, IIT M
126
127. Read the other Matrix; Initialize the product
scanf("%d%d", &bRows, &bCols);
for(i = 1; i <= bRows; i++)
for(j = 1; j <= bCols; j++)
Remember
scanf("%d", &b[i][j]);
bRows must
equal aCols
c is a aRows x bCols matrix
/* initialize entries in Matrix c to 0 */
for(i = 1; i <= aRows; i++)
for(j = 1; j <= bCols; j++)
c[i][j] = 0;
/*continued on next slide */
PSK, NSN, DK, VK – CS&E, IIT M
127
129. Multiply Matrices and Print the Result
/* multiply both the matrices and store in matrix c */
for(i =1; i <= aRows; i++)
for(j = 1; j <= bCols; j++)
for(k = 1; k <= aCols; k++)
c[i][j] += a[i][k]*b[k][j];
/* print matrix c */
for(i = 1; i <= aRows; i++){
for(j = 1; j <= bCols; j++) /* print a row */
printf("%d ", c[i][j]); /* notice missing n */
printf("n");
/* print a newline at the end a row */
}
}
/* End of main program */
PSK, NSN, DK, VK – CS&E, IIT M
129
130. Points to Ponder
• Some repetition in the program
– Reading in matrix A seems to be similar to reading in
matrix B
• Except for changes in the number of rows and columns
• You will learn how to write functions in C later
– Functions are written to avoid repeated actions
– Example C program would look like
readMat(A, aRows, aCols);
readMat(B, bRows, bCols);
– Function readMat( ) must perform the operations
desired
PSK, NSN, DK, VK – CS&E, IIT M
130
131. Data, Types, Sizes,Values
• int, char, float, double
• char – single byte, capable of holding one
character
• Integer Qualifiers – short and long
•
short int – 16 bits, long int – 32 bits
• Compiler dependent, based on the underlying
hardware – int is atleast 16 bits, short is atleast
16 bits, long is atleast 32 bits, and int is no
larger than long, and atleast as long as short
PSK, NSN, DK, VK – CS&E, IIT M
131
132. char, signed and unsigned
• Qualifier signed or unsigned can be applied to
int or char
• Unsigned numbers are non-negative
• Signed char holds numbers between –128 and
127. Whether char is signed or unsigned
depends on the system. Find out on your
system. Print integers between 0 to 255 as
characters, and integers between –128 to 127 on
your system.
PSK, NSN, DK, VK – CS&E, IIT M
132
134. Binary, Octal and Hexadecimal
The internal representation of binary, octal, and
hexadecimal numbers is similar
Octal - 2
7
3
2
5
6
0
6
Binary - 010111011010101110000110
Hexadecimal -
PSK, NSN, DK, VK – CS&E, IIT M
5
5
13
D
10 11 8
A B 8
6
6
134
135. A funny infinite loop - arithmetic
This program of mine, ran into an infinite loop. I only
wanted to find which numbers corresponded to which
characters, the significance of signed and unsigned
characters, basically relationship between which
integers can be printed as characters we recognize.
Why did the infinite loop happen, how to avoid it?
#include<stdio.h>
Print it as a
Print it as a
main()
character
decimal number
{char c;
for(c=-128; c <= 127; c++) printf(“%d -- %c n”, c, c);
}
PSK, NSN, DK, VK – CS&E, IIT M
Try omitting one parameter…
135
136. Float and Double
• Two types, one for single-precision arithmetic,
and the other for double precision arithmetic
• Long double is used for extended-precision
arithmetic.
• The size of floating pointing objects are
implementation defined.
PSK, NSN, DK, VK – CS&E, IIT M
136
137. Variable Initialization
• Variables may be initialized either at the time of
declaration, for example,
#define MAXLINE 200
char esc = ‘’;
int i =0;
int limit = MAXLINE + 1;
float eps = 1.0e-5
• Or they may be assigned value by assignment
statements in the program
• Otherwise they contain some random garbage
values
PSK, NSN, DK, VK – CS&E, IIT M
137
138. Constants
• At run time, each variable holds a constant,
which changes from time to time!!!!!
1234 is of type int
123456789L is a long constant
123456789ul is an unsigned long constant
123.4 is a floating point constant, so is 1e-2 which
denotes .01. Their type is double. If suffixed by
an f, or by l, the type is float or long double,
respectively
PSK, NSN, DK, VK – CS&E, IIT M
138
139. Overflow in integers…
#include <stdio.h>
int main() {
int i = 2147483647;
unsigned int j = 4294967295;
printf("%d %d %dn", i, i+1, i+2);
printf("%u %u %un", j, j+1, j+2);
return 0;
}
Here is the result for some system:
2147483647 -2147483648 -2147483647
4294967295 0 1
PSK, NSN, DK, VK – CS&E, IIT M
139
140. 32 bit numbers
The unsigned 32 bit integers vary from
-2147483648 to 2147483647
The signed 32 bit integers vary from
0 to 4294967295
Internally they are the 4294967296 (or 232)
different permutations that 32 bits can
represent. Beyond this number it starts all
over again.
PSK, NSN, DK, VK – CS&E, IIT M
140
141. Printing directives
#include <stdio.h> int main() {
unsigned int un = 3000000000;
/* system with 32-bit int */
printf("un = %u and not %dn", un, un);
return 0; }
un = 3000000000 and not -1294967296
Both have the same
internal representation
PSK, NSN, DK, VK – CS&E, IIT M
141
142. Printing directives
#include <stdio.h> int main() {
short end = 200;
/* and 16-bit short */
printf("end = %hd and %dn", end, end);
return 0; }
short decimal
end = 200 and 200
Printing a short decimal as
a normal is okay
PSK, NSN, DK, VK – CS&E, IIT M
142
143. Printing directives
#include <stdio.h> int main() {
long big = 65537;
printf("big = %ld and not %hdn", big, big);
return 0; }
big = 65537 and not 1
When the value 65537 is written in binary format as a 32-bit
number, it looks like 00000000000000010000000000000001.
Using the %hd specifier persuaded printf() to look at just the last
16 bits; therefore, it displayed the value as 1.
PSK, NSN, DK, VK – CS&E, IIT M
143
144. Printing directives
#include <stdio.h> int main() {
long long verybig = 12345678908642;
printf("verybig= %lld and not %ldn", verybig,
verybig);
64 bits
Truncated 32 bits
return 0; }
verybig= 12345678908642 and not 1942899938
PSK, NSN, DK, VK – CS&E, IIT M
144
145. Character Constants …
• …are integers, written as one character within
single quotes. Example – ‘a’, ‘x’, ‘1’, ‘2’ etc.
• The value of a character constant is the numeric
value of the character in the machine’s character
set. For example, ‘1’ has the value 49 in the
ASCII character set. That is, number 49,
interpreted as a character code stands for ‘1’
• Character constants can participate in
arithmetic. What does ‘1’+’2’ hold? (not ‘3’!)
Understand this distinction. Character
arithmetic is used mainly for comparisons.
PSK, NSN, DK, VK – CS&E, IIT M
145
146. Characters – escape sequences
a
b
f
n
r
t
v
alert (bell)
backspace
formfeed
newline
carriage return
horizontal tab
vertical tab
PSK, NSN, DK, VK – CS&E, IIT M
?
’
”
ooo
xhh
backslash
question mark
single quote
double quote
octal number
hexadecimal
Non-printable characters
146
147. More Constants
Constant numbers, Constant characters, and now
Constant Expressions – Expressions all of whose
operands are constants.
Therefore, these can be evaluated at compile time.
Examples:
#define No_of_Rows 100
#define No_of_Colos 100
#define No_of_Melts No_of_Rows * No_of_Colos
#define is preprocessor directive. Recall: #include
PSK, NSN, DK, VK – CS&E, IIT M
147
148. Enumerated Constants
• enum boolean {No, Yes}
By default enum
type begin with 0
– defines two constants No = 0, and Yes = 1.
• enum months {jan = 1, feb, march, april, may,
jun, jul, aug, sep, oct, nov, dec}
– when a value is explicitly specified (jan=1) then it
starts counting from there
• enum escapes {BELL = ‘a’, BACKSPACE =
‘b’, TAB = ‘t’, NEWLINE =‘n’}
– more than one value can be specified
PSK, NSN, DK, VK – CS&E, IIT M
148
149. Enum and #define
• Better than #define, the constant values are
generated for us.
• Values from 0 on wards unless specified
• Not all values need to be specified
• If some values are not specified, they are obtained by
increments from the last specified value
• Variables of enum type may be declared, but the
compilers need not check that what you store is a valid
value for enumeration
PSK, NSN, DK, VK – CS&E, IIT M
149
150. Strings
A string is a array of characters terminated by the
null character, ‘0’.
A string is written in double quotes.
Example: “This is a string”.
‘This is rejected by the C Compiler’
Anything within single quotes gets a number
associated with it
“” – empty string
Exercise : understand the difference between ‘x’
and “x”.
PSK, NSN, DK, VK – CS&E, IIT M
150
151. Declaring Constants
The qualifier const applied to a declaration
specifies that the value will not be changed.
const int j = 25; /* j is a constant through out the
program */
Response to modifying j depends on the system.
Typically, a warning message is issued while
compilation.
const char mesg[] = “how are you?”;
The character array mesg is declared as a constant
which will store “how are you?”
PSK, NSN, DK, VK – CS&E, IIT M
151
152. Assignment and Arithmetic Rules
• Basic data types, numbers and characters can be
assigned to their corresponding variables.
Example: char c = ‘a’; char no = ‘1’; int j = 25;
Arrays cannot participate in assignments and
arithmetic
Char mesg[] = “hello”; is a valid declaration
Int numbers[5] = {0,1,2,3,4}; is a valid declaration
But an assignment in the program is a syntax
error.
PSK, NSN, DK, VK – CS&E, IIT M
152
153. Functions to handle strings
Strings being a non basic data type, in other words
Constructed data type, require functions to handle.
Typical functions are:
a. Length of a string.
b. Are two strings equal?
c. Does a given pattern occur as a substring?
d. Concatenate two strings and return the result
These are exercises to gain programming
knowledge. But use standard functions
provided with string.h
PSK, NSN, DK, VK – CS&E, IIT M
153
154. Recap
•
•
•
•
Variables
Assignments
relational operators (comparisons)
Selection and repetition constructs: control
structures
• Data types and their limitations
• Arrays – arrayname[n], single dimensional array
Arrayname[m][n] – 2D array, arrayname[i][j] gives the
element in the i-th row and j-th coloumn
PSK, NSN, DK, VK – CS&E, IIT M
154
155. Logical Operators
• Recall relational operators {<=, <, >, >=} to compare
values
• && and ||
• Called boolean and, boolean or
• Expressions involving these as operations take boolean values, and
their operands also take boolean values.
• Called truth values also.
• E1 && E2 is true if and only if both E1 and E2 are true
• E1 || E2 is true if and only if either E1 or E2 or both are
• Precedence of && is higher than ||, and both are lower
than relational or equality operators
PSK, NSN, DK, VK – CS&E, IIT M
155
156. How to use these in a program
• They are used when composite conditions are to
be tested in decision statements.
– For(I=0;I < lim – 1 && (c = getchar()) != ‘n’ && c !=EOF; I++) s[I] = c;
• The loop is executed as long as the test
conditions is true
• Which is while all the test conditions are true
• The loop is exited when the test condition
becomes false
• Which is when one of the test conditions becomes false
• For example when an enter is read from keyboard
PSK, NSN, DK, VK – CS&E, IIT M
156
157. Exercise
• Write a program which will exit when a certain
number of occurences of any keystroke is read.
• You need arrays
• Loops
• Loops with logical operations and so on.
PSK, NSN, DK, VK – CS&E, IIT M
157
158. Operators
• Increment operator : effect is to increment value
of a variable
• x = j++ - x gets the value of j, and then j is incremented
• x = ++j - j is incremented first, then assigned to x
• Decrement operators – decrements values
• x = j-- - x gets the value of j, then j is decremented by 1
• x = --j – j is first decremented, and then assigned to x
• Assignment operator short cut
• E1 op= E2 is equivalent to the assignment E1 = E1 op E2
• Once you learn it, your code is concise
• Matter of taste
PSK, NSN, DK, VK – CS&E, IIT M
158
159. Functions = outsourcing
• Break large computing tasks into small ones
• Helps you to build on what others have done
• You and others write functions
• When you want to build a program, find out how to use
the function and use it.
• Use standard functions provided by the library.
• You are hidden from the implementation
• Example – you don’t have to worry about how pow(m,n)
is implemented
• As engineers from different disciplines you will
use and develop different set of functions
PSK, NSN, DK, VK – CS&E, IIT M
159
160. Modular Programming
Subprograms
functions in C, C++, procedures and functions in Pascal
facilitate modular programming
Overall task is divided into modules
Each module - a collection of subprograms
a subprogram may be invoked at several points
A commonly used computation
hiding the implementation
incorporating changes
easier
PSK, NSN, DK, VK – CS&E, IIT M
160
161. Example of function sets
• String manipulation
• Mathematical
• Finite Element Method
• Used in structural analysis by Mechanical, Civil, Aero,
etc. for stress calculations etc.
• Most function libraries cost a lot
• Business opportunity – identify functions that are useful
to you area of study, create libraries.
• Functions for use in different software.
• Say, functions for web services
PSK, NSN, DK, VK – CS&E, IIT M
161
162. Basics
• Function is a part of your program.
• It cannot be a part of any other function
• Main() is a function: it is the main function. Execution starts there or
the control flow starts there
• From there it can flow from one function to another, return after a
computation with some values, probably, and then flow on.
• Transfer of control is affected by calling a function
•
•
•
•
•
•
•
With a function call, we pass some parameters
These parameters are used within the function
A value is computed
The value is returned to the function which initiated the call
The calling function can ignore the value returned
It could use it in some other computation
A function could call itself, these are called recursive function calls
PSK, NSN, DK, VK – CS&E, IIT M
162
163. Add function to your Program
• A program was a set of variables, and
assignments to variables
• Now add function to it.
•
•
•
•
Set of variables
Some functions including main()
Communicating values to each other
Computing and returning values for each other
• Instead of one long program, we now write
structured program composed of functions
PSK, NSN, DK, VK – CS&E, IIT M
163
164. Features
• C program -- a collection of functions
– function main ( ) - mandatory - program starts here.
• C is not a block structured language
– a function can not be defined inside another function
– only variables can be defined in functions / blocks
• Variables can be defined outside of all functions
– global variables - accessible to all functions
– a means of sharing data between functions - caution
• Recursion is possible
– a function can call itself - directly or indirectly
PSK, NSN, DK, VK – CS&E, IIT M
164
166. Function Definition in C
return-type function-name (argument declarations)
{ variable/constant declarations and
statements }
No function
declarations here!
Arguments or parameters:
the means of giving input to the function
type and name of arguments are declared
names are formal - local to the function
Return Value: for giving the output value
return ( expression ); -- optional
Matching the
number and type
of arguments
Invoking a function: funct-name(exp1,exp2,…,expn)
PSK, NSN, DK, VK – CS&E, IIT M
166
167. Function Prototype
• defines
– the number of parameters, type of each parameter,
– type of the return value of a function
• used by the compiler to check the usage
– prevents execution-time errors
• function prototype of power function
– int power ( int, int );
– no need for naming the parameters
• function prototypes - given in the beginning
PSK, NSN, DK, VK – CS&E, IIT M
167
168. Power Function
#include <stdio.h>
function prototype
int power (int, int);
-- Computes the nth
power of base.
main () {
for ( int i = 0; i < 20; i ++ )
printf(“%d %d %dn”, i, power(3,i), power(-4,i);}
int power (int base, int n) {
int i, p = 1;
Invocation with
arguments
for ( i = 1; i <= n ; i ++) A block
p = p ∗ base;
return p;
}
PSK, NSN, DK, VK – CS&E, IIT M
168
169. Calling Power Function with i=3
printf(“%d %d %dn”, i, power(3,i), power(-4,i);}
-64
27
int power (int base, int n) {
int i, p = 1;
for ( i = 1; i <= n ; i ++)
p = p ∗ base;
return p;
}
PSK, NSN, DK, VK – CS&E, IIT M
int power (int base, int n) {
int i, p = 1;
for ( i = 1; i <= n ; i ++)
p = p ∗ base;
return p;
}
169
170. More on Functions
• To write a program
• You could create one file with all the functions
• You could/are encouraged to identify the different
modules and write the functions for each module in a
different file
• Each module will have a separate associated header file
with the variable declaration global to that module
• You could compile each module separately and a .o file
will be created
• You can then cc the differnet .o files and get an a.out file
• This helps you to debug each module separately
PSK, NSN, DK, VK – CS&E, IIT M
170
171. Running with less memory
• Functions
• Provided to break up our problem into more basic units
• Control flow – flows from function to function, saving the
current context, changing contexts, then returning…..
• Helps the program to run with lesser memory, but slower
than in the case of a long big program
• The issue now with data associated with other
functions.
• Typically functions communicate using the
arguments and return values
PSK, NSN, DK, VK – CS&E, IIT M
171
172. Call by Value
In C, function arguments are passed “by value”
– values of the arguments given to the called function
in temporary variables rather than the originals
– the modifications to the parameter variables do not
affect the variables in the calling function
“Call by reference”
– variables are passed by reference
• subject to modification by the function
– achieved by passing the “address of” variables
PSK, NSN, DK, VK – CS&E, IIT M
172
173. Call by Value - an example
main( ) {
Function prototype
int p = 1, q = 2, r = 3, s;
int test(int, int, int);
Function call
…;
s = test (p, q, r); … /* s is assigned 9 */
}
/* p,q,r don’t change, only their copies do */
int test( int a, int b, int c){
a ++; b ++; c ++;
return (a + b + c);
}
PSK, NSN, DK, VK – CS&E, IIT M
Function definition
173
174. Call by Reference
#include <stdio.h>
void quoRem(int, int, int*, int*);
main(){
int x, y, quo, rem;
scanf(“%d%d”, &x, &y);
quoRem(x, y, &quo, &rem);
printf(“%d %d”, quo , rem);
}
/*pointers*/
Passing
addresses
Does not return
anything
void quoRem(int num, int den, int* quoAdr, int* remAdr){
*quoAdr = num / den; *remAdr = num % den;
}
PSK, NSN, DK, VK – CS&E, IIT M
174
175. Recursive Function Example
int power (int num, int exp) {
int p;
if (exp = = 1) return num;
p = power(num, exp/2);
if (exp % 2 = = 0) return p*p;
else return p*p*num;
}
The base case exp = 1
Guarantees termination
power (3, 13)
36*36*3 = 729*729*3 = 1594323
power (3, 6)
33*33 = 27*27 = 729
power(3,3)
31*31*3 = 27
power(3,1)
= 3
PSK, NSN, DK, VK – CS&E, IIT M
175
176. Factorial (n)
• n! = 1 * 2 * 3 * .... * (n-2) * (n-1) * n
Iterative version
int fact(int n)
{
int i; int result;
result = 1;
for (i = 1; i <= n; i++)
result = result * i;
return result;
}
PSK, NSN, DK, VK – CS&E, IIT M
In practice int may
not be enough!
176
177. Factorial (n) – recursive program
fact(n) = n*fact(n-1)
int fact(int n)
{
if (n == 1) return 1;
return n * fact(n - 1);
}
• Shorter, simpler to understand
• Uses fewer variables
• Machine has to do more work running this one!
PSK, NSN, DK, VK – CS&E, IIT M
177
178. Pending computations
• In this recursive version the calling
version still has pending work after
it gets the return value.
int fact(int n)
{
if (n == 1) return 1;
return n * fact(n - 1);
}
(fact 4)
4 * (fact 3)
It needs to save
some values for
future use
3 * (fact 2)
2 * (fact 1)
1
2*1 =2
3*2 = 6
4*6 = 24
PSK, NSN, DK, VK – CS&E, IIT M
178
179. Tail recursion
int fact(n)
{ return fact_aux(n, 1); }
Auxiliary variable
int fact_aux(int n, int result)
{
if (n == 1) return result;
return fact_aux(n - 1, n * result)
}
PSK, NSN, DK, VK – CS&E, IIT M
The recursive call
is in the return
statement. The
function simply
returns what it
gets from the call
it makes. The
calling version
does not have
save any values!
179
180. scanf and getchar
• getchar() reads and returns one character
• scanf – formatted input, stores in variable
– scanf returns an integer = number of inputs it
managed to convert successfully
printf ("Input 2 numbers: ");
if (scanf("%d%d", &i, &j) == 2)
printf ("You entered %d and %dn", i, j);
else printf ("You failed to enter 2 numbersn");
from <http://cprogramming.com>
PSK, NSN, DK, VK – CS&E, IIT M
180
181. Input buffer
• Your input line is first stored in a buffer.
• If you are reading a number with scanf (%d) and
enter 1235ZZZ, scanf will read 1235 into the
variable and leave ZZZ in the buffer.
• The next read statement will get ZZZ and may
ignore the actual input!
• One may need to write a statement to clear the
buffer…
while (getchar() != 'n');
This reads and ignores input till the end of line.
PSK, NSN, DK, VK – CS&E, IIT M
181
182. Code to insist on one number only
#include <stdio.h>
int main(void) {
exit if one number
int temp;
printf ("Input your number: ");
while (scanf("%d", &temp) != 1)
{ while (getchar() != 'n');
clear buffer before
reading again
printf ("Try again: ");
}
printf ("You entered %dn", temp);
return(0); }
from <http://cprogramming.com>
PSK, NSN, DK, VK – CS&E, IIT M
182
183. Experiments with numbers1
The Collatz problem asks if iterating
always returns to 1 for positive α. The members
of the sequence produced by the Collatz problem
are sometimes known as hailstone numbers.
From Wolfram Mathworld
http://mathworld.wolfram.com/CollatzProblem.html
PSK, NSN, DK, VK – CS&E, IIT M
183
184. Hailstone numbers
• A Hailstone Sequence is generated by a simple
algorithm.
Start with an integer N. If N is even, the next
number in the sequence is N / 2. If N is odd, the
next number in the sequence is (3 * N) + 1.
• 7, 22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8,
4, 2, 1, 4, 2, 1, ... repeats
• 12, 6, 3, 10, 5, 16, 8, 4, 2, 1, 4, 2, 1 ….
• 909, 2726, 1364, 682, 341, 1024, 512, 256, 128,
64, 32, 16, 8, 4, 2, 1, 4, 2, 1…
10
PSK, NSN, DK, VK – CS&E, IIT M
2
184