SlideShare a Scribd company logo
1 of 86
Introduction
to
C Programming
•By: Prof. Ganesh Ingle
Session objective
History of C Language
Structure of a C program
Statements & Basic Data Types
Variables &Constants
Input & Output statements
Operators, Precedence, Expressions, Simple C programs.
SUMMARY
History of C
1960: ALGOL (ALGOrithmic Language)
1967: BCPL (Basic Combined
Programming Language)
1970: B programming language (typeless)
1972: C: BCPL plus B with types
1978: Kernighan + Ritchie standard for C
1989: ANSI standard for C
2.1 Program Structure
4
5
/*-----------------------------------------*/
/* Program chapter1_1 */
/* This program computes the */
/* distance between two points. */
#include <stdio.h>
#include <math.h>
int main(void)
{
/* Declare and initialize variables. */
double x1=1, y1=5, x2=4, y2=7,
side_1, side_2, distance;
/* Compute sides of a right triangle. */
side_1 = x2 - x1;
side_2 = y2 - y1;
distance=sqrt(side_1*side_1 + side_2*side_2);
/* Print distance. */
printf("The distance between the two "
"points is %5.2f n", distance);
return 0; /* Exit program. */
}
/*-----------------------------------------*/
Comments
Preprocessor,
standard C library
every C program must
have main function, this
one takes no parameters
and it returns int value
{  begin
Variable declarations,
initial values (if any)
Statements
must end with ;
indentation
indentation
indentation
return 0
}  end of function
Parts of a Program
#include <stdio.h>
int x;
int main () {
int y;
printf("Enter x and y: ");
scanf(&x,&y);
printf("Sum is %dn",x+y);
}
Preprocessor Directive
Global Declaration
Function
Local Declaration
Statements
C Program Structure
Preprocessor Directives
Global Declarations
Function Definitions
int main () {
}
Local Declarations
Statements
 Program defined by:
 global declarations
 function definitions
 May contain
preprocessor directives
 Always has one
function named main,
may contain others
Outline
II. Program Basics
A. Program skeleton
preprocessor directives
global declarations
functions
local declarations
statements
B. Comments and Documentation
C. Names (identifiers)
reserved words
Outline (cont)
II. Program Basics (cont)
D. Variable declarations
1. Memory allocation
2. Atomic types
void, int, float, char
E. Constants
1. literal
2. defined
3. memory
Outline (cont)
II. Program Basics (cont)
F. Formatted input/output
1. Files
2. Printf (monitor output)
a. format strings
field specifications
b. data list
3. Scanf (keyboard input)
a. format strings
b. address list
4. Prompting for Input
Preprocessor Directives
 Begin with #
 Instruct compiler to perform some
transformation to file before compiling
 Example: #include <stdio.h>
 add the header file stdio.h to this file
 .h for header file
 stdio.h defines useful input/output
functions
Declarations
 Global
 visible throughout program
 describes data used throughout program
 Local
 visible within function
 describes data used only in function
Functions
 Consists of header and body
 header: int main ()
 body: contained between { and }
 starts with location declarations
 followed by series of statements
 More than one function may be defined
 Functions are called (invoked) - more
later
Main Function
 Every program has one function main
 Header for main: int main ()
 Program is the sequence of statements
between the { } following main
 Statements are executed one at a time
from the one immediately following to
main to the one before the }
Comments
 Text between /* and */
 Used to “document” the code for the
