0% found this document useful (0 votes)
18 views

Introduction to C (2)

Uploaded by

mborasydn
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views

Introduction to C (2)

Uploaded by

mborasydn
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 56

Introduction to

Programming Language C
BIL 110E

© 2007 Pearson Education, Inc. All rights reserved.


CONTACT INFORMATION

Instructor: Egnar Özdikililer

E-mail: [email protected]

© 2007 Pearson Education, Inc. All rights reserved.


COURSE INFORMATION

Text Books:
C-How-to-Program-Deitel-6Ed, H.M. Deitel and P.J. Deitel, Prentice-Hall
Inc., 2010

Web Pages:
https://www.programiz.com/c-programming#tutorial
https://www.sitesbay.com/cprogramming/index

Editor & Compiler Software:


DEV C++: https://sourceforge.net/projects/orwelldevcpp/
Code::Blocks:
http://sourceforge.net/projects/codeblocks/files/Binaries/20.03/Windows/codeb
locks-20.03-setup.exe
Online Compiler: https://replit.com/

© 2007 Pearson Education, Inc. All rights reserved.


COURSE INFORMATION

Exams and Grading:


Two midterm exams (each 20%)
Two quizzes (each 2.5%)
Two projects (15%)
One final exam (40%)

Before the final exam the sum of your midterm exam


grades should be larger than 25

Attendance: Minimum 5 weeks


Course web address http://www.ninova.itu.edu.tr

© 2007 Pearson Education, Inc. All rights reserved.


5

2
Introduction
to C Programming

© 2007 Pearson Education, Inc. All rights reserved.


6

OBJECTIVES
In this chapter you will learn:
▪ To write simple computer programs in C.
▪ To use simple input and output statements.
▪ The fundamental data types.
▪ Computer memory concepts.
▪ To use arithmetic operators.
▪ The precedence of arithmetic operators.
▪ To write simple decision-making statements.

© 2007 Pearson Education, Inc. All rights reserved.


7

2.1 Introduction
2.2 A Simple C Program: Printing a Line of Text
2.3 Another Simple C Program: Adding Two Integers
2.4 Memory Concepts
2.5 Arithmetic in C
2.6 Decision Making: Equality and Relational Operators

© 2007 Pearson Education, Inc. All rights reserved.


8

2.1 Introduction
▪ C programming language
– Structured and disciplined approach to program design
▪ Structured programming

© 2007 Pearson Education, Inc. All rights reserved.


1 /* Fig. 2.1: fig02_01.c 9
2 A first program in C */
3 #include <stdio.h>
Outline
/* and */ indicate comments – ignored by compiler
4
5 /* function main begins program execution */ #include directive tells C to load a
6 int main( void ) particular file
7 {
‘{‘ Left brace declares beginning of fig02_01.c
8 printf( "Welcome to C!\n" ); main function
9 Statement tells C to perform an
10 action
return 0; /* indicate that program ended successfully */
return statement ends the
11
12 } /* end function main */ function
‘}’ Right brace declares end of main
Welcome to C!
function

Code output

© 2007 Pearson Education,


Inc. All rights reserved.
10

2.2 A Simple C Program:


Printing a Line of Text
Comments
– Text surrounded by /* and */ is ignored by computer
– Used to describe program
▪ #include <stdio.h>
– Preprocessor directive
- Tells computer to load contents of a certain file
– <stdio.h> allows standard input/output operations

