Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 68

Introduction to C Programming

CSE115: Programming Language I


Semantics and Syntax
• Semantics – the meaning of the language within a given context
String firstName = 23; // java example

• Syntax - Syntax are the rules to join words


together in forming a correct expression or phrase.

int volume = 66 * 22 * 55; // C syntax


volume := 66 * 22 * 55 // Go syntax

• He drinks rice (wrong semantic- meaningless, right syntax- grammar)


• He drink water (right semantic- has meaning, wrong syntax- grammar)

• In natural languages it is often possible to assemble a sentence in more


than one correct ways.
C Programming Language
Why 'C' ?
• Because based on 'B'; developed at Bell Laboratories
• Developed by Dennis Ritchie at Bell Laboratories in the
1960s
• In cooperation with Ken Thomson it was used for Unix
systems
• The C Language was only vaguely defined, not
standardized, so that almost everyone had his own
perception of it, to such an extend that an urgent need for
a standard code was creeping up
A Simple Program in C
#include <stdio.h>
standard Library, input-output, header-file
#include <stdlib.h>
Beginning of program

int main()
Start of Segment
{ Function for printing text

printf("Hello world!\n");
return 0; End of statement

} Insert a new line

End of Segment
Preprocessor Directives
• A C program begins with # which provides an instruction to the C
preprocessor
• It is executed before the actual compilation is done.
• Two most common directives :
• #include
• #define
• In our example (#include<stdio.h>) identifies the header
file for standard input and output operations.
Function main()
• Identify the start of the program
• Every C program has a main( )
• 'main' is a C keyword. We must not use it for any other
purpose.
• 4 common ways of main declaration

int main(void) void main(void) main(void) main( )


{ { { {

return 0;
} } } }
The curly braces { }
• Identify a segment / body of a program
• The start and end of a function
• The start and end of the selection or repetition block.
• Since the opening brace indicates the start of a segment
with the closing brace indicating the end of a segment,
there must be just as many opening braces as closing
braces (this is a common mistake of beginners)
Statement
• Specifying an action to be taken by the computer as the program
executes.
• Each statement in C needs to be terminated with semicolon (;)
• Example:
#include <stdio.h>
int main()
{
printf(“I love programming\n”); statement
printf(“You will love it too once ”); statement
printf(“you know the trick\n”); statement
return 0; statement

}
Statement
• Statement has two parts :
• Declaration
• The part of the program that tells the compiler the names of memory
cells in a program
• Executable statements
• Program lines that are converted to machine language instructions and
executed by the computer
An Example
/*
Converts distance in miles
to kilometres.
*/
#include <stdio.h> //printf, scanf definitions
#define KMS_PER_MILE 1.609 //conversion constant

int main(void) {
float miles, // input – distance in miles
kms; // output – distance in kilometres
miles = 10.5;
//Convert the distance to kilometres
kms = KMS_PER_MILE * miles;

//Display the distance in kilometres


printf("That equals %f km.\n", kms);

return 0;
}

Why scanf()
Programmer vs User
An Example
/*
Converts distance in miles
to kilometres.
*/
#include <stdio.h> //printf, scanf definitions
#define KMS_PER_MILE 1.609 //conversion constant

int main(void) {
float miles, // input – distance in miles
kms; // output – distance in kilometres

//Get the distance in miles


printf("Enter distance in miles: ");
scanf("%f", &miles);

//Convert the distance to kilometres


kms = KMS_PER_MILE * miles;

//Display the distance in kilometres


printf("That equals %f km.\n", kms);

return 0;
}
An Example
/*
Converts distance in miles
to kilometres.
*/ standard header file
preprocessor #include <stdio.h> //printf, scanf definitions
directives #define KMS_PER_MILE 1.609 //conversion constant
constant
int main(void) {
float miles, // input – distance in miles
reserved kms; // output – distance in kilometres
words
//Get the distance in miles
variables printf("Enter distance in miles: "); comments
scanf("%f", &miles);

functions //Convert the distance to kilometres


kms = KMS_PER_MILE * miles;
special //Display the distance in kilometres
symbols printf("That equals %f km.\n", kms);

return 0;
} punctuations
An Example
/*
Converts distance in miles
to kilometres.
*/
#include <stdio.h> //printf, scanf definitions
#define KMS_PER_MILE 1.609 //conversion constant

int main(void) {
float miles, // input – distance in miles
declarations
kms; // output – distance in kilometres

//Get the distance in miles


printf("Enter distance in miles: ");
scanf("%f", &miles);

//Convert the distance to kilometres


kms = KMS_PER_MILE * miles;

//Display the distance in kilometres Executable


printf("That equals %f km.\n", kms); statements

return 0;
}
An Example
/*
Converts distance in miles
to kilometres.
*/
#include <stdio.h> //printf, scanf definitions
#define KMS_PER_MILE 1.609 //conversion constant

int main(void) {
float miles, // input – distance in miles
kms; // output – distance in kilometres

//Get the distance in miles


printf("Enter distance in miles: ");
scanf("%f", &miles);

//Convert the distance to kilometres


kms = KMS_PER_MILE * miles;

//Display the distance in kilometres


printf("That equals %f km.\n", kms);

return 0; Sample Run


} Enter distance in miles: 10.5
That equals 16.89 km.
An Example
 What happens in the computer memory?

memory memory memory

MileToKm.exe MileToKm.exe MileToKm.exe

miles miles miles


? 10.5 10.5

kms kms kms


? ? 16.89

At the beginning After user enters: After this line is


Do not assume that
uninitialised variables 10.5 to executed:
contain zero! (Very
common mistake.) scanf("%f", &miles); kms = KMS_PER_MILE * miles;
Variables
• Variable  a name associated with a memory cell whose value can
change
• Variable Declaration: specifies the type of a variable
• Example: int num;
• Variable Definition: assigning a value to the declared variable
• Example: num = 5;
Identifiers
Basic Data Types
• There are 4 basic data types :
• int // 4 bytes
• float // 4 bytes
• double // 8 bytes
• char // 1 bytes
• int
• used to declare numeric program variables of integer type
• whole numbers, positive and negative
• keyword: int
int number;
number = 12;
….

number = 7;
Basic Data Types
• float
• fractional parts, positive and negative
• keyword: float
float height;
height = 1.72;
• double
• used to declare floating point variable of higher precision or higher range
of numbers
• exponential numbers, positive and negative
• keyword: double
double valuebig;
• valuebig = 12E-3; (is equal to 12X10-3)
Basic Data Types
• char
• A single symbol that can be typed using the keyboard
• Example of characters:
• Numeric digits: 0 - 9
• Lowercase/uppercase letters: a - z and A - Z
• Space (blank)
• Special characters: , . ; ? “ / ( ) [ ] { } * & % ^ < >
etc
• single character
• keyword: char The declared character must be
char d; enclosed within a single quote!
d = 128;
• In addition, there are void, short, long, etc.

• Extended ASCII (American Standard Code for Information


Interchange) represents both control characters and
printable characters.
Data types (summary)
Type Storage Value range Precision
size

char 1 byte -128 to 127 or 0 to 255 n/a

-2,147,483,648 to n/a
int 4 bytes 2,147,483,647

unsigned 4 bytes 0 to 4,294,967,295 n/a


int

float 4 byte 1.2E-38 to 3.4E+38 6 decimal places

double 8 byte 2.3E-308 to 1.7E+308 15 decimal places

Here unsigned is a modifier; a modifier is a C keyword that can be used in front


of a data type to modify the behavior of that data type
A closer look at variables

Memory

26
A closer look at variables

int a = 139, b = -5;

Memory

27
A closer look at variables

int a = 139, b = -5;

Memory

a 139

b -5

28
A closer look at variables

int a = 139, b = -5;

Memory

a 139

b -5

0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 1 0 1 132 bits

29
A closer look at variables

int a = 139, b = -5;

Memory

a 139

b -5

1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 1 132 bits
30
 ------------------------------------ 2’s complement of 5 ------------------------
A closer look at variables
char c = ‘H’;

0 1 0 0 1 0 0 0 8 bits
A closer look at variables
char c = ‘H’;

0 1 0 0 1 0 0 0 8 bits

?
A closer look at variables
char c = 0x2A;//stores (00101010)2=(2A)16

0 1 0 0 1 0 0 0 8 bits

?
10010002 = 7210
Input/Output Operations
• Input operation
• an instruction that copies data from an input device into
memory
• Output operation
• an instruction that displays information stored in memory to
the output devices (such as the monitor screen)
Input/Output Functions
• A C function that performs an input or output operation
• A few functions that are pre-defined in the header file
stdio.h such as :
• printf()
• scanf() #include <stdio.h>
• getchar() & putchar()
int main () {
char c;
printf("Enter character: ");
c = getchar();
printf("Character entered: ");
putchar(c);
return(0);
}
Output:
Enter character: a
Character entered: a
The printf function
• Used to send data to the standard output (usually the monitor) to
be printed according to specific format.
• General format:
• printf(“string literal”);
• A sequence of any number of characters surrounded by
double quotation marks.
• printf(“format string”, variables);
• Format string is a combination of text, conversion specifier
and escape sequence.
The printf function

• Example:
• printf(“Thank you”);
• printf (“Total sum is: %d\n”, sum);
• %d is a placeholder (conversion specifier)
• marks the display position for a type
integer variable
• \n is an escape sequence
• moves the cursor to the new line
Placeholder / Conversion Specifier
No Conversion Output Type Output Example
Specifier
1 %d Signed decimal integer -76
2 %i Signed decimal integer 76
3 %o Unsigned octal integer 134
4 %u Unsigned decimal integer 76
5 %x Unsigned hexadecimal (small letter) 9c
6 %X Unsigned hexadecimal (capital letter) 9C
7 %f Integer including decimal point 76.0000
8 %e Signed floating point (using e 7.6000e+01
notation)
9 %E Signed floating point (using E 7.6000E+01
notation)
10 %g The shorter between %f and %e 76
11 %G The shorter between %f and %E 76
12 %c Character ‘7’
13 %s String “76”
Escape Sequence
Escape Sequence Effect
\a Beep sound
\b Backspace
\n New line
\t Tab
\v Vertical tab
\\ Backslash
\” “ sign
Formatting output
int meters = 21, feet = 68 , inches =
11;
printf("Results:%3d meters=%4d ft.%2d
in.\n", meters, feet, inches);

R e s u l t s : 2 1 m e t e r s = 6 8 f t . 1 1 i n .

printf("Results:%03d meters=%04d ft.%02d


in.\n", meters, feet, inches);
R e s u l t s : 0 2 1 m e t e r s = 0 0 6 8 f t . 1 1 i n .
Formatting output
Formatting output
• Displaying x Using Format String Placeholder %6.2f

• printf(“%6.2f”,x);
The scanf function
• Read data from the standard input device (usually keyboard) and
store it in a variable.
• General format:
• scanf(“Format string”, &variable);
• Notice ampersand (&) operator :
• C address of operator
• it passes the address of the variable instead of the variable
itself
• tells the scanf() where (in the RAM) to find the variable to store
the new value
The scanf function
• Example :
int age;
printf(“Enter your age: “);
scanf(“%d”, &age);

• Common Conversion specifier used in printf and scanf


functions.

printf scanf
int %d %d
float %f %f
double %lf %lf
char %c %c
string %s %s
The scanf function

• If you want the user to enter more than one value, you
serialize the inputs.
• Example:
float height, weight;

printf(“Please enter your height and weight:”);


scanf(“%f%f”, &height, &weight);
Expressions
 An expression is any valid set of literals, variables,
operators, operands and expressions that evaluates to
a single value.
 This value can be a number, a string or a logical value.
 For instance a = b + c; denotes an expression in which
there are 3 operands a, b, c and two operator + and =.
 The number of operands of an operator is called its
arity.
 Based on arity, operators are classified as nullary (no
operands), unary (1 operand), binary (2 operands),
ternary (3 operands).
Arithmetic Operators

Operation Operator Example Value of


(a=5,b=3) expression
Addition + a+b 8
Subtraction - b-a -2
Multiplication * a*b 15
Integer / a/b 1
Division
Modulus % a%b 2
Division / a*1.0/b 1.666666
Arithmetic Operators
• If both of the operands are int types, then the result
of the expression is an int too. If you want the result
to be any other type, you have to use typecasting.

int a = 3, b = 5;
double c;

c = 1/5; //value of c is 0.0


c = 1.0/5; //value of c is 0.2
c = a/b; //value of c is 0.0
c = (double)a/b; //value of c is 0.6

• modulus (%) operators works only when both of its


operands are int variables/values.
Assignment Operators
• Assignment operators are used to combine the '='
operator with one of the binary arithmetic operators
• In the following table, assume that c = 9 for all the
examples
Operator Example Equivalent Value of c is
Statement
+= c += 7 c = c + 7 16
-= c -= 8 c = c – 8 1
*= c *= 10 c = c * 10 90
/= c /= 5 c = c / 5 1
%= c %= 5 c = c % 5 4
Unary Operators

C Operation Operator Example


Positive + a = +3;
Negative - b = -a;

• The first assigns positive 3 to a.


• The second assigns the negative value of a to b.
Operator Precedence
• When an expression contains more than one operator,
the meaning of the expression may not be immediately
clear:
Does i + j * k mean (i + j) * k or
i + (j * k) ?

• In C, this potential ambiguity is resolved by operator


precedence.

• Precedence of the arithmetic operators:

Highest: + - (unary)
* / %
Lowest: + - (binary)
Operator Precedence
• Examples:

i + j * k means i + (j * k)
-i * -j means (-i) * (-j)
+i + j / k means (+i) + (j / k)
Associativity
• Operator precedence rules alone aren’t enough when an
expression contains two or more operators at the same level
of precedence. The associativity of the operators now comes
into play.

• The binary arithmetic operators are all left associative (they


group from left to right); the unary operators are right
associative.

• Examples of associativity:

i - j - k means (i - j) - k
i * j / k means (i * j) / k
i - j * i + k means (i - (j * i)) + k
- - i means -(-i) right associative
Increment and Decrement
Operators
• The ++ and -- operators increment and decrement variables.
• Both operators have the same precedence as negation.
• Either operator can be prefix or postfix:
++i (same as i = i + 1)
i++ (same as i = i + 1)
--i (same as i = i - 1)
i-- (same as i = i - 1)
• When used as a prefix operator, ++ increments the variable
before its value is fetched:
i = 1;
printf("i is %d\n", ++i); /* prints "i is 2" */
Increment and Decrement
Operators
• When used as a postfix operator, ++ increments the variable
after its value is fetched:
i = 1;
printf("i is %d\n", i++); /* prints "i is 1" */
printf("i is %d\n", i); /* prints "i is 2" */

• The -- operator has similar properties:


i = 1;
printf("i is %d\n", --i); /* prints "i is 0" */

i = 1;
printf("i is %d\n", i--); /* prints "i is 1" */
printf("i is %d\n", i); /* prints "i is 0" */
Increment and Decrement
Operators
int R = 10, count=10;

Statement Equivalent R value Count


Statements value
R = count++; R = count;
count = count + 1; 10 11
R = ++count; count = count + 1;
R = count; 11 11
R = count --; R = count;
count = count – 1; 10 9
R = --count; Count = count – 1;
R = count; 9 9
Partial List of C Operators
Precedence Operator Associativity
2 ++ (prefix) Right
-- (prefix)
+ (unary)
- (unary)
3 * Left
/
%
4 + Left
-
5 = *= /= %= += -= Right
6 ++ (postfix) Left
-- (postfix)
Programming Exercise
•Try to predict the output of the following program and see if you can
get it right.
#include <stdio.h>
int main()
{
int x = 3;
printf("%d\n", 3 -2 / 4);
printf("%f\n", 3 -2.0 / 4);
printf("%d\n", -27 / -5 + 4 / 3);
printf("%d\n", 16 % -5 + 7 * 6);

printf("%d\n", -12 * 3 % 5 * -23 / +6 - 5 * 2);

printf("%d\n", x-- * 2 + 5);


printf("%d\n", x);
printf("%d\n", --x * 2 + 5);

printf("%d\n", 3 % 5 / (5 % 3));
return 0;
}
Bitwise Operators
• OR vs XOR & bitwise AND
• Students who have
| bitwise OR
completed CSE115 or
Mat116 can take CSE173. ^ bitwise XOR
• Soup or salad comes with Exclusive-OR
this entrée ~ 1’s compliment
<< Shift left
>> Shift right
All these operators (except ~) can be
suffixed with =
For instance, a &= b; is the same as
a = a & b;
Bitwise Operators
• Truth table

~a a^b a|b a&b b a

1 0 0 0 0 0

1 1 1 0 1 0

0 1 1 0 0 1

0 0 1 1 1 1
Bitwise Operators
• Examples

11010011 11010011 11010011


& | ^
10001100 10001100 10001100
------------ ------------ ------------
10000000 11011111 01011111

~11010011
------------
00101100
Bitwise Operators
• Examples: int a = 33333, b = -77777;

Expression Representation Value


a 00000000 00000000 10000010 00110101 33333
b 11111111 11111110 11010000 00101111 -77777
a&b 00000000 00000000 10000000 00100101 32805
a^b 11111111 11111110 01010010 00011010 -110054
a|b 11111111 11111110 11010010 00111111 -77249
~(a|b) 00000000 00000001 00101101 11000000 77248
~a&~b 00000000 00000001 00101101 11000000 77248
Bitwise Operators
• Examples
(211)10

11010011>>3 11010011<<3
------------ ------------
Right 00011010 left 10011000

211/23=26 211x23 = 1688 = 11010011000


Bitwise Operators
char c = 130;
unsigned int b = 1 << 31;

Expressio Representation Action


n
c 10111100 unshifted
c << 4 11000000 left shifted 4
c >> 4 00001011 right shifted 4
b 10000000 00000000 00000000 00000000 unshifted
b >> 3 00010000 00000000 00000000 00000000 right shifted 3
Suggested reading
• Bitwise
• https://www.guru99.com/c-bitwise-operators.html
• https://www.programiz.com/c-programming/bitwise-operators
• Book
• Chapter 2
• Problem Solving and Program Design in C-Addison-Wesley
(Eight Edition)
• Jeri R. Hanly, Elliot B. Koffman
Practice
• Write a program that calculates the area and the perimeter of a rectangle where
the length and the width of the rectangle are provided by the user as inputs.
• Write a program that calculates the area of a triangle where the base and the
height of the triangle are provided by the user as inputs.
• Write a program that calculates the area and the perimeter of a circle where the
radius of the circle is provided by the user as input.
• Write a program that calculates the volume and surface area of a flat washer
where the height, outer diameter (), the inner diameter () and height (h) are
provided by the user as input.

𝑑2
𝑑1

• Write a program that accepts a character (small letter) as input from the user
and (a) converts it into uppercase letter and (b) shows its binary equivalent. For
example if the user input is ‘b’ then your output is ‘B’ and 01100010 (ASCII code
of ‘b’ is 98 and binary equivalent of 98 is 01100010)

You might also like