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

C Programming Week2

The document provides an overview of the C programming language, its origins, and its significance in programming and software development. It outlines the phases of developing a C program, basic programming concepts, variable declaration, and various operators. Additionally, it includes examples of simple C programs and exercises for practical application.

Uploaded by

ABHISHEK GOUTAM
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

C Programming Week2

The document provides an overview of the C programming language, its origins, and its significance in programming and software development. It outlines the phases of developing a C program, basic programming concepts, variable declaration, and various operators. Additionally, it includes examples of simple C programs and exercises for practical application.

Uploaded by

ABHISHEK GOUTAM
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

15/09/17

The C Programming Language


• An imperative general-purpose programming
language
• Used extensively in the development of UNIX
CS1100
• Extremely effective and expressive
Introduction to Programming
• Not a “very high level” nor a “big” language
Introduction to C Programming • Has compact syntax, modern control flow and
data structures and a rich a set of operators
Madhu Mutyam
Department of Computer Science and Engineering • Extensive collections of library functions
Indian Institute of Technology Madras

Course Material – SD, SB, PSK, NSN, DK, TAG – CS&E, IIT M 1 2
SD, PSK, NSN, DK, TAG – CS&E, IIT M

Origins of C Developing and Using a C Program


• Developed by Dennis M. Ritchie at Bell Labs A C program typically goes through six phases
– first implemented on DEC PDP-11 in 1972 Turing Award
1983
• Edit: the program is created and stored on disk
• Based on two existing languages – Emacs and vi are popular editors on Linux
– Basic Combined Programming Language (BCPL) and B
language – usually part of IDE on Windows platforms
– BCPL: Martin Richards, 1967 - systems programming • Preprocess: handles preprocessor directives
– B: Ken Thomson, 1970 - early versions of UNIX – include other files, macro expansions, etc
– The C Programming Language- Kernighan, Ritchie, 1978
• Compile: translates the program
• ANSI C: a standard adopted in 1990
– into machine language code or object code
– unambiguous, machine-independent definition of C
– stores on disk
– The C Programming Language (2nd edition)- Kernighan,
Ritchie, 1988
SD, PSK, NSN, DK, TAG – CS&E, IIT M 3 SD, PSK, NSN, DK, TAG – CS&E, IIT M 4

Other Phases Programs = Solutions


• Link: combines • A program is a sequence of instructions
– the object code of the program – This is from the perspective of the machine or the
– object code of library functions and other functions compiler!
– creates an executable image with no “holes”
• Load: • A program is a (frozen) solution
– transfers the executable image to the memory – From the perspective of a human, a program is a
representation of a solution devised by the human.
• Execute: Once frozen (or written and compiled), it can be
– computer carries out the instructions of the program executed by the computer – much faster, and as many
times as you want.

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

1
15/09/17

Programming = Problem Solving Hello, World!


A comment
• Software development involves the following /* A first program in C */
– A study of the problem (requirements analysis) #include <stdio.h> Library of standard input/output
– A description of the solution (specification) main( ) functions

– Devising the solution (design) { Every C program starts


– Writing the program (coding) execution with this function.
printf(“Hello, World! \n”);
– Testing }
Statement terminator
• The critical part is the solution design. One must
work out the steps of solving the problem, Body of the function -
Escape sequence - newline

analyze the steps, and then code them into a enclosed in braces

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

Programming Basics (emacs for programs) Variables and Constants


• A variable – changes value during the execution • Names
of a program. – made up of letters, digits and ‘_’
• A variable has a name, e.g. – name, value, speed, • case sensitive: classSize and classsize are different
• maximum size: 31 chars
revsPerSec etc.
– first character must be a letter
• Always referred to by its name
– choose meaningful and self-documenting names
• Note: physical address changes from one run of • MAX_PILLAR_RADIUS a constant
the program to another. • pillarRadius a variable
– keywords are reserved
• if, for, else, float, …

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

Assignments and Variables Variable Declaration


• The value of a variable is modified due to an • Need to declare variables
assignment • A declaration: <type> variableName;
• The LHS is the variable to be modified and the • Types: int, float, char
RHS is the value to be assigned
• E.g.: int x;
• So RHS is evaluated first and then assignment
• Number of bytes assigned to a variable depends
performed on its type.
• E.g.: a = 1
• Assigning types helps write more correct
–a=c programs.
– a = MAX_PILLAR_RADIUS – Automatic type checking can catch errors like
– a = a*b + d/e integer = char+char;
SD, PSK, NSN, DK, TAG – CS&E, IIT M 11 SD, PSK, NSN, DK, TAG – CS&E, IIT M 12

2
15/09/17

Variables need Declaration Exercise


Another simple C program • Type the above program using the Emacs editor.
1 #include<stdio.h> • Compile it using cc
2 main()
{ A function • Run the a.out file
3 from stdio.h
4 int int_size;
5 int chr_size, flt_size; • If you already know C:
6 int_size = sizeof(int); chr_size =sizeof(char); • Write a program that reads the coefficients of a
7 flt_size = sizeof(float); quadratic and prints out its roots
8 printf(“int, char, and float use %d %d and %d bytes\n”,
9 int_size, chr_size, flt_size);
}
SD, PSK, NSN, DK, TAG – CS&E, IIT M 13 SD, PSK, NSN, DK, TAG – CS&E, IIT M 14

Modifying Variables (rm with –i option) An Addition Program