1 /* Fig. 2.1: fig02_01.c


2 A first program in C */
3 #include <stdio.h>
4
5 /* function main begins program execution */
6 int main( void )
7 {
8 printf( "Welcome to C!\n" ); © 2007 Pearson Education, Inc. All rights reserved.
11

2.2 A Simple C Program:


Printing a Line of Text
▪ int main()
– C programs contain one or more functions, exactly one of
which must be main
– Parenthesis used to indicate a function
– int means that main "returns" an integer value
– Braces ({ and }) indicate a block
- The bodies of all functions must be contained in braces
1 /* Fig. 2.1: fig02_01.c
2 A first program in C */
3 #include <stdio.h>
4
5 /* function main begins program execution */
6 int main( void )
7 {
8 printf( "Welcome to C!\n" );
9
10 return 0; /* indicate that program ended successfully */
11
12 } /* end function main */
© 2007 Pearson Education, Inc. All rights reserved.
12

2.2 A Simple C Program:


Printing a Line of Text
▪ printf( "Welcome to C!\n" );
– printf() function prints the string of characters within quotes (" ")
– Entire line is called as a statement. All statements must end with a
semicolon (;)
– Escape character (\)
- Indicates that printf should do something out of the ordinary
- \n is the newline character

Escape sequence Description

\n Newline. Position the cursor at the beginning of the next line.


\t Horizontal tab. Move the cursor to the next tab stop.
\a Alert. Sound the system bell.
\\ Backslash. Insert a backslash character in a string.
\" Double quote. Insert a double-quote character in a string.

© 2007 Pearson Education, Inc. All rights reserved.


13

2.2 A Simple C Program:


Printing a Line of Text
1 /* Fig. 2.1: fig02_01.c
2 A first program in C */
3 #include <stdio.h>
4
5 /* function main begins program execution */
6 int main( void )
7 {
8 printf( "Welcome to C!\n" );
9
10 return 0; /* indicate that program ended successfully */
11
12 } /* end function main */

Welcome to C!

▪ return 0;
– A way to exit a function
– return 0, in this case, means that the program terminated
normally. When you return 0, you tell the caller (OS in case of
main) that the status of your program was successful.

© 2007 Pearson Education, Inc. All rights reserved.


1 /* Fig. 2.3: fig02_03.c 14
2 Printing on one line with two printf statements */
3 #include <stdio.h>
Outline
4
5 /* function main begins program execution */
6 int main( void )
fig02_03.c
7 { printf statement starts printing from
8 printf( "Welcome " );
9 printf( "to C!\n" ); where the last statement ended, so the
10 text is printed on one line.
11 return 0; /* indicate that program ended successfully */
12
13 } /* end function main */

Welcome to C!

Add a comment to the line containing the


right brace, }, that closes every function,
including main.

© 2007 Pearson Education,


Inc. All rights reserved.
1 /* Fig. 2.3: fig02_03.c 15
2 Printing on one line with two printf statements */
3 #include <stdio.h>
Outline
4
5 /* function main begins program execution */
6 int main( void )
fig02_03.c
7 {
8 printf( "Welcome " );
9 printf( "to C!\n" );
10
11 return 0; /* indicate that program ended successfully */
12
13 } /* end function main */

Welcome to C!

Indent the entire body of each function (we


recommend three spaces) within the braces
that define the body of the function.

© 2007 Pearson Education,


Inc. All rights reserved.
1 /* Fig. 2.4: fig02_04.c 16
2 Printing multiple lines with a single printf */
3 #include <stdio.h>
Outline
4
5 /* function main begins program execution */
6 int main( void )
Newline characters move the cursor to the fig02_04.c
7 {
8 printf( "Welcome\nto\nC!\n" );next line
9
10 return 0; /* indicate that program ended successfully */
11
12 } /* end function main */

Welcome
to
C!

© 2007 Pearson Education,


Inc. All rights reserved.
Q1

Write a C code that prints the following shape by using one


printf statement.

* *
* *
* *
Code is:
printf ( "* *\n* *\n* *" );
Q1

Write a C code that prints the following shape by using one


printf statement. Space character is not allowed. Use tab
character to give a space between asterics (*) characters.

* *
* *
* *
Code is:
printf ( "*\t*\n*\t*\n*\t*" );
Declaring Variables
int x; // Declare x to be an
// integer variable;
float radius; // Declare radius to
// be a double variable;
char a; // Declare a to be a
// character variable;

Assignment Statements
x = 1; // Assign 1 to x;

radius = 1.8; // Assign 1.0 to radius;


a = 'A'; // Assign 'A' to a;
Declaring and Initializing
in One Step
int x = 1;
float d = 1.4;
1 /* Fig. 2.5: fig02_05.c 21
2 Addition program */
3 #include <stdio.h>
Outline
4
5 /* function main begins program execution */
6 int main( void )
fig02_05.c
7 {
8 int integer1; /* first number to be input by user */ Definitions of
9 int integer2; /* second number to be input by user */
10 int sum; /* variable in which sum will be stored */
variables
11
12 printf( "Enter first integer\n" ); /* prompt */ scanf obtains a value from the
13 scanf( "%d", &integer1 ); /* read an integer */ user and assigns it to
14
integer1
15 printf( "Enter second integer\n" ); /* prompt */
16 scanf( "%d", &integer2 ); /* read an integer */
17
18 sum = integer1 + integer2; /* assign total to sum */
19
20 printf( "Sum is %d\n", sum ); /* print sum */
Assigns a value to sum
21
22 return 0; /* indicate that program ended successfully */
23
24 } /* end function main */
scanf uses standard input which is usually
Enter first integer keyboard.
45
Enter second integer
72
Sum is 117 When the scanf command is executed the code stops
and waits for an input from the keyboard. And
assigns the input to integer1 until the enter key is
pressed. © 2007 Pearson Education,
Inc. All rights reserved.
22

