0% found this document useful (0 votes)
47 views83 pages

CSE109 Week1-2

The document provides an introduction to the C programming language. It covers topics like why C is used, its history and creator Dennis Ritchie, the basic structure of a C program including main functions and header files, and basic programming concepts like variables, data types, and global versus local variables. The document is part of a lecture series on C for undergraduate students.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
47 views83 pages

CSE109 Week1-2

The document provides an introduction to the C programming language. It covers topics like why C is used, its history and creator Dennis Ritchie, the basic structure of a C program including main functions and header files, and basic programming concepts like variables, data types, and global versus local variables. The document is part of a lecture series on C for undergraduate students.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 83

Introduction to C

Lecture: 1 - 5
Reference Book: Teach yourself C
Chapter/Section: 1.1-1.7, 1.10, 2.5-2.7, 4.1, 4.2,
4.4-4.7, 8.4, 8.5, 11.3, 11.5, 11.8-11.10

Shadman Saqib Eusuf


Lecturer, CSE, BUET
1 CSE 109
Presentation Acknowledgement

Prepared & Edited by:


Johra Muhammad Moosa,
Md. Aashikur Rahman Azim
Assistant Professor
Department of Computer Science & Engineering
Bangladesh University of Engineering & Technology

2 CSE 109
Why You Need a Programming Language?
To communicate with a machine/computer
Robotics
Microcontrollers: automobiles and airplanes
Embedded processors: phones, portable electronics, etc.
DSP (Digital Signal Processing) processors: digital audio
and TV systems

3 CSE 109
About C
Invented and first implemented by Dennis Ritchie
Middle level language
Structured and disciplined approach to computer program
ANSI (American National Standards Institute) approved a
standard in 1989

4 CSE 109
Dennis Ritchie

5 CSE 109
A First Look at C
header file
return type

function
start of program

statement

parameter

end of program

Library function
6 CSE 109
A First Look at C
# include <stdio.h>
int main(void)
{
printf(“This is a short C program”);
return 0;
}

# include
• # symbol indicates a preprocessor
• It means it has to be done before compilation
• #include to include the contents of the header file

7 CSE 109
A First Look at C
# include <stdio.h>
int main(void)
{
printf(“This is a short C program”);
return 0;
}

<stdio.h>
• Name of the header file
• Header files: constants, functions, other declarations
• You must know which header you need
• Use help and documentation to find out
8 CSE 109
A First Look at C
# include <stdio.h>
int main(void)
{
printf(“This is a short C program”);
return 0;
}

<stdio.h>
• Enclosed in < > (header in default place)
• May be enclosed in “ ” (header is in the same folder as the source)
• stdio.h : standard input/output header file
• Needed for the function: printf()
9 CSE 109
A First Look at C
# include <stdio.h>
int main(void)
{
printf(“This is a short C program”);
return 0;
}

main
• Every C program must have a ‘main’ function
• Program starts from the 1st line in ‘main’
• Parameter type void
• Return type int
10• int CSE
main()
109
A First Look at C
# include <stdio.h>
int main(void)
{
printf(“This is a short C program”);
return 0;
}
{ } curly braces
• The curly braces are like containers
• The code between two braces are called a block
• Missing either brace will generate compile error
• “Compound Statement missing”

11 CSE 109
A First Look at C
# include <stdio.h>
int main(void)
{
printf(“This is a short C program”);
return 0;
}
{ } curly braces
• Left curly brace {
• Begin the body of function
• Right Curly brace }
• End of the function

12 CSE 109
A First Look at C
# include <stdio.h>
int main(void)
{
printf(“This is a short C program”);
return 0;
}

printf
• A function given in stdio.h
• Prints the text given as the parameter

13 CSE 109
A First Look at C
# include <stdio.h>
int main(void)
{
printf(“This is a short C program”) ;
return 0;
}

; (semicolon)
• Every C statement must end with a ;
• Otherwise compiler will generate an error
• Statement Missing

