CS1101 Computational Engineering

Slides:



Advertisements
Similar presentations
Lecture 2 Introduction to C Programming
Advertisements

Introduction to C Programming
Introduction to C Programming
1 ICS103 Programming in C Lecture 3: Introduction to C (2)
Differences between Java and C CS-2303, C-Term Differences between Java and C CS-2303, System Programming Concepts (Slides include materials from.
1 Lecture 2  Input-Process-Output  The Hello-world program  A Feet-to-inches program  Variables, expressions, assignments & initialization  printf()
 2007 Pearson Education, Inc. All rights reserved Introduction to C Programming.
Introduction to C Programming Overview of C Hello World program Unix environment C programming basics.
 2003 Prentice Hall, Inc. All rights reserved. 1 Machine Languages, Assembly Languages, and High-level Languages Three types of computer languages 1.Machine.
1 ICS103 Programming in C Lecture 2: Introduction to C (1)
Chapter 2 Data Types, Declarations, and Displays
Introduction to C Programming
C programming Language and Data Structure For DIT Students.
Computer Science 210 Computer Organization Introduction to C.
COMPUTER SCIENCE I C++ INTRODUCTION
Chapter 2 Getting Started in C Programming
A First Book of ANSI C Fourth Edition
UniMAP Sem2-08/09 DKT121: Fundamental of Computer Programming1 Introduction to C – Part 2.
Chapter 3 Processing and Interactive Input. 2 Assignment  The general syntax for an assignment statement is variable = operand; The operand to the right.
CNG 140 C Programming Lecture Notes 2 Processing and Interactive Input Spring 2007.
A First Book of ANSI C Fourth Edition Chapter 3 Processing and Interactive Input.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
Input, Output, and Processing
UniMAP Sem1-07/08EKT120: Computer Programming1 Week2.
Constants Numeric Constants Integer Constants Floating Point Constants Character Constants Expressions Arithmetic Operators Assignment Operators Relational.
Introduction to C Programming Chapter 2 : Data Input, Processing and Output.
C++ for Engineers and Scientists Second Edition
Gator Engineering Copyright © 2008 W. W. Norton & Company. All rights reserved. 1 Chapter 3 Formatted Input/Output.
Tokens in C  Keywords  These are reserved words of the C language. For example int, float, if, else, for, while etc.  Identifiers  An Identifier is.
UNIMAP Sem2-07/08EKT120: Computer Programming1 Week 2 – Introduction to Programming.
 2003 Prentice Hall, Inc. All rights reserved Basics of a Typical C++ Environment C++ systems –Program-development environment –Language –C++
1 Types of Programming Language (1) Three types of programming languages 1.Machine languages Strings of numbers giving machine specific instructions Example:
Introduction to Algorithmic Processes CMPSC 201C Fall 2000.
Chapter 1 slides1 What is C? A high-level language that is extremely useful for engineering computations. A computer language that has endured for almost.
From Algorithms to Programs Both are sets of instructions on how to do a task Algorithm: –talking to humans, easy to understand –in plain (English) language.
CSCE 206 Structured Programming in C
Computer Science 210 Computer Organization
Chapter 1: Introduction to computers and C++ Programming
Chapter 2 Introduction to C++ Programming
ECE Application Programming
Chapter 2 - Introduction to C Programming
Tokens in C Keywords Identifiers Constants
Revision Lecture
ICS103 Programming in C Lecture 3: Introduction to C (2)
Introduction to C Topics Compilation Using the gcc Compiler
Introduction to C Programming Language
Chapter 2 - Introduction to C Programming
Introduction to C Programming
Computer Science 210 Computer Organization
Variables In programming, we often need to have places to store data. These receptacles are called variables. They are called that because they can change.
Chapter 2 - Introduction to C Programming
Chapter 2 - Introduction to C Programming
Chapter 2 - Introduction to C Programming
A First Book of ANSI C Fourth Edition
CS111 Computer Programming
Introduction to C Programming
Introduction to C Topics Compilation Using the gcc Compiler
Lectures on Numerical Methods
Chapter 2 - Introduction to C Programming
Differences between Java and C
Lecture3.
C programming Language
Introduction to C Topics Compilation Using the gcc Compiler
Engineering Problem Solving with C++ An Object Based Approach
Chapter 2 - Introduction to C Programming
Session 1 – Introduction to Computer and Algorithm (Part 2)‏
DATA TYPES There are four basic data types associated with variables:
Introduction to C Programming
Presentation transcript:

CS1101 Computational Engineering Introduction to C Programming Language

The C Programming Language An imperative general-purpose programming 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

Origins of C Developed by Dennis M. Ritchie at Bell Labs first implemented on DEC PDP-11 in 1972 Based on two prior 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

Developing and Using a C program A C program typically goes through six phases 1. Edit: the program is created and stored on disk Emacs and vi are popular editors on Linux usually part of IDE on Windows platforms 2. Preprocess: handles preprocessor directives include other files, macro expansions etc 3. Compile: translates the program into machine language code or object code stores on disk

creates an executable image with no “holes” 5. Load: 6. Execute: Other Phases 4. Link: combines the object code of the program object code of library functions and other functions creates an executable image with no “holes” 5. Load: transfers the executable image to the memory 6. Execute: computer carries out the instructions of the program

A program is a sequence of instructions 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.

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, analyze the steps, and then code them into a programming language.

/* A first program in C */ #include <stdio.h> main( ) { Hello, World! A comment /* A first program in C */ #include <stdio.h> main( ) { printf(“Hello, World! \n”); } Library of standard input/output functions Every C program starts execution with this function. Statement terminator Escape sequence - newline Body of the function - enclosed in braces printf - a function from C Standard library stdio.h - prints a char string on the standard output

Programming Basics (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 Note: physical address changes from one run of the program to another. 9

Variables and Constants Names made up of letters, digits and ‘_’ case sensitive: classSize and classsize are different maximum size: 31 chars first character must be a letter choose meaningful and self-documenting names MAX_PILLAR_RADIUS a constant pillarRadius a variable keywords are reserved if, for, else, float, …

Assignments and Variables The value of a variable is modified due to an assignment The LHS is the variable to be modified and the RHS is the value to be assigned So RHS is evaluated first and then assignment performed E.g.: a = 1 a = c a = MAX_PILLAR_RADIUS a = a*b + d/e 11

Need to declare variables A declaration: type variablename; Variable Declaration Need to declare variables A declaration: type variablename; Types: int, float, char E.g.: int x; 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; 12

Variables need Declaration Another simple C program #include<stdio.h> main() {int int_size; int chr_size, flt_size; int_size = sizeof(int); chr_size =sizeof(char); flt_size = sizeof(float); printf(“int, char, and float use %d %d and %d bytes\n”, int_size, chr_size, flt_size); } A function from stdio.h 1 2 3 4 5 6 7 8 9 13

Type the above program using the Gedit/Vim/Emacs editor. Exercise Type the above program using the Gedit/Vim/Emacs editor. Compile it using gcc Run the a.out file If you already know C: Write a program that reads the coefficients of a quadratic and prints out its roots 14

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 15

An Addition Program #include <stdio.h> main( ) { int operand1, operand2, sum; printf(“Enter first operand\n”); scanf(“%d”, &operand1); printf(“Enter second operand\n”); scanf(“%d”, &operand2); sum = operand1 + operand2; printf(“The sum is %d \n”, sum); return 0; } Declarations, must precede use “ %d ” - conversion specifier d - decimal & - address of operand1 assignment Returning a 0 is used to signify normal termination

Total: 45 different operators in C 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 for float/double Total: 45 different operators in C

Order of Evaluation (Operator Precedence) first : parenthesized sub-expressions - innermost first second :  , / and % - left to right third : + and – - left to right a + b  c  d % e – f / g 5 1 2 3 6 4 a + ((( b  c )  d ) % e ) – (f / g ) good practice – use parentheses rather than rely on precedence rules – better readability

Precedence – Another Example Value = a * (b + c) % 5 + x / (3 + p) – r – j Evaluation order – (b + c) and (3 + p) : due to brackets * and % and / have same precedence: a*(b + c) is evaluated first, then mod 5. Also, x/(3 + p). Finally, the additions and subtractions are done from the left to right. Finally, the assignment of the RHS to LHS is done. = is the operator that violates the left to right rule 19

Relational and Logical Operators A logical variable can have two values {true, false} or {1, 0} In C: int flag // 0 is false, any non-zero value is true Operators: ! 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

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 is 4, y is 6 and n is 6 after the execution

Assignment Statement/Expression Form: variable-name = expression E.g.: total = test1Marks + test2Marks + endSemMarks; 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));