2.3 Another Simple C Program:


Adding Two Integers
▪ int integer1, integer2, sum;
– Definition of variables
- Variables: locations in memory where a value can be stored
– int means the variables can hold integers (-1, 3, 0, 47)

same definition

▪ int integer1;
▪ int integer2;
▪ int sum;
– Definitions appear before executable statements
- If an executable statement references an undeclared variable it
will produce a syntax (compiler) error

© 2007 Pearson Education, Inc. All rights reserved.


23

2.3 Another Simple C Program:


Adding Two Integers
▪ int integer1, integer2, sum;
– Variable names (identifiers) consist of letters, digits
(cannot begin with a digit) and underscores( _ )
int i,j, k;
float _length, height14;

▪ Use identifiers (variable names) of 31 or fewer


characters. This helps ensure portability and can
avoid some subtle programming errors.
int integerdeneysonyeniden;

© 2007 Pearson Education, Inc. All rights reserved.


24

Good Programming Practice 2.6


Choosing meaningful variable names
helps make a program self-documenting,
i.e., fewer comments are needed.
int deneyson;

© 2007 Pearson Education, Inc. All rights reserved.


25

Good Programming Practice 2.9


Separate the definitions and executable statements in a function with one
blank line to emphasize where the definitions end and the executable
statements begin.
1 /* Fig. 2.5: fig02_05.c
2 Addition program */
3 #include <stdio.h>
4
5 /* function main begins program execution */
6 int main( void )
7 {
8 int integer1; /* first number to be input by user */
9 int integer2; /* second number to be input by user */
10 int sum; /* variable in which sum will be stored */
11
12 printf( "Enter first integer\n" ); /* prompt */
13 scanf( "%d", &integer1 ); /* read an integer */
14
15 printf( "Enter second integer\n" ); /* prompt */
16 scanf( "%d", &integer2 ); /* read an integer */
17
18 sum = integer1 + integer2; /* assign total to sum */
19
20 printf( "Sum is %d\n", sum ); /* print sum */
21
22 return 0; /* indicate that program ended successfully */
23
24 } /* end function main */

Enter first integer


45 © 2007 Pearson Education, Inc. All rights reserved.
26

2.3 Another Simple C Program:


Adding Two Integers
▪ scanf( "%d", &integer1 );
– Obtains a value from the user
- scanf uses standard input (usually keyboard)
– This scanf statement has two arguments
- %d - indicates data should be a decimal integer
- &integer1 - location in memory to store variable

– When the scanf command is executed the code stops and


waits for an input from the keyboard.
– The user responds to the scanf statement by typing in a
number, then pressing the enter (return) key

© 2007 Pearson Education, Inc. All rights reserved.


27

Good Programming Practice 2.10


Place a space after each comma (,) to
make programs more readable.

scanf( "%d", &integer1 );

© 2007 Pearson Education, Inc. All rights reserved.


28

2.3 Another Simple C Program:


Adding Two Integers
sum = variable1 + variable2;

= is assignment operator. Assigns a value to a


variable. The sum of variable1 + variable2 is assigned
to sum.

© 2007 Pearson Education, Inc. All rights reserved.


29

2.3 Another Simple C Program:


Adding Two Integers
sum = variable1 + variable2;

A binary-operator operates on two operands and


manipulates them to return a result.

‘sum’ and ‘ variable1 + variable2’


are two operands of ’=’ in this example.

‘variable1’ and ’ variable2’


are two operands of ’+’ in this example.

© 2007 Pearson Education, Inc. All rights reserved.


30

2.3 Another Simple C Program:


Adding Two Integers
▪ printf( "Sum is %d\n", sum );

The value of sum will be printed in place of %d

– Similar to scanf
- %d means decimal integer will be printed
- sum specifies what integer will be printed
– Calculations can be performed inside printf
statements
printf("Sum is %d\n", integer1 +
integer2);

© 2007 Pearson Education, Inc. All rights reserved.


31

Good Programming Practice 2.11


Place spaces on either side of a binary
operator. This makes the operator stand
out and makes the program more readable.
sum = variable1 + variable2;

spaces

© 2007 Pearson Education, Inc. All rights reserved.


32

Common Programming Error 2.6


A calculation in an assignment statement
must be on the right side of the = operator.
It is a syntax error to place a calculation on
the left side of an assignment operator.
sum = variable1 + variable2;
variable1 + variable2 = sum causes syntax error