14 CSE 109
A First Look at C
# include <stdio.h>
int main(void)
{
printf(“This is a short C program”);
return 0;
}
return 0
• Indicate how the program exited
• return 0 means that execution was successful and there was no error.
• abnormal termination is usually signaled by a non-zero return
• but there is no standard for how non-zero codes are interpreted.
• When a program is called by another program
15 CSE 109
Basic Structure of a C Program
Function
Building Block
Named subroutine
 Can be called by other parts of the program
May contain more than one functions
One of which must be main()
 Where execution begins

Standard library
 Provides library functions
 Example: I/O operation, string, math … etc

16 CSE 109
Basic Structure of a C Program
 Header file
.h extension
Add header file using #include (preprocessor directive)
 Statement
Action performed by the program
Perform operations
End with a semicolon (;)
Two or more statements can be placed on a single line
 Case sensitive
Main & main are different
 Indentation
Not a programming decision

17 CSE 109
A first look at C

18 CSE 109
Programming Tools
Compiler
Standard Library
Help files & documentations
IDE

19 CSE 109
Compilers
What does it do?
Match syntax
Find Errors
Prepare object code
 instructions in a computer language, usually a machine code

20 CSE 109
Standard Library
What does it do?
Provide implementations of some basic and important
functions
Usually these functions are very efficient
Programmers should use library functions to improve
performance and portability

21 CSE 109
IDE - Integrated Development Environment
Helps to Write
Use different color to highlight different type of code
Sometimes shows hints
Helps to Compile
Set environment variables
Linking with libraries
Helps to Run
Helps to Debug
Execute step by step
Use breaks
Watch the values of variables
22 CSE 109
Help Files and Documentation
Provide details about
Syntax
Keywords
Library functions
Examples
Etc.

23 CSE 109
Lifecycle of a C Program
User defined Standard
Source Header File Header File
File
Compile Compile
Compile
Link
Library File
Object File

Executable
File
24 CSE 109
Keywords
C has some words that has a special meaning for the
compiler
These words can not be used to name variables, functions
etc.auto double int struct
break else long switch
case enum register typedef
char extern return union
const float short unsigned
continue for signed void
default goto sizeof volatile
do if static while
25 CSE 109
Variables
Variables are placeholders
They can hold values
Each variable takes up some memory space
The values can be assigned, changed, read etc.
Variables must be defined before using them

26 CSE 109
Variable Declaration
First write the keyword for datatype
Then write the name of the variable
Example
int num=10;
char c=‘a’;
int i, j, k;
char esc=‘\\’;
float exp=3.2e-5;

27 CSE 109
Variables
Name of variable
Case sensitive
 Count, count & COUNT are different
Can be of any length, but only first 31 characters are important
Can contain letters, digits and the ‘_’
But first character must be a letter or ‘_’
Variable name cannot be same as a keyword
For example –
correct: abcd, abcd2, abcd_3, Abcd
incorrect: ab cd, 2abcd, abcd…3, ab!cd

28 CSE 109
Variables
Name of variable
Should be clear and meaningful
If two or more words are needed then either separate them
using a ‘_’ or keep them together, but start each word except
the first one with a capital
For Example –
student_no average_age
dateOfBirth averageAge
Second way is recommended

29 CSE 109
Variables
Global variables
Outside all function
Can be accessed by any function
Local variables/ automatic variables
Inside a block/function
Can be declared at the start of a block

30 CSE 109
Global Variable
# include <stdio.h>
int a; Global variable
int main(void)
{
a=5;
printf(“This is a short C program”);
return 0;
}
• Global Variable
Outside all function
Can be accessed by any function

31 CSE 109
Local Variable
# include <stdio.h>
int main(void)
{
int a; Local variable
a=5;
printf(“This is a short C program”);
return 0;
}
Local variables/ automatic variables
Inside a block/function

32 CSE 109
Datatypes
C has basically these data types-
 int (integer / whole number)
 float (floating point / fraction)
 double (double precision float)
 char (character)
 void (empty / no value )
 enum (enumeration)