human reader
 Ignored by compiler (not part of
program)
 Have to be careful
 comments may cover multiple lines
 ends as soon as */ encountered (so no
internal comments - /* An /* internal */
Comment Example
#include <stdio.h>
/* This comment covers
* multiple lines
* in the program.
*/
int main () /* The main header */ {
/* No local declarations */
printf(“Too many commentsn”);
} /* end of main */
Documentation
 Global - start of program, outlines
overall solution, may include structure
chart
 Module - when using separate files,
indication of what each file solves
 Function - inputs, return values, and
logic used in defining function
 Add documentation for key (tough to
understand) comments
 Names of variables - should be chosen
to be meaningful, make program
General Form
18
preprocessing directives
int main(void)
{
declarations
statements
}
 The main function contains
two types of commands:
declarations and statements
 Declarations and statements
are required to end with a
semicolon (;)
 Preprocessor directives do not
end with a semicolon
 To exit the program, use a
return 0; statement
Another Program
19
/***************************************************/
/* Program chapter1 */
/* This program computes the sum of two numbers */
#include <stdio.h>
int main(void)
{
/* Declare and initialize variables. */
double number1 = 473.91, number2 = 45.7, sum;
/* Calculate sum. */
sum = number1 + number2;
/* Print the sum. */
printf(“The sum is %5.2f n”, sum);
system("pause"); /* keep DOS window on the screen*/
return 0; /* Exit program. */
}
/****************************************************/
2.2 Constants and Variables
 What is a variable in math?
f(x) = x2+x+4
 In C,
 A variable is a memory location that holds
a value
 An identifier or variable name is used to
reference a memory location.
20
21
Memory
double x1=1,x2=7,distance;
1 = 00000001
7 = 00000111
? = 01001101
…
11
12
13
14
15
16
…
x1
x2
distance
addressname Memory - content
How many memory cells
does your computer have?
Say it says 2Gbyte memory?
1K=103 or 210 = 1024
1M=106 or 220 = 10242
1G=109 or 230 = 10243
Memory Snapshot
22
Name Addr Content
x1 1
y1 5
x2 4
y2 7
side_1 ?
side_2 ?
distance ?
Rules for selecting a valid
identifier (variable name)
 Must begin with an alphabetic character or
underscore (e.g., abcABC_)
 May contain only letters, digits and
underscore (no special characters ^%@)
 Case sensitive (AbC, aBc are different)
 Cannot use C keywords as identifiers (e.g.,
if, case, while)
23
Are the following valid identifiers?
 distance
 1x
 x_1
24
rate%
x_sum
switch
initial_time
DisTaNce
X&Y
C Numeric Data Types
25
Example Data-Type Limits
26
C Character Data Type: char
27
In memory, everything is stored as binary value, which can be interpreted
as char or integer. Examples of ASCII Codes
char result =‘Y’;
28
Memory
How to represent ‘a’ ?
char My_letter=‘a’;
int My_number = 97
Always we have 1’s and 0’s
in the memory. It depends
on how you look at it?
For example, 01100001 is
97 if you look at it as int, or
‘a’ if you look at it as char
‘3’ is not the same as 3
How to represent 2.5?
‘a’= 01100001
97 = 01100001
? = 01001101
0
1
2
3
4
5
6
…
My_number
addressname Memory - content
My_letter
Program to Print Values as
Characters and Integers
29
Constants
 A constant is a specific value that we use in our
programs. For example
3.14, 97, ‘a’, or “hello”
 In your program,
int a = 97;
char b =‘a’;
double area, r=2.0;
double circumference;
area = 3.14 * r*r;
circumference = 2 * 3.14 * r;
30
01100001
01100001
?
?
2.0
a
b
area
circumf
erence
r
Symbolic Constants
 What if you want to use a better estimate of ?
For example, you want 3.141593 instead of 3.14.
 You need to replace all by hand 
 Better solution, define  as a symbolic constant, e.g.
#define PI 3.141593
…
area = PI * r * r;
circumference = 2 * PI * r;
 Defined with a preprocessor directive
 Compiler replaces each occurrence of the directive
identifier with the constant value in all statements that
follow the directive
31
2.3 Assignment Statements
 Used to assign a value to a variable
 General Form:
identifier = expression;
/* ‘=‘ means assign expression to identifier */
 Example 1
double sum = 0;
 Example 2
int x;
x=5;
 Example 3
char ch;
ch = ‘a’;
32
0
5
‘a’
sum
x
ch
Assignment examples (cont’d)
 Example 3
int x, y, z;
x = y = 0;
right to left!
Z = 1+1;
 Example 4
y=z;
y=5;
33
0
0
2
x
y
z
2 5
Assignment examples with
different types
int a, b=5;
double c=2.3;
…
a=c; /* data loss */
c=b; /* no data loss */
34
?
5
2.3
a
b
c
2
5.0
long double, double, float, long integer, integer, short integer, char
 Data may be lost. Be careful!
 No data loss
Exercise: swap
 Write a set of statements that swaps the
contents of variables x and y
35
3
5
x
y
Before After
5
3
x
y
Exercise: swap
First Attempt
x=y;
y=x;
36
Before
3
5
x
y
After x=y
5
5
x
y
After y=x
5
5
x
y
Exercise: swap
Solution
temp= x;
x=y;
y=temp;
37
Before
?temp
3
5
x
y
after temp=x after x=y after y = temp
3temp
3
5
x
y
3temp
5
5
x
y
3temp
5
3
x
y
Will the following solution work, too? temp= y;
y=x;
x=temp;
Write a C program to swap the values of two variables
38
OPERATORS
Name Addr Content
Lecture 4
Arithmetic Operators
 Addition + sum = num1 + num2;
 Subtraction - age = 2007 – my_birth_year;
 Multiplication * area = side1 * side2;
 Division / avg = total / number;
 Modulus % lastdigit = num % 10;
 Modulus returns remainder of division between two integers
 Example 5%2 returns a value of 1
 Binary vs. Unary operators
 All the above operators are binary (why)
 - is an unary operator, e.g., a = -3 * -4
39
Arithmetic Operators (cont’d)
 Note that ‘id = exp‘ means assign
the result of exp to id, so
 X=X+1 means
 first perform X+1 and
 Assign the result to X
 Suppose X is 4, and
 We execute X=X+1
40
4 X5
Integer division vs Real division
 Division between two integers results in an
integer.
 The result is truncated, not rounded
 Example:
int A=5/3;  A will have the value of 1
int B=3/6;  B will have the value of 0
 To have floating point values:
double A=5.0/3;  A will have the value of 1.666
double B=3.0/6.0;  B will have the value of 0.5
41
Implement a program that computes/prints
simple arithmetic operations
Declare a=2, b=5, c=7, d as int
Declare x=5.0, y=3.0, z=7.0, w as double
d = c%a Print d
d = c/a Print d
w = z/x Print w
d = z/x Print d
w = c/a Print w
a=a+1 Print a
… try other arithmetic operations too.. 42
Mixed operations and
Precedence of Arithmetic Operators
43
int a=4+6/3*2;  a=?
int b=(4+6)/3*2;  b=?
a= 4+2*2 = 4+4 = 8
b= 10/3*2 = 3*2= 6
5 assign = Right to left
Extend the previous program to compute/print
mixed arithmetic operations
44
Declare a=2, b=5, c=7, d as int
Declare x=5.0, y=3.0, z=7.0, w as double
d = a+c%a Print d
d = b*c/a Print d
w = y*z/x+b Print w
d = z/x/y*a Print d
w = c/(a+c)/b Print w
a=a+1+b/3 Print a
… try other arithmetic operations too..
Increment and Decrement Operators
 Increment Operator ++
 post increment x++;
 pre increment ++x;
 Decrement Operator --
 post decrement x--;
 pre decrement --x;
45
} x=x+1;
} x=x-1;
But, the difference is in the following example. Suppose x=10;
A = x++ - 5; means A=x-5; x=x+1; so, A= 5 and x=11
B =++x - 5; means x=x+1; B=x-5; so, B=6 and x=11
Abbreviated Assignment Operator
operator example equivalent statement
+= x+=2; x=x+2;
-= x-=2; x=x-2;
*= x*=y; x=x*y;
/= x/=y; x=x/y;
%= x%=y; x=x%y;
!!! x *= 4+2/3  x = x*4+2/3 wrong
x=x*(4+2/3) correct
46
Precedence of
Arithmetic Operators (updated)
47
Writing a C statement for a
given MATH formula
 Area of trapezoid
area = base*(height1 + height2)/2;
 How about this