© 2007 Pearson Education, Inc. All rights reserved.


33

2.4 Memory Concepts


▪ Variables
– Variable names correspond to locations in the computer's memory
– Every variable has a name, a type, a size and a value
– Whenever a new value is placed into a variable (through scanf, for
example), it replaces (and destroys) the previous value
– Reading variables from memory does not change them

int integer1;
interger1 = 45;
After executing the above statement

Fig. 2.6 | Memory location showing the name and value of a variable.

© 2007 Pearson Education, Inc. All rights reserved.


34

interger1 = 45;
interger2 = 72;

After executing the above statement

Fig. 2.7 | Memory locations after both variables are input.

© 2007 Pearson Education, Inc. All rights reserved.


35
interger1 = 45;
interger2 = 72;
sum = interger1 + interger2;

After executing the above statement

Fig. 2.8 | Memory locations after a calculation.

© 2007 Pearson Education, Inc. All rights reserved.


36

2.5 Arithmetic Operators


Operator Description Example

+ Adds two operands. A + B = 30


− Subtracts second operand from the A − B = -10
first.
* Multiplies both operands. A * B = 200
/ Divides numerator by denumerator. B /A= 2
Integer division truncates remainder
7 / 5 evaluates to 1
% Modulus operator(%) returns the B %A=0
remainder
7 % 5 evaluates to 2

© 2007 Pearson Education, Inc. All rights reserved.


37

Operator precedence
– Some arithmetic operators act before others (i.e.,
multiplication before addition)

Operator(s) Operation(s) Order of evaluation (precedence)


( ) Parentheses Evaluated first. If the parentheses are
nested, the expression in the innermost pair is
evaluated first. If there are several pairs of
parentheses “on the same level” (i.e., not nested),
they are evaluated left to right.
* Multiplication Evaluated second. If there are several, they are
/ Division evaluated left to right.
% Remainder
+ Addition Evaluated last. If there are several, they are
- Subtraction evaluated left to right.

Fig. 2.10 | Precedence of arithmetic operators.

© 2007 Pearson Education, Inc. All rights reserved.


38

Fig. 2.11 | Order in which a second-degree polynomial is evaluated.

© 2007 Pearson Education, Inc. All rights reserved.


39

2.6 Equality and Relational Operators


The binary relational and equality operators compare their first operand to
their second operand to test the validity of the specified relationship. The
result of a relational expression is 1 if the tested relationship is true and 0
if it is false.

Standard algebraic C equality or


Example of
equality operator or relational Meaning of C condition
C condition
relational operator operator

Equality operators
= == x == y x is equal to y

 != x != y x is not equal to y
Relational operators

 > x > y x is greater than y

 < x < y x is less than y

≥ >= x >= y x is greater than or equal to y

≤ <= x <= y x is less than or equal to y

Fig. 2.12 | Equality and relational operators.


© 2007 Pearson Education, Inc. All rights reserved.
40

What is the output of the following code Q


#include <stdio.h>
int main()
{

printf("3==3 results %d\n",3==3);


printf("3==4 results %d\n",3==4);
printf("3<4 results %d\n",3<4);
printf("3!=3 results %d\n",3!=3);
printf("3>4 results %d\n",3>4);
return 0; }

Result is:
3==3 results 1
3==4 results 0
3<4 results 1
3!=3 results 0
3>4 results 0

© 2007 Pearson Education, Inc. All rights reserved.


Write is the output of this code Q

© 2007 Pearson Education, Inc. All rights reserved.


Q
If a is set to be 5, b is set to be 2, c is set to be 1; what is the
result of following arithmetic expression?

a%5+b*a/2-c+(a+b)

a) 5 b) 4 c) 20 d) 11 e) 13
43

Common Programming Error 2.16


A syntax error will occur if the two symbols
in any of the operators ==, !=, >= and <=
are separated by spaces.

No space

variable1 = = sum causes syntax error

© 2007 Pearson Education, Inc. All rights reserved.


44

Common Programming Error 2.17

A syntax error will occur if the two symbols


in any of the operators !=, >= and <= are
reversed as in =!, => and =<, respectively.

© 2007 Pearson Education, Inc. All rights reserved.


45

Common Programming Error 2.18

Confusing the equality operator == with


the assignment operator =

© 2007 Pearson Education, Inc. All rights reserved.


46

if control statement
▪ if control statement
– Simple version in this section, more detail later

– If a condition is true, then the body of the if statement executed

if (condition) {
body statements
}

© 2007 Pearson Education, Inc. All rights reserved.