33 CSE 109
Datatypes
Datatype Size Range
unsigned char 8 bits 0 to 255
char 8 bits -128 to 127
enum 16 bits -32,768 to 32,767
unsigned int 16 bits 0 to 65,535
short int 16 bits -32,768 to 32,767
int 16 bits -32,768 to 32,767
unsigned long 32 bits 0 to 4,294,967,295
long 32 bits -2,147,483,648 to 2,147,483,647
float 32 bits 3.4 * (10**-38) to 3.4 * (10**+38)
double 64 bits 1.7 * (10**-308) to 1.7 * (10**+308)
long double 80 bits 3.4 * (10**-4932) to 1.1 * (10**+4932)
34 CSE 109
Float vs. Double
Single precision (float) gives you 23 bits of significant, 8
bits of exponent, and 1 sign bit.
Double precision (double) gives you 52 bits of significant,
11 bits of exponent, and 1 sign bit.

35 CSE 109
Printing Variables
#include <stdio.h>

int main(void)
{
int num=10;
printf("num=%d", num);
return 0;
}

36 CSE 109
Conversion Specifiers
Integer: %d
Character : %c
Float : %f
Double : %lf

37 CSE 109
Details on printf (sec 8.5)
%% : prints % sign
%i : signed decimal integer
%x : unsigned hexadecimal number
%e : scientific notation
%p: displays a pointer
etc.

38 CSE 109
Details on printf (sec 2.6)
\n : newline
\t: horizontal tab
\\: backslash
etc

39 CSE 109
Format Specifier
printf ("Preceding with blanks: %10d \n", 1977);
print as a decimal integer with a width of at least 10 wide with
space padded to left
printf ("Preceding with zeros: %010d \n", 1977);
print as a decimal integer with a width of at least 10 wide with
zero padded to left
printf("%3.2f\n",d);

40 CSE 109
Details on printf (sec 8.5)
#include<stdio.h>
#define AREA length*width

int main(void)
{
printf("%d %o %x %X\n", 90, 90, 90, 90);
printf("%e %E\n", 99.231, 99.231);
return 0;
}

Output:
90 132 5a 5A
9.92310e+01 9.92310E+01
41 CSE 109
Details on printf (sec 8.5)
#include<stdio.h>
#define AREA length*width
Alphabets in the number representation will be shown in capital letter

int main(void)
{
printf("%d %o %x %X\n", 90, 90, 90, 90);
printf("%e %E\n", 99.231, 99.231);
return 0;
}

Output:
90 132 5a 5A
9.92310e+01 9.92310E+01
42 CSE 109
Details on printf (sec 8.5)
#include <stdio.h>

int main() {
printf ("Characters: %c %c \n", 'a', 65);
printf ("Decimals: %d %ld\n", 1977, 650000L);
printf ("Preceding with blanks: %10d \n", 1977);
printf ("Preceding with zeros: %010d \n", 1977);
printf ("Some different radices: %d %x %o %#x %#o \n", 100, 100, 100, 100,
100);
printf ("floats: %4.2f %+.0e %E \n", 3.1416, 3.1416, 3.1416);
printf ("Width trick: %*d \n", 5, 10);
printf ("%s \n", "A string");
return 0;
}
43 CSE 109
Input Numbers from Keyboard
#include <stdio.h>

int main(void) & (ampersand) :


ADDRESS
{
OPERATOR
int num;
scanf("%d", &num);
printf("num=%d", num);
return 0;
}

44 CSE 109
Input Multiple Numbers from Keyboard
#include <stdio.h>

int main(void)
{
int num1, num2;
scanf("%d %d", &num1, &num2);
printf("num=%d", num1+num2);
return 0;
}
 Input must be seperated by blank, tab or newline
 Common programming error:
Forgetting address operator (&) before variable name in scanf
 Placing
CSE 109 commas (when none are needed) between conversion specifiers
45
Expressions
Combination of operators and operands
Appear on the right side of an assignment statement

46 CSE 109
Operators
Depending on the number of operand, operators can be-
Unary (-a)
Binary (a-b)
Ternary (later)
Depending on the functionality, operators can be-
Arithmetic
Bitwise
Assignment
Relational
Logical
Others
Operators containing two symbols can not be separated by space.

47 CSE 109
Arithmetic Operators
Sign Meaning Type Comments
+ Plus Binary
- Minus Binary
* Multiply Binary
/ Division Binary
% Modulus Binary Operators can
only be
integer
++ Increment Unary
-- Decrement Unary
- Unary Unary
48 CSE 109 negation
Example
count=count*num+88/val-19%count;
char x,y;
x=‘a’;
y=‘b’;
int z=x+y;