• Each C program is a sequence of modification of #include <stdio.h>
variable values main( ) Declarations, must precede use
{
• A modification can happen due to operations like int operand1, operand2, sum; “ %d ” - conversion
+, -, /, *, etc. printf(“Enter first operand\n”); specifier
d - decimal
• Also due to some functions provided by the scanf(“%d”, &operand1);
& - address of operand1
system like sizeof, sin, etc. printf(“Enter second operand\n”);
scanf(“%d”, &operand2);
• Also due to some functions (another part of your sum = operand1 + operand2; assignment
program) created by the programmer 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 15 SD, PSK, NSN, DK, TAG – CS&E, IIT M 16

Arithmetic Operators in C Order of Evaluation (Operator Precedence)


Four basic operators first : parenthesized sub-expressions
- innermost first
+, – , * , /
second : * , / and % - left to right
addition, subtraction, multiplication and division
applicable to integers and floating point numbers third : + and – - left to right
integer division - fractional part of result truncated
12/5 à 2, 5/9 à 0 a+b* c*d%e –f/g
5 1 2 3 6 4
modulus operator : %
x % y : gives the remainder after x is divided by y a + ((( b * c ) * d ) % e ) – (f / g )
applicable only for integers, not for float/double good practice – use parentheses rather than rely on
precedence rules – better readability
SD, PSK, NSN, DK, TAG – CS&E, IIT M 17 SD, PSK, NSN, DK, TAG – CS&E, IIT M 18

3
15/09/17

Precedence – Another Example Relational and Logical Operators


• Value = a * (b + c) % 5 + x / (3 + p) – r – j • A logical variable can have two values {true, false} or {1,
0}
• Evaluation order –
• In C: int flag // 0 is false, any non-zero value is true
– (b + c) and (3 + p) : due to brackets
• Operators:
– * and % and / have same precedence: a*(b + c) is
! unary logical negation operator
evaluated first, then mod 5. Also, x/(3 + p).
< , <= , > , >= comparison operators
– Finally, the additions and subtractions are done from
the left to right. = = , != equality and inequality
&& logical AND operator
• Finally, the assignment of the RHS to LHS is
|| logical OR operator
done.
• logical operators return true/false
– = is the operator that violates the left to right rule
• order of evaluation -- as given above
SD, PSK, NSN, DK, TAG – CS&E, IIT M 19 SD, PSK, NSN, DK, TAG – CS&E, IIT M 20

Increment and Decrement Operators Assignment Statement/Expression


• Unusual operators - prefix or postfix only to • Form: variable-name = expression;
variables – E.g.: total = test1Marks + test2Marks + endSemMarks;
++ adds 1 to its operand – int i; float x;
–– subtracts 1 from its operand i = x; fractional part of x is dropped
• n++ increments n after its use x = i; i is converted into a float
• ++n increments n before its use • Multiple assignment:
• n = 4; x = n++; y = ++n; x = y = z = a + b;
• x is 4, y is 6 and n is 6 after the execution x = (y = (z = a + b));

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

Assignment Operators Output Statement


• X = X op (expr); can be written as X op= expr; printf (format-string, var1, var2, …, varn);
– op : +, – , *, /,%
format-string indicates:
• E.g.: n = n + 10; à n += 10; 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 23 SD, PSK, NSN, DK, TAG – CS&E, IIT M 24

4
15/09/17

Examples - Output General Form


int x; float y; General conversion specifier: %w.p c
x = 20; y = – 16.7889; w : total width of the field, optional

p : precision (digits after decimal point)


printf(“Value x = %d and value y = %9.3f \n”, x, y);
c : conversion character
‘%d’, ‘%9.3f’ : conversion specifiers Conversion Characters:
‘d’, ‘f’ : conversion characters d : signed decimal integer
The output: u : unsigned decimal integer
o : unsigned octal value
Value x = 20 and value y = –16.789 x : unsigned hexadecimal value
 - blank space (9 spaces) f : real decimal in fractional notation
e : real decimal in exponent form
SD, PSK, NSN, DK, TAG – CS&E, IIT M 25 SD, PSK, NSN, DK, TAG – CS&E, IIT M 26

Input Statement Conversion Specifiers for “scanf”


scanf(format-string, &var1, &var2, …, &varn); d - read a signed decimal integer
format-string: u - read an unsigned decimal integer
types of data items to be stored in var1, var2, etc o - read an unsigned octal value
enclosed in double quotes x - read an unsigned hexadecimal value
Example: scanf(“%d%f ”, &marks, &aveMarks ); f - read a real decimal in fractional notation
data line: 16 14.75 e - read a real decimal in exponent form
scanf skips spaces and scans more than one line c - read a single character
to read the specified number of values s - read a string of characters

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

Solving a Quadratic Equation (rm –i is safe) Quadratic (continued) (use vi to create files)

#include<stdio.h> printf(“Enter the 3rd coefficient:”);


#include<math.h> scanf(“%f ”, &coeff3); b2 – 4ac
main() /* Now compute the roots*/
{ float coeff1, coeff2, coeff3; discrim = pow(coeff2, 2) – 4*coeff1*coeff3;
float root1, root2, discrim, denom; denom = 2*coeff1;
printf(“Enter the 1st coefficient:”); /* prompt */ root1 = (– coeff2 + sqrt(discrim))/denom;
scanf(“%f ”,&coeff1); /* read and store */ root2 = (– coeff2 – sqrt(discrim))/denom;
printf(“Enter the 2nd coefficient:”); printf(“the roots were %f, %f \n”, root1, root2);
scanf(“%f ”, &coeff2); }
SD, PSK, NSN, DK, TAG – CS&E, IIT M 29 SD, PSK, NSN, DK, TAG – CS&E, IIT M 30

5
15/09/17

Exercise (see http://www.gnu.org) Problem Solving withVariables


• Write a program that will take two degree 5
Modify the program so that the quadratic is also polynomials as input and print out their product.
output. • What are the inputs?
Summary: Variables are modified as the program – Coefficients from each polynomial. Six from each.
runs. – We need 12 Input variables.
• How many outputs are there?
– We need 12 Output variables

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

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

You might also like