X = X op (expr) can be written as X op= expr Assignment Operators X = X op (expr) can be written as X op= expr op : +, – , , / , % E.g.: n = n + 10;  n += 10;

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

Value x = 20 and value y = –16.789 Examples - Output int x; float y; x = 20; y = – 16.7889; printf(“Value x = %d and value y = %9.3f \n”, x, y); ‘%d’, ‘%9.3f’ : conversion specifiers ‘d’, ‘f’ : conversion characters The output: Value x = 20 and value y = –16.789  - blank space (2 spaces)

Fun with Modulus operator main() { printf ("%d %d %d %d\n", 5%2, (-5)%2, 5%(-2), (-5)%(-2)); //1 -1 1 -1 printf ("%d %d %d %d\n", 5/2, (-5)/2, 5/(-2), (-5)/(-2)); // 2 -2 -2 2 } /* a / b -- quotient q, reminder r. => a = b * q + r */ x = y = z = a + b; x = (y = (z = a + b))

General conversion specifier: %w.p c w : total width of the field, 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 optional

Input Statement scanf(format-string, &var1, &var2, …, &varn); format-string: types of data items to be stored in var1, var2, 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

Conversion Specifiers for “scanf” d - read a signed decimal integer u - read an unsigned decimal integer o - read an unsigned octal value x - read an unsigned hexadecimal value f - read a real decimal in fractional notation e - read a real decimal in exponent form c - read a single character s - read a string of characters

Solving a Quadratic Equation (rm –i is safe) #include<stdio.h> #include<math.h> main() { float coeff1, coeff2, coeff3; float root1, root2, discrim, denom; printf(“Enter the 1st coefficient:”); /* prompt */ scanf(“%f ”,&coeff1); /* read and store */ printf(“Enter the 2nd coefficient:”); scanf(“%f ”, &coeff2); 30

Quadratic (continued) (use vi to create files) printf(“Enter the 3rd coefficient:”); scanf(“%f ”, &coeff3); /* Now compute the roots*/ discrim = pow(coeff2, 2) – 4*coeff1*coeff3; denom = 2*coeff1; root1 = (– coeff2 + sqrt(discrim))/denom; root2 = (– coeff2 – sqrt(discrim))/denom; printf(“the roots were %f, %f \n”, root1, root2); } b2 – 4ac 31

Exercise (see http://www.gnu.org) Modify the program so that the quadratic is also output. Summary: Variables are modified as the program runs. 32

Problem Solving withVariables Write a program that will take two degree 5 polynomials as input and print out their product. What are the inputs? Coefficients from each polynomial. Six from each. We need 12 Input variables. How many outputs are there? We need 12 Output variables 33

Another Exercise (www.howstuffworks.com) Write a program that takes as input 3 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. 34