49 CSE 109
Increment and Decrement Operator
Postfix operator
n++, n--
Prefix operator
++n, --n

50 CSE 109
Bitwise Operators
These operators are used for bitwise logic operations.
The operands must be integer values

‘&’ bitwise AND binary


‘^’ bitwise XOR binary
‘|’ bitwise OR binary
‘~’ 1’s complement unary
‘!’ bitwise NOT unary
‘<<’ left shift binary
‘>>’ right shift binary
51 CSE 109
Bitwise Operator (sec 11.5)
Operator Description Example
& Bitwise AND 101 & 110 = 100
| Bitwise OR 100 & 001 = 101
^ Bitwise XOR (exclusive 110 & 101 = 011
OR)
~ 1’s complement ~100 = 011

52 CSE 109
Bitwise Operator (AND)

a b a&b
0 0 0
0 1 0
1 0 0
1 1 1

53 CSE 109
Bitwise Operator (OR)

a b a|b
0 0 0
0 1 1
1 0 1
1 1 1

54 CSE 109
Bitwise Operator (XOR)

a b a^b
0 0 0
0 1 1
1 0 1
1 1 0

55 CSE 109
Bitwise Operator (to be taught later)
#include<stdio.h>
# include<conio.h> Loop Bit pattern
int main(void) counter
{ 128 10000000
char ch; 64 01000000
int i; 32 00100000
ch=getche(); 16 00010000
printf("\n");
8 00001000
for(i=128; i>0; i=i/2)
4 00000100
if(i & ch) printf("1 ");
else printf("0 "); 2 00000010
return 0; 1 00000001
}
56 CSE 109
Assignment Operators (sec 11.8)
These operators assign the value of the expression on
the right to the variable on the left

‘=’ assign binary

Shortcuts
a += b; means a = a + b;
‘+=’, ‘- =’, ‘*=’, ‘/=’, ‘%=’,
‘&=’, ‘|=’, ‘^=’, ‘<<=’, ‘>>=’
57 CSE 109
Relational Operators
These operators are used for comparison. The
result is boolean.

‘<’ less than binary


‘>’ greater than binary
‘<=’ less/equal binary
‘>=’ greater/equal binary
‘==’ equal binary
‘!=’ not equal binary
58 CSE 109
Logical Operators
These operators are evaluating logical expressions.
The result is boolean

‘&&’ logical AND binary


‘||’ logical OR binary
‘!’ logical NOT unary

59 CSE 109
Operator Precedence
If there are a chain of operations, then C defines which of
them will be applied first.
*, / and % are higher in precedence that + and -
Precedence can be altered by using parentheses
Innermost parentheses evaluated first
For example-
6+4/2 is 8
 because ‘/’ has precedence over ‘+’
 if we want the ‘+’ to work first, we should write-
(6+4)/2

60 CSE 109
Precedence Chart (sec 11.10)
! ~ ++ -- + -
* / %
+ -
<< >>
< <= > >=
== !=
&
^
|
&&
||
= += -= *= /= %= &= |= ^=
61 CSE 109
Example
Stepwise evaluation of the expression x=7/6*4+3/5+3
x=7/6*4+3/8+3
x=1*4+3/5+3 operation: /
x=4+3/5+3 operation: *
x=4+0+3 operation: /
x=4+3 operation: +
x=7 operation: +
All the operators associate from left to right except for
assignment operators

62 CSE 109
Example
Determining difference between two persons’ height