48
2
)(* 21 heightheightbase
area


g
mm
mm
Tension 


21
212
49
Exercise
 Write a C statement to compute the following
14.305.0
3.62
2
23



xx
xxx
f
f = (x*x*x-2*x*x+x-6.3)/(x*x+0.05*x+3.14);
Tension = 2*m1*m2 / m1 + m2 * g;
Tension = 2*m1*m2 / (m1 + m2) * g
wrong
g
mm
mm
Tension 


21
212
Exercise: Arithmetic operations
 Show the memory snapshot after the
following operations by hand
int a, b, c=5;
double x, y;
a = c * 2.5;
b = a % c * 2 - 1;
x = (5 + c) * 2.5;
y = x – (-3 * a) / 2;
Write a C program and print out the
values of a, b, c, x, y and compare them
with the ones that you determined by
hand.
50
?
?
5
?
?
a
b
c
x
y
a = 12 b = 3 c= 5 x = 25.0000 y = 43.0000
Exercise: Arithmetic
operations
 Show how C will perform the following
statements and what will be the final
output?
int a = 6, b = -3, c = 2;
c= a - b * (a + c * 2) + a / 2 * b;
printf("Value of c = %d n", c);
51
Step-by-step show how C will
perform the operations
c = 6 - -3 * (6 + 2 * 2) + 6 / 2 * -3;
c = 6 - -3 * (6 + 4) + 3 * -3
c = 6 - -3 *10 + -9
c = 6 - -30 + -9
c = 36 + -9
c = 27
 output:
Value of c = 27
52
Step-by-step show how C will
perform the operations
int a = 8, b = 10, c = 4;
c = a % 5 / 2 + -b / (3 – c) * 4 + a / 2 * b;
printf("New value of c is %d n", c);
53
Exercise: reverse a number
 Suppose you are given a number in the
range [100 999]
 Write a program to reverse it
 For example,
num is 258
reverse is 852
54
int d1, d2, d3, num=258, reverse;
d1 = num / 100;
d2 = num % 100 / 10;
d3 = num % 10;
reverse = d3*100 + d2*10 + d1;
printf(“reverse is %dn”, reverse);
d1 = num / 100;
d3 = num % 10;
reverse = num – (d1*100+d3) +
d3*100 + d1;
55
Lecture++;
Name Addr Content
Lecture 5
2.4 Standard Input and Output
 Output: printf
 Input: scanf
 Remember the program computing the distance between
two points!
 /* Declare and initialize variables. */
 double x1=1, y1=5, x2=4, y2=7,
 side_1, side_2, distance;
 How can we compute distance for different points?
 It would be better to get new points from user, right? For
this we will use scanf
 To use these functions, we need to use
#include <stdio.h>
56
Standard Output
 printf Function
 prints information to the screen
 requires two arguments
 control string
 Contains text, conversion specifiers or both
 Identifier to be printed
 Example
double angle = 45.5;
printf(“Angle = %.2f degrees n”, angle);
Output:
Angle = 45.50 degrees
57
Control String
Identifier
Conversion
Specifier
58
Conversion Specifiers for
Output Statements
Frequently Used
Standard Output
Output of -145 Output of 157.8926
Specifier Value Printed
%f 157.892600
%6.2f 157.89
%7.3f 157.893
%7.4f 157.8926
%7.5f 157.89260
%e 1.578926e+02
%.3E 1.579E+02
59
Specifier Value Printed
%i -145
%4d -145
%3i -145
%6i __-145
%-6i -145__
%8i ____-145
%-8i -145____
60
Exercise
printf("Sum = %5i; Average = %7.1f n", sum, average);
printf("Sum = %4i n Average = %8.4f n", sum, average);
printf("Sum and Average nn %d %.1f n", sum, average);
printf("Character is %c; Sum is %c n", ch, sum);
printf("Character is %i; Sum is %i n", ch, sum);
int sum = 65;
double average = 12.368;
char ch = ‘b’;
Show the output line (or lines) generated by the following statements.
61
Exercise (cont’d)
 Solution
Sum = 65; Average = 12.4
Sum = 65
Average = 12.3680
Sum and Average
65 12.4
Character is b; Sum is A
Character is 98; Sum is 65
Standard Input
 scanf Function
 inputs values from the keyboard
 required arguments
 control string
 memory locations that correspond to the specifiers in the
control string
 Example:
double distance;
char unit_length;
scanf("%lf %c", &distance, &unit_length);
 It is very important to use a specifier that is appropriate for the data
type of the variable
62
63
Conversion Specifiers for
Input Statements
Frequently Used
64
Exercise
float f;
int i;
scanf(“%f %i“, &f, &i);
 What will be the values stored in f and i after scanf statement if
following values are entered
12.5 1
12 45
12 23.2
12.1 10
12
1
Good practice
 You don’t need to have a printf before
scanf, but it is good to let user know what
to enter:
printf(“Enter x y : ”);
scanf(“%d %d”, &x, &y);
 Otherwise, user will not know what to do!
 What will happen if you forget & before
the variable name?
65
Exercise: How to input two points
without re-compiling the program
66
printf(“enter x1 y1: “);
scanf(“%lf %lf“, &x1, &y1);
printf(“enter x2 y2: “);
scanf(“%lf %lf“, &x2, &y2);
Programming exercise
 Write a program that asks user to enter
values for the double variables (a, b, c, d)
in the following formula. It then computes
the result (res) and prints it with three
digits after .
67
ca
bc
ba
ca
dc
ba
res








Exercise
 Study Section 2.5 and 2.6 from the
textbook
68
69
Lecture++;
Name Addr Content
Lecture 6
Library Functions
70
2.7 Math Functions
71
#include <math.h>
fabs(x) Absolute value of x.
sqrt(x) Square root of x, where x>=0.
pow(x,y) Exponentiation, xy. Errors occur if
x=0 and y<=0, or if x<0 and y is not an integer.
ceil(x) Rounds x to the nearest integer toward  (infinity).
Example, ceil(2.01) is equal to 3.
floor(x) Rounds x to the nearest integer toward - (negative
infinity). Example, floor(2.01) is equal to 2.
exp(x) Computes the value of ex.
log(x) Returns ln x, the natural logarithm of x to the base e.
Errors occur if x<=0.
log10(x) Returns log10x, logarithm of x to the base 10.
Errors occur if x<=0.
Trigonometric Functions
72
sin(x) Computes the sine of x, where x is in radians.
cos(x) Computes the cosine of x, where x is in radians
tan(x) Computes the tangent of x, where x is in radians.
asin(x) Computes the arcsine or inverse sine of x,
where x must be in the range [-1, 1].
Returns an angle in radians in the range [-/2,/2].
acos(x) Computes the arccosine or inverse cosine of x,
where x must be in the range [-1, 1].
Returns an angle in radians in the range [0, ].
atan(x) Computes the arctangent or inverse tangent of x. The
Returns an angle in radians in the range [-/2,/2].
atan2(y,x) Computes the arctangent or inverse tangent of the value
y/x. Returns an angle in radians in the range [-, ].
Parameters or Arguments of a
function
 A function may contain no argument or contain one
or more arguments
 If more than one argument, list the arguments in the
correct order
 Be careful about the meaning of an argument. For
example, sin(x) assumes that x is given in radians, so
to compute the sin of 60 degree, you need to first
conver 60 degree into radian then call sin function:
#define PI 3.141593
theta = 60;
theta_rad = theata * PI / 180;
b = sin(theta_rad); /* is not the same as sin(theta); */
73
Exercise
 Write an expression to compute velocity using the following
equation
 Assume that the variables are declared
)(22
xoxavovelocity 
74
velocity = sqrt(vo*vo+2*a*(x-xo));
velocity = sqrt(pow(vo,2)+2*a*(x-xo));
Exercise
 Write an expression to compute velocity using the following
equation
 Assume that the variables are declared
asr
asr
center
)(
sin)(19.38
22
33



75
center = (38.19*(pow(r,3)-pow(s,3))*sin(a))/
((pow(r,2)-pow(s,2))*a);
Make sure that a is given in radian; otherwise, first convert it to radian
center = (38.19*(r*r*r - s*s*s)*sin(a))/((r*r –s*s)*a);
Exercise: Compute Volume
 Write a program to compute the volume
of a cylinder of radius r and height h
hrV 2

76
h
r
Solution: Compute Volume
77
Problem Solving Methodology
1. Problem Statement
2. Input/Output Description
3. Hand Example
4. Algorithm Development
5. Testing
Solution: Compute Volume
(cont’d)
 Problem Statement
 compute the volume of a cylinder of radius r and
height h
 Input Output Description
78
radius r
height h
volume v
Solution: Compute Volume
(cont’d)
 Hand example
 r=2, h =3, v=37.68
 Algorithm Development
 Read radius
 Read height
 Compute Volume
 Print volume
 Convert to a program (see next slide)
79
hrV 2

Solution: Compute Volume
(coding)
80
#include <stdio.h>
#define PI 3.141593
int main(void)
{
/* Declare Variables */
double radius, height, volume;
printf("Enter radius: "); scanf("%lf",&radius);
printf("Enter height: "); scanf("%lf",&height);
/* Compute Volune */
volume = PI*radius*radius*height;
/* Print volume */
printf("Volume = %8.3f n", volume);
system("pause");
exit(0);
}
81
Exercise
 Write a program to find the radius of a circle
given its area. Read area from user. Compute
radius and display it.
2
rA 
r
Exercise
C
c
B
b
A
a
sinsinsin

82
AbcBacCabarea sin
2
1
sin
2
1
sin
2
1

A
B Ca
b
c
Write a program that asks user to
enter A in degrees, a and b in cm,
then computes
B=? in degrees
C=? in degrees
c=? in cm
area=? in cm2
For example, given A=36o, a=8 cm, b=5 cm:
B=21.55o, C=122.45o, c=11.49 cm
Write a program that finds the
intersection of two lines and the
angle between them
 See handout
83
2.8 Character Functions
84
#include <ctype.h>
putchar(‘a’);
C= getchar();
toupper(ch) If ch is a lowercase letter, this function returns the
corresponding uppercase letter; otherwise, it returns ch
isdigit(ch) Returns a nonzero value if ch is a decimal digit; otherwise, it
returns a zero.
islower(ch) Returns a nonzero value if ch is a lowercase letter; otherwise,
it returns a zero.
isupper(ch) Returns a nonzero value if ch is an uppercase letter;
otherwise, it returns a zero.
isalpha(ch) Returns a nonzero value if ch is an uppercase letter or a
lowercase letter; otherwise, it returns a zero.
isalnum(ch) Returns a nonzero value if ch is an alphabetic character or a
numeric digit; otherwise, it returns a zero.
Exercise
85
What is the output of the following program
#include <stdio.h>
#include <ctype.h>
int main(void)
{
char ch1='a', ch2;
char ch3='X', ch4;
char ch5='8';
ch2 = toupper(ch1);
printf("%c %c n",ch1,ch2);
ch4 = tolower(ch3);
printf("%c %c n",ch3,ch4);
printf("%dn",isdigit(ch5));
printf("%dn",islower(ch1));
printf("%dn",isalpha(ch5));
system("pause");
return(0);
}
Skip
 Study Section 2.9 from the textbook
 Skip Section 2.10
86

More Related Content

What's hot

Colored petri nets theory and applications
Colored petri nets theory and applicationsColored petri nets theory and applications
Colored petri nets theory and applicationsAbu Hussein
 
SyScan360 - Stefan Esser - OS X El Capitan sinking the S\H/IP
SyScan360 - Stefan Esser - OS X El Capitan sinking the S\H/IPSyScan360 - Stefan Esser - OS X El Capitan sinking the S\H/IP
SyScan360 - Stefan Esser - OS X El Capitan sinking the S\H/IPStefan Esser
 
Compiler Design
Compiler DesignCompiler Design
Compiler DesignMir Majid
 
Mathematical Analysis of Recursive Algorithm.
Mathematical Analysis of Recursive Algorithm.Mathematical Analysis of Recursive Algorithm.
Mathematical Analysis of Recursive Algorithm.mohanrathod18
 
Presentacion final
Presentacion finalPresentacion final
Presentacion finalErick Roldan
 
25422733 c-programming-and-data-structures-lab-manual
25422733 c-programming-and-data-structures-lab-manual25422733 c-programming-and-data-structures-lab-manual
25422733 c-programming-and-data-structures-lab-manualkamesh dagia
 
UNIT-1-PPTS-DAA.ppt
UNIT-1-PPTS-DAA.pptUNIT-1-PPTS-DAA.ppt
UNIT-1-PPTS-DAA.pptracha49
 
8 queens problem using back tracking
8 queens problem using back tracking8 queens problem using back tracking
8 queens problem using back trackingTech_MX
 
Stack - Data Structure - Notes
Stack - Data Structure - NotesStack - Data Structure - Notes
Stack - Data Structure - NotesOmprakash Chauhan
 
4 Mapping the Application
4 Mapping the Application4 Mapping the Application
4 Mapping the ApplicationSam Bowne
 
Removal Of Recursion
Removal Of RecursionRemoval Of Recursion
Removal Of RecursionRicha Sharma
 

What's hot (20)

Understanding Natural Language Processing
Understanding Natural Language ProcessingUnderstanding Natural Language Processing
Understanding Natural Language Processing
 
Singly Linked List & Data Structure
Singly Linked List & Data StructureSingly Linked List & Data Structure
Singly Linked List & Data Structure
 
Data structures in c#
Data structures in c#Data structures in c#
Data structures in c#
 
C program
C programC program
C program
 
Basics of Maltego
Basics of MaltegoBasics of Maltego
Basics of Maltego
 
Colored petri nets theory and applications
Colored petri nets theory and applicationsColored petri nets theory and applications
Colored petri nets theory and applications
 
SyScan360 - Stefan Esser - OS X El Capitan sinking the S\H/IP
SyScan360 - Stefan Esser - OS X El Capitan sinking the S\H/IPSyScan360 - Stefan Esser - OS X El Capitan sinking the S\H/IP
SyScan360 - Stefan Esser - OS X El Capitan sinking the S\H/IP
 
Compiler Design
Compiler DesignCompiler Design
Compiler Design
 
Mathematical Analysis of Recursive Algorithm.
Mathematical Analysis of Recursive Algorithm.Mathematical Analysis of Recursive Algorithm.
Mathematical Analysis of Recursive Algorithm.
 
Presentacion final
Presentacion finalPresentacion final
Presentacion final
 
Windowsforensics
WindowsforensicsWindowsforensics
Windowsforensics
 
25422733 c-programming-and-data-structures-lab-manual
25422733 c-programming-and-data-structures-lab-manual25422733 c-programming-and-data-structures-lab-manual
25422733 c-programming-and-data-structures-lab-manual
 
UNIT-1-PPTS-DAA.ppt
UNIT-1-PPTS-DAA.pptUNIT-1-PPTS-DAA.ppt
UNIT-1-PPTS-DAA.ppt
 
8 queens problem using back tracking
8 queens problem using back tracking8 queens problem using back tracking
8 queens problem using back tracking
 
COMPILER DESIGN- Syntax Directed Translation
COMPILER DESIGN- Syntax Directed TranslationCOMPILER DESIGN- Syntax Directed Translation
COMPILER DESIGN- Syntax Directed Translation
 
Balanced Tree (AVL Tree & Red-Black Tree)
Balanced Tree (AVL Tree & Red-Black Tree)Balanced Tree (AVL Tree & Red-Black Tree)
Balanced Tree (AVL Tree & Red-Black Tree)
 
Constructor and destructor in C++
Constructor and destructor in C++Constructor and destructor in C++
Constructor and destructor in C++
 
Stack - Data Structure - Notes
Stack - Data Structure - NotesStack - Data Structure - Notes
Stack - Data Structure - Notes
 
4 Mapping the Application
4 Mapping the Application4 Mapping the Application
4 Mapping the Application
 
Removal Of Recursion
Removal Of RecursionRemoval Of Recursion
Removal Of Recursion
 

Similar to Introduction to c programming

UNIT-1 notes(Data Types – Variables – Operations – Expressions and Statements...
UNIT-1 notes(Data Types – Variables – Operations – Expressions and Statements...UNIT-1 notes(Data Types – Variables – Operations – Expressions and Statements...
UNIT-1 notes(Data Types – Variables – Operations – Expressions and Statements...RSathyaPriyaCSEKIOT
 
Lec1_EENG112-Introduction.pdf
Lec1_EENG112-Introduction.pdfLec1_EENG112-Introduction.pdf
Lec1_EENG112-Introduction.pdfShwetaSaharan8
 
Ch2 introduction to c
Ch2 introduction to cCh2 introduction to c
Ch2 introduction to cHattori Sidek
 
Labsheet1 stud
Labsheet1 studLabsheet1 stud
Labsheet1 studrohassanie
 
Introduction to C++ lecture ************
Introduction to C++ lecture ************Introduction to C++ lecture ************
Introduction to C++ lecture ************Emad Helal
 
Introduction to c programming
Introduction to c programmingIntroduction to c programming
Introduction to c programmingAlpana Gupta
 
C prog ppt
C prog pptC prog ppt
C prog pptxinoe
 
OOPS using C++
OOPS using C++OOPS using C++
OOPS using C++cpjcollege
 
Hello world! Intro to C++
Hello world! Intro to C++Hello world! Intro to C++
Hello world! Intro to C++DSCIGDTUW
 

Similar to Introduction to c programming (20)

UNIT-1 notes(Data Types – Variables – Operations – Expressions and Statements...
UNIT-1 notes(Data Types – Variables – Operations – Expressions and Statements...UNIT-1 notes(Data Types – Variables – Operations – Expressions and Statements...
UNIT-1 notes(Data Types – Variables – Operations – Expressions and Statements...
 
Lec1_EENG112-Introduction.pdf
Lec1_EENG112-Introduction.pdfLec1_EENG112-Introduction.pdf
Lec1_EENG112-Introduction.pdf
 
Ch2 introduction to c
Ch2 introduction to cCh2 introduction to c
Ch2 introduction to c
 
intro to c
intro to cintro to c
intro to c
 
Labsheet1 stud
Labsheet1 studLabsheet1 stud
Labsheet1 stud
 
Introduction to C++ lecture ************
Introduction to C++ lecture ************Introduction to C++ lecture ************
Introduction to C++ lecture ************
 
C programming
C programmingC programming
C programming
 
Introduction to c programming
Introduction to c programmingIntroduction to c programming
Introduction to c programming
 
Labsheet_3
Labsheet_3Labsheet_3
Labsheet_3
 
Programming in C
Programming in CProgramming in C
Programming in C
 
C prog ppt
C prog pptC prog ppt
C prog ppt
 
C-PPT.pdf
C-PPT.pdfC-PPT.pdf
C-PPT.pdf
 
Presentation 2.ppt
Presentation 2.pptPresentation 2.ppt
Presentation 2.ppt
 
Labsheet2
Labsheet2Labsheet2
Labsheet2
 
C Introduction
C IntroductionC Introduction
C Introduction
 
Labsheet1stud
Labsheet1studLabsheet1stud
Labsheet1stud
 
Cinfo
CinfoCinfo
Cinfo
 
OOPS using C++
OOPS using C++OOPS using C++
OOPS using C++
 
Hello world! Intro to C++
Hello world! Intro to C++Hello world! Intro to C++
Hello world! Intro to C++
 
Introduction%20C.pptx
Introduction%20C.pptxIntroduction%20C.pptx
Introduction%20C.pptx
 

More from Infinity Tech Solutions

Database Management System-session 3-4-5
Database Management System-session 3-4-5Database Management System-session 3-4-5
Database Management System-session 3-4-5Infinity Tech Solutions
 
Main topic 3 problem solving and office automation
Main topic 3 problem solving and office automationMain topic 3 problem solving and office automation
Main topic 3 problem solving and office automationInfinity Tech Solutions
 
Computer memory, Types of programming languages
Computer memory, Types of programming languagesComputer memory, Types of programming languages
Computer memory, Types of programming languagesInfinity Tech Solutions
 
AI/ML/DL/BCT A Revolution in Maritime Sector
AI/ML/DL/BCT A Revolution in Maritime SectorAI/ML/DL/BCT A Revolution in Maritime Sector
AI/ML/DL/BCT A Revolution in Maritime SectorInfinity Tech Solutions
 
Programming with matlab session 5 looping
Programming with matlab session 5 loopingProgramming with matlab session 5 looping
Programming with matlab session 5 loopingInfinity Tech Solutions
 

More from Infinity Tech Solutions (20)

Database management system session 6
Database management system session 6Database management system session 6
Database management system session 6
 
Database management system session 5
Database management system session 5Database management system session 5
Database management system session 5
 
Database Management System-session 3-4-5
Database Management System-session 3-4-5Database Management System-session 3-4-5
Database Management System-session 3-4-5
 
Database Management System-session1-2
Database Management System-session1-2Database Management System-session1-2
Database Management System-session1-2
 
Main topic 3 problem solving and office automation
Main topic 3 problem solving and office automationMain topic 3 problem solving and office automation
Main topic 3 problem solving and office automation
 
E commerce
E commerce E commerce
E commerce
 
E commerce
E commerceE commerce
E commerce
 
Bds session 13 14
Bds session 13 14Bds session 13 14
Bds session 13 14
 
Computer memory, Types of programming languages
Computer memory, Types of programming languagesComputer memory, Types of programming languages
Computer memory, Types of programming languages
 
Basic hardware familiarization
Basic hardware familiarizationBasic hardware familiarization
Basic hardware familiarization
 
User defined functions in matlab
User defined functions in  matlabUser defined functions in  matlab
User defined functions in matlab
 
Programming with matlab session 6
Programming with matlab session 6Programming with matlab session 6
Programming with matlab session 6
 
Programming with matlab session 3 notes
Programming with matlab session 3 notesProgramming with matlab session 3 notes
Programming with matlab session 3 notes
 
AI/ML/DL/BCT A Revolution in Maritime Sector
AI/ML/DL/BCT A Revolution in Maritime SectorAI/ML/DL/BCT A Revolution in Maritime Sector
AI/ML/DL/BCT A Revolution in Maritime Sector
 
Programming with matlab session 5 looping
Programming with matlab session 5 loopingProgramming with matlab session 5 looping
Programming with matlab session 5 looping
 
BIG DATA Session 7 8
BIG DATA Session 7 8BIG DATA Session 7 8
BIG DATA Session 7 8
 
BIG DATA Session 6
BIG DATA Session 6BIG DATA Session 6
BIG DATA Session 6
 
MS word
MS word MS word
MS word
 
DBMS CS 4-5
DBMS CS 4-5DBMS CS 4-5
DBMS CS 4-5
 
DBMS CS3
DBMS CS3DBMS CS3
DBMS CS3
 

Recently uploaded

Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AIabhishek36461
 
Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...VICTOR MAESTRE RAMIREZ
 
Concrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptxConcrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptxKartikeyaDwivedi3
 
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...srsj9000
 
Internship report on mechanical engineering
Internship report on mechanical engineeringInternship report on mechanical engineering
Internship report on mechanical engineeringmalavadedarshan25
 
chaitra-1.pptx fake news detection using machine learning
chaitra-1.pptx  fake news detection using machine learningchaitra-1.pptx  fake news detection using machine learning
chaitra-1.pptx fake news detection using machine learningmisbanausheenparvam
 
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfCCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfAsst.prof M.Gokilavani
 
SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )Tsuyoshi Horigome
 
Introduction to Microprocesso programming and interfacing.pptx
Introduction to Microprocesso programming and interfacing.pptxIntroduction to Microprocesso programming and interfacing.pptx
Introduction to Microprocesso programming and interfacing.pptxvipinkmenon1
 
Artificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxArtificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxbritheesh05
 
power system scada applications and uses
power system scada applications and usespower system scada applications and uses
power system scada applications and usesDevarapalliHaritha
 
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...Soham Mondal
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfAsst.prof M.Gokilavani
 
Introduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxIntroduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxk795866
 
IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024Mark Billinghurst
 
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerStudy on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerAnamika Sarkar
 
Biology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxBiology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxDeepakSakkari2
 
GDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSCAESB
 

Recently uploaded (20)

Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AI
 
Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...
 
Concrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptxConcrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptx
 
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
 
Internship report on mechanical engineering
Internship report on mechanical engineeringInternship report on mechanical engineering
Internship report on mechanical engineering
 
chaitra-1.pptx fake news detection using machine learning
chaitra-1.pptx  fake news detection using machine learningchaitra-1.pptx  fake news detection using machine learning
chaitra-1.pptx fake news detection using machine learning
 
Design and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdfDesign and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdf
 
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfCCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
 
SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )
 
Introduction to Microprocesso programming and interfacing.pptx
Introduction to Microprocesso programming and interfacing.pptxIntroduction to Microprocesso programming and interfacing.pptx
Introduction to Microprocesso programming and interfacing.pptx
 
Artificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxArtificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptx
 
power system scada applications and uses
power system scada applications and usespower system scada applications and uses
power system scada applications and uses
 
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
 
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
 
Introduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxIntroduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptx
 
IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024
 
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerStudy on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
 
Biology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxBiology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptx
 
GDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentation
 

Introduction to c programming

  • 2. Session objective History of C Language Structure of a C program Statements & Basic Data Types Variables &Constants Input & Output statements Operators, Precedence, Expressions, Simple C programs. SUMMARY
  • 3. History of C 1960: ALGOL (ALGOrithmic Language) 1967: BCPL (Basic Combined Programming Language) 1970: B programming language (typeless) 1972: C: BCPL plus B with types 1978: Kernighan + Ritchie standard for C 1989: ANSI standard for C
  • 5. 5 /*-----------------------------------------*/ /* Program chapter1_1 */ /* This program computes the */ /* distance between two points. */ #include <stdio.h> #include <math.h> int main(void) { /* Declare and initialize variables. */ double x1=1, y1=5, x2=4, y2=7, side_1, side_2, distance; /* Compute sides of a right triangle. */ side_1 = x2 - x1; side_2 = y2 - y1; distance=sqrt(side_1*side_1 + side_2*side_2); /* Print distance. */ printf("The distance between the two " "points is %5.2f n", distance); return 0; /* Exit program. */ } /*-----------------------------------------*/ Comments Preprocessor, standard C library every C program must have main function, this one takes no parameters and it returns int value {  begin Variable declarations, initial values (if any) Statements must end with ; indentation indentation indentation return 0 }  end of function
  • 6. Parts of a Program #include <stdio.h> int x; int main () { int y; printf("Enter x and y: "); scanf(&x,&y); printf("Sum is %dn",x+y); } Preprocessor Directive Global Declaration Function Local Declaration Statements
  • 7. C Program Structure Preprocessor Directives Global Declarations Function Definitions int main () { } Local Declarations Statements  Program defined by:  global declarations  function definitions  May contain preprocessor directives  Always has one function named main, may contain others
  • 8. Outline II. Program Basics A. Program skeleton preprocessor directives global declarations functions local declarations statements B. Comments and Documentation C. Names (identifiers) reserved words
  • 9. Outline (cont) II. Program Basics (cont) D. Variable declarations 1. Memory allocation 2. Atomic types void, int, float, char E. Constants 1. literal 2. defined 3. memory
  • 10. Outline (cont) II. Program Basics (cont) F. Formatted input/output 1. Files 2. Printf (monitor output) a. format strings field specifications b. data list 3. Scanf (keyboard input) a. format strings b. address list 4. Prompting for Input
  • 11. Preprocessor Directives  Begin with #  Instruct compiler to perform some transformation to file before compiling  Example: #include <stdio.h>  add the header file stdio.h to this file  .h for header file  stdio.h defines useful input/output functions
  • 12. Declarations  Global  visible throughout program  describes data used throughout program  Local  visible within function  describes data used only in function
  • 13. Functions  Consists of header and body  header: int main ()  body: contained between { and }  starts with location declarations  followed by series of statements  More than one function may be defined  Functions are called (invoked) - more later
  • 14. Main Function  Every program has one function main  Header for main: int main ()  Program is the sequence of statements between the { } following main  Statements are executed one at a time from the one immediately following to main to the one before the }
  • 15. Comments  Text between /* and */  Used to “document” the code for the human reader  Ignored by compiler (not part of program)  Have to be careful  comments may cover multiple lines  ends as soon as */ encountered (so no internal comments - /* An /* internal */
  • 16. Comment Example #include <stdio.h> /* This comment covers * multiple lines * in the program. */ int main () /* The main header */ { /* No local declarations */ printf(“Too many commentsn”); } /* end of main */
  • 17. Documentation  Global - start of program, outlines overall solution, may include structure chart  Module - when using separate files, indication of what each file solves  Function - inputs, return values, and logic used in defining function  Add documentation for key (tough to understand) comments  Names of variables - should be chosen to be meaningful, make program
  • 18. General Form 18 preprocessing directives int main(void) { declarations statements }  The main function contains two types of commands: declarations and statements  Declarations and statements are required to end with a semicolon (;)  Preprocessor directives do not end with a semicolon  To exit the program, use a return 0; statement
  • 19. Another Program 19 /***************************************************/ /* Program chapter1 */ /* This program computes the sum of two numbers */ #include <stdio.h> int main(void) { /* Declare and initialize variables. */ double number1 = 473.91, number2 = 45.7, sum; /* Calculate sum. */ sum = number1 + number2; /* Print the sum. */ printf(“The sum is %5.2f n”, sum); system("pause"); /* keep DOS window on the screen*/ return 0; /* Exit program. */ } /****************************************************/
  • 20. 2.2 Constants and Variables  What is a variable in math? f(x) = x2+x+4  In C,  A variable is a memory location that holds a value  An identifier or variable name is used to reference a memory location. 20
  • 21. 21 Memory double x1=1,x2=7,distance; 1 = 00000001 7 = 00000111 ? = 01001101 … 11 12 13 14 15 16 … x1 x2 distance addressname Memory - content How many memory cells does your computer have? Say it says 2Gbyte memory? 1K=103 or 210 = 1024 1M=106 or 220 = 10242 1G=109 or 230 = 10243
  • 22. Memory Snapshot 22 Name Addr Content x1 1 y1 5 x2 4 y2 7 side_1 ? side_2 ? distance ?
  • 23. Rules for selecting a valid identifier (variable name)  Must begin with an alphabetic character or underscore (e.g., abcABC_)  May contain only letters, digits and underscore (no special characters ^%@)  Case sensitive (AbC, aBc are different)  Cannot use C keywords as identifiers (e.g., if, case, while) 23
  • 24. Are the following valid identifiers?  distance  1x  x_1 24 rate% x_sum switch initial_time DisTaNce X&Y
  • 25. C Numeric Data Types 25
  • 27. C Character Data Type: char 27 In memory, everything is stored as binary value, which can be interpreted as char or integer. Examples of ASCII Codes char result =‘Y’;
  • 28. 28 Memory How to represent ‘a’ ? char My_letter=‘a’; int My_number = 97 Always we have 1’s and 0’s in the memory. It depends on how you look at it? For example, 01100001 is 97 if you look at it as int, or ‘a’ if you look at it as char ‘3’ is not the same as 3 How to represent 2.5? ‘a’= 01100001 97 = 01100001 ? = 01001101 0 1 2 3 4 5 6 … My_number addressname Memory - content My_letter
  • 29. Program to Print Values as Characters and Integers 29
  • 30. Constants  A constant is a specific value that we use in our programs. For example 3.14, 97, ‘a’, or “hello”  In your program, int a = 97; char b =‘a’; double area, r=2.0; double circumference; area = 3.14 * r*r; circumference = 2 * 3.14 * r; 30 01100001 01100001 ? ? 2.0 a b area circumf erence r
  • 31. Symbolic Constants  What if you want to use a better estimate of ? For example, you want 3.141593 instead of 3.14.  You need to replace all by hand   Better solution, define  as a symbolic constant, e.g. #define PI 3.141593 … area = PI * r * r; circumference = 2 * PI * r;  Defined with a preprocessor directive  Compiler replaces each occurrence of the directive identifier with the constant value in all statements that follow the directive 31
  • 32. 2.3 Assignment Statements  Used to assign a value to a variable  General Form: identifier = expression; /* ‘=‘ means assign expression to identifier */  Example 1 double sum = 0;  Example 2 int x; x=5;  Example 3 char ch; ch = ‘a’; 32 0 5 ‘a’ sum x ch
  • 33. Assignment examples (cont’d)  Example 3 int x, y, z; x = y = 0; right to left! Z = 1+1;  Example 4 y=z; y=5; 33 0 0 2 x y z 2 5
  • 34. Assignment examples with different types int a, b=5; double c=2.3; … a=c; /* data loss */ c=b; /* no data loss */ 34 ? 5 2.3 a b c 2 5.0 long double, double, float, long integer, integer, short integer, char  Data may be lost. Be careful!  No data loss
  • 35. Exercise: swap  Write a set of statements that swaps the contents of variables x and y 35 3 5 x y Before After 5 3 x y
  • 37. Exercise: swap Solution temp= x; x=y; y=temp; 37 Before ?temp 3 5 x y after temp=x after x=y after y = temp 3temp 3 5 x y 3temp 5 5 x y 3temp 5 3 x y Will the following solution work, too? temp= y; y=x; x=temp; Write a C program to swap the values of two variables
  • 39. Arithmetic Operators  Addition + sum = num1 + num2;  Subtraction - age = 2007 – my_birth_year;  Multiplication * area = side1 * side2;  Division / avg = total / number;  Modulus % lastdigit = num % 10;  Modulus returns remainder of division between two integers  Example 5%2 returns a value of 1  Binary vs. Unary operators  All the above operators are binary (why)  - is an unary operator, e.g., a = -3 * -4 39
  • 40. Arithmetic Operators (cont’d)  Note that ‘id = exp‘ means assign the result of exp to id, so  X=X+1 means  first perform X+1 and  Assign the result to X  Suppose X is 4, and  We execute X=X+1 40 4 X5
  • 41. Integer division vs Real division  Division between two integers results in an integer.  The result is truncated, not rounded  Example: int A=5/3;  A will have the value of 1 int B=3/6;  B will have the value of 0  To have floating point values: double A=5.0/3;  A will have the value of 1.666 double B=3.0/6.0;  B will have the value of 0.5 41
  • 42. Implement a program that computes/prints simple arithmetic operations Declare a=2, b=5, c=7, d as int Declare x=5.0, y=3.0, z=7.0, w as double d = c%a Print d d = c/a Print d w = z/x Print w d = z/x Print d w = c/a Print w a=a+1 Print a … try other arithmetic operations too.. 42
  • 43. Mixed operations and Precedence of Arithmetic Operators 43 int a=4+6/3*2;  a=? int b=(4+6)/3*2;  b=? a= 4+2*2 = 4+4 = 8 b= 10/3*2 = 3*2= 6 5 assign = Right to left
  • 44. Extend the previous program to compute/print mixed arithmetic operations 44 Declare a=2, b=5, c=7, d as int Declare x=5.0, y=3.0, z=7.0, w as double d = a+c%a Print d d = b*c/a Print d w = y*z/x+b Print w d = z/x/y*a Print d w = c/(a+c)/b Print w a=a+1+b/3 Print a … try other arithmetic operations too..
  • 45. Increment and Decrement Operators  Increment Operator ++  post increment x++;  pre increment ++x;  Decrement Operator --  post decrement x--;  pre decrement --x; 45 } x=x+1; } x=x-1; But, the difference is in the following example. Suppose x=10; A = x++ - 5; means A=x-5; x=x+1; so, A= 5 and x=11 B =++x - 5; means x=x+1; B=x-5; so, B=6 and x=11
  • 46. Abbreviated Assignment Operator operator example equivalent statement += x+=2; x=x+2; -= x-=2; x=x-2; *= x*=y; x=x*y; /= x/=y; x=x/y; %= x%=y; x=x%y; !!! x *= 4+2/3  x = x*4+2/3 wrong x=x*(4+2/3) correct 46
  • 48. Writing a C statement for a given MATH formula  Area of trapezoid area = base*(height1 + height2)/2;  How about this 48 2 )(* 21 heightheightbase area   g mm mm Tension    21 212
  • 49. 49 Exercise  Write a C statement to compute the following 14.305.0 3.62 2 23    xx xxx f f = (x*x*x-2*x*x+x-6.3)/(x*x+0.05*x+3.14); Tension = 2*m1*m2 / m1 + m2 * g; Tension = 2*m1*m2 / (m1 + m2) * g wrong g mm mm Tension    21 212
  • 50. Exercise: Arithmetic operations  Show the memory snapshot after the following operations by hand int a, b, c=5; double x, y; a = c * 2.5; b = a % c * 2 - 1; x = (5 + c) * 2.5; y = x – (-3 * a) / 2; Write a C program and print out the values of a, b, c, x, y and compare them with the ones that you determined by hand. 50 ? ? 5 ? ? a b c x y a = 12 b = 3 c= 5 x = 25.0000 y = 43.0000
  • 51. Exercise: Arithmetic operations  Show how C will perform the following statements and what will be the final output? int a = 6, b = -3, c = 2; c= a - b * (a + c * 2) + a / 2 * b; printf("Value of c = %d n", c); 51
  • 52. Step-by-step show how C will perform the operations c = 6 - -3 * (6 + 2 * 2) + 6 / 2 * -3; c = 6 - -3 * (6 + 4) + 3 * -3 c = 6 - -3 *10 + -9 c = 6 - -30 + -9 c = 36 + -9 c = 27  output: Value of c = 27 52
  • 53. Step-by-step show how C will perform the operations int a = 8, b = 10, c = 4; c = a % 5 / 2 + -b / (3 – c) * 4 + a / 2 * b; printf("New value of c is %d n", c); 53
  • 54. Exercise: reverse a number  Suppose you are given a number in the range [100 999]  Write a program to reverse it  For example, num is 258 reverse is 852 54 int d1, d2, d3, num=258, reverse; d1 = num / 100; d2 = num % 100 / 10; d3 = num % 10; reverse = d3*100 + d2*10 + d1; printf(“reverse is %dn”, reverse); d1 = num / 100; d3 = num % 10; reverse = num – (d1*100+d3) + d3*100 + d1;
  • 56. 2.4 Standard Input and Output  Output: printf  Input: scanf  Remember the program computing the distance between two points!  /* Declare and initialize variables. */  double x1=1, y1=5, x2=4, y2=7,  side_1, side_2, distance;  How can we compute distance for different points?  It would be better to get new points from user, right? For this we will use scanf  To use these functions, we need to use #include <stdio.h> 56
  • 57. Standard Output  printf Function  prints information to the screen  requires two arguments  control string  Contains text, conversion specifiers or both  Identifier to be printed  Example double angle = 45.5; printf(“Angle = %.2f degrees n”, angle); Output: Angle = 45.50 degrees 57 Control String Identifier Conversion Specifier
  • 58. 58 Conversion Specifiers for Output Statements Frequently Used
  • 59. Standard Output Output of -145 Output of 157.8926 Specifier Value Printed %f 157.892600 %6.2f 157.89 %7.3f 157.893 %7.4f 157.8926 %7.5f 157.89260 %e 1.578926e+02 %.3E 1.579E+02 59 Specifier Value Printed %i -145 %4d -145 %3i -145 %6i __-145 %-6i -145__ %8i ____-145 %-8i -145____
  • 60. 60 Exercise printf("Sum = %5i; Average = %7.1f n", sum, average); printf("Sum = %4i n Average = %8.4f n", sum, average); printf("Sum and Average nn %d %.1f n", sum, average); printf("Character is %c; Sum is %c n", ch, sum); printf("Character is %i; Sum is %i n", ch, sum); int sum = 65; double average = 12.368; char ch = ‘b’; Show the output line (or lines) generated by the following statements.
  • 61. 61 Exercise (cont’d)  Solution Sum = 65; Average = 12.4 Sum = 65 Average = 12.3680 Sum and Average 65 12.4 Character is b; Sum is A Character is 98; Sum is 65
  • 62. Standard Input  scanf Function  inputs values from the keyboard  required arguments  control string  memory locations that correspond to the specifiers in the control string  Example: double distance; char unit_length; scanf("%lf %c", &distance, &unit_length);  It is very important to use a specifier that is appropriate for the data type of the variable 62
  • 63. 63 Conversion Specifiers for Input Statements Frequently Used
  • 64. 64 Exercise float f; int i; scanf(“%f %i“, &f, &i);  What will be the values stored in f and i after scanf statement if following values are entered 12.5 1 12 45 12 23.2 12.1 10 12 1
  • 65. Good practice  You don’t need to have a printf before scanf, but it is good to let user know what to enter: printf(“Enter x y : ”); scanf(“%d %d”, &x, &y);  Otherwise, user will not know what to do!  What will happen if you forget & before the variable name? 65
  • 66. Exercise: How to input two points without re-compiling the program 66 printf(“enter x1 y1: “); scanf(“%lf %lf“, &x1, &y1); printf(“enter x2 y2: “); scanf(“%lf %lf“, &x2, &y2);
  • 67. Programming exercise  Write a program that asks user to enter values for the double variables (a, b, c, d) in the following formula. It then computes the result (res) and prints it with three digits after . 67 ca bc ba ca dc ba res        
  • 68. Exercise  Study Section 2.5 and 2.6 from the textbook 68
  • 71. 2.7 Math Functions 71 #include <math.h> fabs(x) Absolute value of x. sqrt(x) Square root of x, where x>=0. pow(x,y) Exponentiation, xy. Errors occur if x=0 and y<=0, or if x<0 and y is not an integer. ceil(x) Rounds x to the nearest integer toward  (infinity). Example, ceil(2.01) is equal to 3. floor(x) Rounds x to the nearest integer toward - (negative infinity). Example, floor(2.01) is equal to 2. exp(x) Computes the value of ex. log(x) Returns ln x, the natural logarithm of x to the base e. Errors occur if x<=0. log10(x) Returns log10x, logarithm of x to the base 10. Errors occur if x<=0.
  • 72. Trigonometric Functions 72 sin(x) Computes the sine of x, where x is in radians. cos(x) Computes the cosine of x, where x is in radians tan(x) Computes the tangent of x, where x is in radians. asin(x) Computes the arcsine or inverse sine of x, where x must be in the range [-1, 1]. Returns an angle in radians in the range [-/2,/2]. acos(x) Computes the arccosine or inverse cosine of x, where x must be in the range [-1, 1]. Returns an angle in radians in the range [0, ]. atan(x) Computes the arctangent or inverse tangent of x. The Returns an angle in radians in the range [-/2,/2]. atan2(y,x) Computes the arctangent or inverse tangent of the value y/x. Returns an angle in radians in the range [-, ].
  • 73. Parameters or Arguments of a function  A function may contain no argument or contain one or more arguments  If more than one argument, list the arguments in the correct order  Be careful about the meaning of an argument. For example, sin(x) assumes that x is given in radians, so to compute the sin of 60 degree, you need to first conver 60 degree into radian then call sin function: #define PI 3.141593 theta = 60; theta_rad = theata * PI / 180; b = sin(theta_rad); /* is not the same as sin(theta); */ 73
  • 74. Exercise  Write an expression to compute velocity using the following equation  Assume that the variables are declared )(22 xoxavovelocity  74 velocity = sqrt(vo*vo+2*a*(x-xo)); velocity = sqrt(pow(vo,2)+2*a*(x-xo));
  • 75. Exercise  Write an expression to compute velocity using the following equation  Assume that the variables are declared asr asr center )( sin)(19.38 22 33    75 center = (38.19*(pow(r,3)-pow(s,3))*sin(a))/ ((pow(r,2)-pow(s,2))*a); Make sure that a is given in radian; otherwise, first convert it to radian center = (38.19*(r*r*r - s*s*s)*sin(a))/((r*r –s*s)*a);
  • 76. Exercise: Compute Volume  Write a program to compute the volume of a cylinder of radius r and height h hrV 2  76 h r
  • 77. Solution: Compute Volume 77 Problem Solving Methodology 1. Problem Statement 2. Input/Output Description 3. Hand Example 4. Algorithm Development 5. Testing
  • 78. Solution: Compute Volume (cont’d)  Problem Statement  compute the volume of a cylinder of radius r and height h  Input Output Description 78 radius r height h volume v
  • 79. Solution: Compute Volume (cont’d)  Hand example  r=2, h =3, v=37.68  Algorithm Development  Read radius  Read height  Compute Volume  Print volume  Convert to a program (see next slide) 79 hrV 2 
  • 80. Solution: Compute Volume (coding) 80 #include <stdio.h> #define PI 3.141593 int main(void) { /* Declare Variables */ double radius, height, volume; printf("Enter radius: "); scanf("%lf",&radius); printf("Enter height: "); scanf("%lf",&height); /* Compute Volune */ volume = PI*radius*radius*height; /* Print volume */ printf("Volume = %8.3f n", volume); system("pause"); exit(0); }
  • 81. 81 Exercise  Write a program to find the radius of a circle given its area. Read area from user. Compute radius and display it. 2 rA  r
  • 82. Exercise C c B b A a sinsinsin  82 AbcBacCabarea sin 2 1 sin 2 1 sin 2 1  A B Ca b c Write a program that asks user to enter A in degrees, a and b in cm, then computes B=? in degrees C=? in degrees c=? in cm area=? in cm2 For example, given A=36o, a=8 cm, b=5 cm: B=21.55o, C=122.45o, c=11.49 cm
  • 83. Write a program that finds the intersection of two lines and the angle between them  See handout 83
  • 84. 2.8 Character Functions 84 #include <ctype.h> putchar(‘a’); C= getchar(); toupper(ch) If ch is a lowercase letter, this function returns the corresponding uppercase letter; otherwise, it returns ch isdigit(ch) Returns a nonzero value if ch is a decimal digit; otherwise, it returns a zero. islower(ch) Returns a nonzero value if ch is a lowercase letter; otherwise, it returns a zero. isupper(ch) Returns a nonzero value if ch is an uppercase letter; otherwise, it returns a zero. isalpha(ch) Returns a nonzero value if ch is an uppercase letter or a lowercase letter; otherwise, it returns a zero. isalnum(ch) Returns a nonzero value if ch is an alphabetic character or a numeric digit; otherwise, it returns a zero.
  • 85. Exercise 85 What is the output of the following program #include <stdio.h> #include <ctype.h> int main(void) { char ch1='a', ch2; char ch3='X', ch4; char ch5='8'; ch2 = toupper(ch1); printf("%c %c n",ch1,ch2); ch4 = tolower(ch3); printf("%c %c n",ch3,ch4); printf("%dn",isdigit(ch5)); printf("%dn",islower(ch1)); printf("%dn",isalpha(ch5)); system("pause"); return(0); }
  • 86. Skip  Study Section 2.9 from the textbook  Skip Section 2.10 86