CS1101 Computational Engineering: Introduction To C Programming Language

Download as pdf or txt
Download as pdf or txt
You are on page 1of 34

CS1101

Computational Engineering

Introduction to C Programming
Language

Course Material – SD, SB, PSK, NSN, DK, TAG – CS&E, IIT M 1
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

SD, PSK, NSN, DK, TAG – CS&E, IIT M 2


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

SD, PSK, NSN, DK, TAG – CS&E, IIT M 3


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

SD, PSK, NSN, DK, TAG – CS&E, IIT M 4


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

SD, PSK, NSN, DK, TAG – CS&E, IIT M 5


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.

SD, PSK, NSN, DK, TAG – CS&E, IIT M 6


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.

SD, PSK, NSN, DK, TAG – CS&E, IIT M 7


Hello, World!
A comment
/* A first program in C */
#include <stdio.h> Library of standard input/output
main( ) functions

{ Every C program starts


printf(“Hello, World! \n”); 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
SD, PSK, NSN, DK, TAG – CS&E, IIT M 8
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.

SD, PSK, NSN, DK, TAG – CS&E, IIT M 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, …

SD, PSK, NSN, DK, TAG – CS&E, IIT M 10


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
SD, PSK, NSN, DK, TAG – CS&E, IIT M 11
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;
SD, PSK, NSN, DK, TAG – CS&E, IIT M 12
Variables need Declaration
Another simple C program
A function
1 #include<stdio.h> from stdio.h
2 main()
3 {int int_size;
4 int chr_size, flt_size;
5 int_size = sizeof(int); chr_size =sizeof(char);
6 flt_size = sizeof(float);
7 printf(“int, char, and float use %d %d and %d bytes\n”,
8 int_size, chr_size, flt_size);
9 }

SD, PSK, NSN, DK, TAG – CS&E, IIT M 13


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

SD, PSK, NSN, DK, TAG – CS&E, IIT M 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

SD, PSK, NSN, DK, TAG – CS&E, IIT M 15


An Addition Program
#include <stdio.h>
main( ) Declarations, must precede use
{
int operand1, operand2, sum; “ %d ” - conversion
printf(“Enter first operand\n”); specifier

scanf(“%d”, &operand1); d - decimal


& - address of operand1
printf(“Enter second operand\n”);
scanf(“%d”, &operand2);
sum = operand1 + operand2; assignment
printf(“The sum is %d \n”, sum);
return 0;
Returning a 0 is used to signify
} normal termination
SD, PSK, NSN, DK, TAG – CS&E, IIT M 16
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
SD, PSK, NSN, DK, TAG – CS&E, IIT M 17
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
SD, PSK, NSN, DK, TAG – CS&E, IIT M 18
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
SD, PSK, NSN, DK, TAG – CS&E, IIT M 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
SD, PSK, NSN, DK, TAG – CS&E, IIT M 20
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

SD, PSK, NSN, DK, TAG – CS&E, IIT M 21


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));

SD, PSK, NSN, DK, TAG – CS&E, IIT M 22


Assignment Operators
• X = X op (expr) can be written as X op= expr
– op : +, – , , /,%

• E.g.: n = n + 10;  n += 10;

SD, PSK, NSN, DK, TAG – CS&E, IIT M 23


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
SD, PSK, NSN, DK, TAG – CS&E, IIT M 24
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)
SD, PSK, NSN, DK, TAG – CS&E, IIT M 25
Fun with Modulus operator

main() {
printf ("%d %d %d %d\n", 5%2, (-5)%2, 5%(-2), (-5)%(-2)); //1 -1 1 -1
x = y5/(-2),
printf ("%d %d %d %d\n", 5/2, (-5)/2, = z = a(-5)/(-2));
+ b; // 2 -2 -2 2
} x = (y = (z = a + b))

/* a / b -- quotient q, reminder r. => a = b * q + r */

SD, PSK, NSN, DK, TAG – CS&E, IIT M 26


General Form
General conversion specifier: %w.p c
w : total width of the field, optional

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
SD, PSK, NSN, DK, TAG – CS&E, IIT M 27
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
SD, PSK, NSN, DK, TAG – CS&E, IIT M 28
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

SD, PSK, NSN, DK, TAG – CS&E, IIT M 29


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);
SD, PSK, NSN, DK, TAG – CS&E, IIT M 30
Quadratic (continued) (use vi to create files)

printf(“Enter the 3rd coefficient:”);


scanf(“%f ”, &coeff3); b2 – 4ac
/* 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);
}
SD, PSK, NSN, DK, TAG – CS&E, IIT M 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.

SD, PSK, NSN, DK, TAG – CS&E, IIT M 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

SD, PSK, NSN, DK, TAG – CS&E, IIT M 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.
SD, PSK, NSN, DK, TAG – CS&E, IIT M 34

You might also like