#include<stdio.h>
int main ()
{
int f1, i1, f2, i2, f3, i3, d;
printf("Enter height (feet,inches) of person one: ");
scanf("%d,%d", &f1, &i1);
printf("Enter height (feet,inches) of person two: ");
scanf("%d,%d", &f2, &i2);
d=(f1*12+i1)-(f2*12+i2);
f3=d/12;
i3=d%12;
printf("Difference between height is %d feet, %d inches\n", f3, i3);
63 CSEreturn
109 0;
Type Conversion (sec 4.5, 4.6)
C allows mixing of types
Integral promotion
During evaluation of an expression
‘A’+2
Type promotion
Converts all operands “up” to the type of the largest

64 CSE 109
Type Conversion
Operands that differ in type may undergo type conversion
In general the result will be expressed in the highest
precision possible
int i=7;
float f=5.5;

i+f : 12.5

65 CSE 109
Type Conversion (sec 4.5, 4.6)
#include <stdio.h>

int main() {
int i;
float f;

i=10;
f=23.25;

printf ("%f \n", i*f);


return 0;
}
66 CSE 109
Type Conversion in assignment (sec 4.6)
 Type of right side is converted to the type of the left

#include <stdio.h>
int main() {
int i;
char c; Output:
i=1111; W, 87
c=i;
printf ("%d, %c \n", c, c);
return 0;
}
67 CSE 109
Type Conversion (sec 4.5, 4.6)
Loss of precision
#include <stdio.h>

int main() {
double f;
f=7/2;
printf ("%lf \n", f);
return 0;
}
68 CSE 109
Type Cast (sec 4.7)
#include <stdio.h>

int main() {
double f;
f=7/2.0;
printf ("%lf \n", f);
return 0;
}

69 CSE 109
Type Cast (sec 4.7)
#include <stdio.h>

int main() {
double f;
f=7.0/2;
printf ("%lf \n", f);
return 0;
}

70 CSE 109
Type Cast (sec 4.7)
Value of an expression can be converted to a different data
type if desired.
Temporary type change
(data type) expression

int i=7;
float f=5.5;

(i+f)%2 : error
((int)(i+f))%2

71 CSE 109
Type Cast (sec 4.7)
#include <stdio.h>

int main() {
double f;
f=(double)7/2;

printf ("%lf \n", f);


printf ("%d \n", (int)f);

return 0;
}
72 CSE 109
Type Cast (sec 4.7)
#include <stdio.h>

int main() {
double f;
f=7/(double)2;

printf ("%lf \n", f);


printf ("%d \n", (int)f);

return 0;
}
73 CSE 109
Type Cast (sec 4.7)
 Loss of precision
#include <stdio.h>

int main() {
7/2=3
double f;
(double)(7/2)=(double)(3)=3.0
f=(double)(7/2);

printf ("%lf \n", f);


printf ("%d \n", (int)f);

return 0;
}
74 CSE 109
Datatype Modifiers (sec 4.1)
Modifiers
 long
 short
 unsigned
signed
Except type void, the basic data types may have various modifiers
preceding them.
Multiple modifiers can be used in a declaration

75 CSE 109
Datatype Modifiers
Qualifiers
 const
may not be changed by your program.
can be given an initial value, however.
compiler is free to place variables of this type into read-only
memory (ROM).
 volatile
can be changed by your program and also external program
One or both modifiers can be used in a declaration

76 CSE 109
Datatypes
Example
 int
 long double
 unsigned long int
 const unsigned long int
volatile const char

77 CSE 109
Variable Declaration Example
int num=10;
char c=‘A’;
char c=65;
int i, j, k;
char esc=‘\\’;
float exp=3.2e-5;

78 CSE 109
Comments
Note for the programmer
Ignored by the compiler
Used as documentation
Can be used anywhere a space character (blank, tab/
newline) can.
Comment can be used to temporarily remove a chunk
of codes.

79 CSE 109
Comments
Two types of comments
Single line
Starts with //
Can not be spread over several lines
Not currently defined by ANSI C
Created by C++
Use in C program is technically invalid
Valid in C99
Multiline
Can not be nested
Starts with /*
Ends with */

80 CSE 109
Comments
Following program is valid
#include <stdio.h>

int main(void)
{
int num1, /*allowed! */num2;
scanf("%d %d", &num1, /*allowed
too!*/&num2);
printf("num=%d", num1+num2);
return 0;
}
81 CSE 109
Home Work
Given the radius of a circle, write a C program to calculate
it’s area.
Write a C program which convert temperature from
Fahrenheit to Celsius.
Find the values of x & n after each statement of the
following code segment:
x=n++;
x=++n;

82 CSE 109
Practice
Examples & Exercises
Mastery Skill Check
Review Skill Check

83 CSE 109

You might also like