1 /* Fig. 2.13: fig02_13.c 47
2 Using if statements, relational
3 operators, and equality operators */
Outline
4 #include <stdio.h>
5
6 /* function main begins program execution */
fig02_13.c
7 int main( void )
8 {
9 int num1; /* first number to be read from user */
(1 of 3 )
10 int num2; /* second number to be read from user */
11
12 printf( "Enter two integers, and I will tell you\n" );
13 printf( "the relationships they satisfy: " );
14
15 scanf( "%d%d", &num1, &num2 ); /* read two integers */
16
17 if ( num1 == num2 ) { Checks if num1 is equal to num2
18 printf( "%d is equal to %d\n", num1, num2 );
19 } /* end if */
20
21 if ( num1 != num2 ) { Checks if num1 is not equal to num2
22 printf( "%d is not equal to %d\n", num1, num2 );
23 } /* end if */
24
25 if ( num1 < num2 ) { Checks if num1 is less than num2
26 printf( "%d is less than %d\n", num1, num2 );
27 } /* end if */
28

© 2007 Pearson Education,


Inc. All rights reserved.
29 if ( num1 > num2 ) {
30 printf( "%d is greater than %d\n", num1, num2 );
48
Outline
31 } /* end if */
Checks if num1 is greater than num2
32
33 if ( num1 <= num2 ) { Checks if num1 is less than or equal to num2
34 printf( "%d is less than or equal to %d\n", num1, num2 );
35 } /* end if */
fig02_13.c
36
37 if ( num1 >= num2 ) { Checks if num1 is greater than equal to num2
(2 of 3 )
38 printf( "%d is greater than or equal to %d\n", num1, num2 );
39 } /* end if */
40
41 return 0; /* indicate that program ended successfully */
42
43 } /* end function main */
43 } /* end function main */

Enter two integers, and I will tell you


the relationships they satisfy: 3 7
3 is not equal to 7
3 is less than 7
3 is less than or equal to 7

(continued on next slide… )

© 2007 Pearson Education,


Inc. All rights reserved.
(continued from previous slide…) 49
Enter two integers, and I will tell you Outline
the relationships they satisfy:
22 is not equal to 12
22 is greater than 12
22 is greater than or equal to 12
fig02_13.c

Enter two integers, and I will tell you (3 of 3 )


the relationships they satisfy:
7 is equal to 7
7 is less than or equal to 7
7 is greater than or equal to 7

© 2007 Pearson Education,


Inc. All rights reserved.
50

Operator precedence
– Some arithmetic operators act before others

Operators Associativity
() left to right
* / % left to right
+ - left to right
< <= > >= left to right
== != left to right
= right to left
Fig. 2.14 | Precedence and associativity of the operators discussed so far.

© 2007 Pearson Education, Inc. All rights reserved.


Q
If a is 5, b is 4, c is 10 what is the output?

a=b=c+6%2; printf ("%d %d %d", a, b, c);

a) 5 10 10 b) 13 13 10 c) 10 10 10 d) 5 4 10 e) 13 10 10
52

Keywords
– Special words reserved for C
– Cannot be used as identifiers or variable names

Keywords
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

Fig. 2.15 | C’s keywords.

© 2007 Pearson Education, Inc. All rights reserved.


Q
What is the result of this logic statement?

int i=5, j=10, k=20;

i > 5 * k % 3 > (k-2!=18)

© 2007 Pearson Education, Inc. All rights reserved.


Q
What is the result of this logic statement?

int i=5, j=10, k=20;

i > 5 * k % 3 > (k-2!=18)

© 2007 Pearson Education, Inc. All rights reserved.


Q
What is the result of this logic statement?
int i=5, j=10, k=20;

i > 5 * k % 3 > (k-2!=18)



i > 5 * k % 3 > (18!=18)

i>5*k%3>0

i > 100 % 3 > 0

i>1>0

1>0

1

© 2007 Pearson Education, Inc. All rights reserved.


56

Write a program that inputs one five-digit number, separates


the number into its individual digits and prints the digits
separated from one another by three spaces each.
[Hint: Use combinations of integer division and the remainder
operation.] For example, if the user types in 42139, the
program should print
Q
4 2 1 3 9
#include <stdio.h>
#include <stdlib.h>
int main()
{
int x1;

printf("Input 5 digit integer: " );


scanf("%d",&x1);

printf("%d %d %d %d %d\n", x1/10000, (x1%10000)/1000, (x1%1000)/100, (x1%100)/10,


x1%10);

system("Pause"); return 0; /* successful termination */


}
© 2007 Pearson Education, Inc. All rights reserved.

You might also like