You are on page 1of 67

MEK0101 :

Bilgisayar
Programlama I
2021-2022 Güz

Hafta 3

Dr. Selma YILMAZYILDIZ KAYAARMA


Plan for Today
• Recap from the last week
• printf() and scanf() in C
• Memory Concept
• Variables in C
• Data Types

2
Recap from the last week

✓Algorithm is the heart of programming! (Remember: Peanut butter and honey sandwich)
✓ Pseudocode and Flowcharts
✓How to write a computer program
✓Fundamental Concepts in Programming
✓ Variable, Assignment, Function, Counter, Loop
✓Getting Started with C Language
✓Our first C program

3
Plan for Today
• Recap from the last week
• printf() and scanf() in C
• Memory Concept
• Variables in C
• Data Types

4
Our First C Program
/*
* hello.c Output:
* This program prints a welcome message
* to the user.
*/
✓ Program comments:
#include <stdio.h> // for printf /* your comment */ OR //
✓ Preprocessor directive
/* my first program in C */
int main() { #include <stdio.h>
printf(" Hello BTU 2021-2022 class! \n"); ✓ main function
return 0; int main() {}
} ✓ printf function :
printf(…)

© 2016 Pearson Education, Ltd. All rights reserved.


5
printf() and scanf() functions in C
The printf() and scanf() functions are used for input and output in C language.
Both functions are inbuilt library functions, defined in stdio.h (header file).

• printf() function • scanf() function


• The printf() function is used for output. It • The scanf() function is used for input. It
prints the given statement to the console. reads the input data from the console.
• The syntax of printf() function is: • The syntax of scanf() function is:
printf("format string",argument_ scanf("format string",&argument_
list); list);
• The format string can be %d (integer), %c • The format string can be %d (integer),
(character), %s (string), %f (float) etc. %c (character), %s (string), %f (float) etc.
(we’ll come to these later!)

6
Using Multiple printfs
• The printf function can print Hello BTU 2021-2022 class! several
different ways.
• For example, the example on the next slide produces the same output.

© 2016 Pearson Education, Ltd. All rights reserved.


7
Our First C Program
/* Output:
* hello.c
* This program prints a welcome message
* to the user.
*/
• This works because each printf resumes
#include <stdio.h> // for printf
printing where the previous printf
stopped printing.
/* my first program in C */ • The first printf prints Welcome followed
int main() { by a space and the second printf begins
printf(" Hello BTU "); printing on the same line immediately
printf(" 2021-2022 class! \n"); following the space.
return 0;
}
© 2016 Pearson Education, Ltd. All rights reserved.
8
• One printf can print several lines by using additional newline characters as in the example.
• Each time the \n (newline) escape sequence is encountered, output continues at the beginning of the
next line.

/*
* hello.c
* This program prints a welcome message
* to the user.
*/
#include <stdio.h> // for printf Output:

/* my first program in C */
int main() {
printf("Hello \nBTU \n2021-2022 \nclass\n");
return 0;
}
© 2016 Pearson Education, Ltd. All rights reserved.
9
Escape Sequences
• Notice that the characters \n were not printed on the screen.
• The backslash (\) is called an escape character.
• It indicates that printf is supposed to do something out of the ordinary.

• When encountering a backslash in a string, the compiler looks ahead at the next
character and combines it with the backslash to form an escape sequence.
• The escape sequence \n means newline.
• When a newline appears in the string output by a printf, the newline causes
the cursor to position to the beginning of the next line on the screen.
• Some common escape sequences are listed in the next slide

© 2016 Pearson Education, Ltd. All rights reserved.


10
© 2016 Pearson Education, Ltd. All rights reserved. 11
Our next program uses the Standard Library function scanf to
obtain an integer typed by a user at the keyboard, computes the
cube and prints the result using printf.

12
Example: Getting input from the user and printing the
cube of the given number (x3).

Let’s start with its algorithm...

13
Example: Getting input from the user and printing the
cube of the given number (x3).

Output:

• The scanf("%d",&number) statement reads integer number from the console


and stores the given value in number variable.
• The printf("cube of number is:%d ",number*number*number)
statement prints the cube of number on the console.

14
Example: Getting input from the user and printing the
cube of the given number (x3).

Output:

• The scanf("%d",&number) statement reads integer number from the console


and stores the given value in number variable.
• The printf("cube of number is:%d ",number*number*number)
statement prints the cube of number on the console.

15
Example: Getting input from the user and printing the
cube of the given number (x3).

Output:

• The scanf("%d",&number) statement reads integer number from the console


and stores the given value in number variable.
• The printf("cube of number is:%d ",number*number*number)
statement prints the cube of number on the console.

16
printf() and scanf() functions in C
• The entire line, including the printf • ampersand (&) - called the address operator in
function (the “f” stands for C—followed by the variable name.
“formatted”), its argument within the
parentheses and the semicolon (;), is • The &, when combined with the variable name,
called a statement. tells scanf the location (or address) in memory
• Every statement must end with a at which the variable number is stored.
semicolon (also known as the statement
terminator). • The computer then stores the value that the
• When the preceding printf statement user enters for number at that location.
is executed, it prints the message on the • The use of ampersand (&) is often confusing to
screen. novice programmers or to people who have
• The characters normally print exactly as programmed in other languages that do not
they appear between the double quotes
in the printf statement. require this notation.
• For now, just remember to precede each
variable in every call to scanf with an &
© 2016 Pearson Education, Ltd. All rights
17 reserved.
Our next program uses the Standard Library function scanf to
obtain two integers typed by a user at the keyboard, computes the
sum of these values and prints the result using printf.

18
Example : Printing sum of 2 numbers

Let’s start with its algorithm again ...

19
Example: Printing sum of 2 numbers

20
Example: Printing sum of 2 numbers
Variables and Variable Definitions
• int integer1; // first number to be entered by user
int integer2; // second number to be entered by user
int sum; // variable in which sum will be stored
are definitions.
• The names integer1, integer2 and sum are the names of
variables—locations in memory where values can be stored
for use by a program.
• These definitions specify that the variables integer1,
integer2 and sum are of type int,
• which means that they’ll hold integer values, i.e., whole
numbers such as 7, –11, 0, 31914 and the like.
• All variables must be defined with a name and a data type
before they can be used in a program.
• The preceding definitions could have been combined into a
single definition statement as follows:
• int integer1, integer2, sum;
but that would have made it difficult to describe the
variables with corresponding comments
© 2016 Pearson Education, Ltd. All rights reserved.
21
Example 2: Printing sum of 2 numbers
Identifiers and Case Sensitivity
• A variable name in C is any valid identifier.
• An identifier is a series of characters consisting
of letters, digits and underscores (_) that does
not begin with a digit.
• C is case sensitive—uppercase and lowercase
letters are different in C, so a1 and A1 are
different identifiers.

© 2016 Pearson Education, Ltd. All rights reserved.


22
23
24
Example: Printing sum of 2 numbers
Prompting Messages
• printf( "Enter first integer\n " ); // prompt
• displays the literal “Enter first integer” and positions
the cursor to the beginning of the next line.
• This message is called a prompt because it tells the user to
take a specific action.

The scanf Function and Formatted Inputs


• The next statement
• scanf( "%d", &integer1 ); // read an integer
uses scanf to obtain a value from the user.
• The scanf function reads from the standard input,
which is usually the keyboard.
© 2016 Pearson Education, Ltd. All rights reserved.
25
Example: Printing sum of 2 numbers
• This scanf has two arguments, "%d" and
&integer1.
• The first, the format control string, indicates the type
of data that should be input by the user.
• The %d conversion specifier indicates that the data should
be an integer (the letter d stands for “decimal integer”).
• The % in this context is treated by scanf (and printf as
we’ll see) as a special character that begins a conversion
specifier.
• The second argument of scanf begins with an
ampersand (&)—called the address operator in C—
followed by the variable name.

© 2016 Pearson Education, Ltd. All rights reserved.


26
Example: Printing sum of 2 numbers
• The &, when combined with the variable name, tells
scanf the location (or address) in memory at which the
variable integer1 is stored.
• The computer then stores the value that the user enters for
integer1 at that location.

• The use of ampersand (&) is often confusing to novice


programmers or to people who have programmed in other
languages that do not require this notation.
• For now, just remember to precede each variable in every call to
scanf with an ampersand.

© 2016 Pearson Education, Ltd. All rights reserved.


27
Example: Printing sum of 2 numbers
• When the computer executes the preceding scanf,
it waits for the user to enter a value for variable
integer1.
• The user responds by typing an integer, then
pressing the Enter key to send the number to the
computer.
• The computer then assigns this number, or value, to
the variable integer1.
• Any subsequent references to integer1 in this
program will use this same value.

© 2016 Pearson Education, Ltd. All rights reserved.


28
Example: Printing sum of 2 numbers
• printf( "Enter second integer\n" ); // prompt
• displays the message Enter second integer on the
screen, then positions the cursor to the beginning of
the next line.
• This printf also prompts the user to take action.
• scanf( "%d", &integer2 ); // read an integer
• obtains a value for variable integer2 from the user.

© 2016 Pearson Education, Ltd. All rights reserved.


29
Example: Printing sum of 2 numbers
Assignment Statement
• The assignment statement
• sum = integer1 + integer2; // assign total to sum
calculates the total of variables integer1 and integer2 and
assigns the result to variable sum using the assignment
operator =.
• The statement is read as, “sum gets the value of integer1 +
integer2.” Most calculations are performed in assignments.
• The = operator and the + operator are called binary operators
because each has two operands.
• The + operator’s two operands are integer1 and integer2.
• The = operator’s two operands are sum and the value of the
expression integer1 + integer2.

© 2016 Pearson Education, Ltd. All rights reserved.


30
31
Example: Printing sum of 2 numbers
Printing with a Format Control String
• printf( "Sum is %d\n", sum ); // print sum
• calls function printf to print the literal Sum is followed by the
numerical value of variable sum on the screen.
• This printf has two arguments, "Sum is %d\n" and sum.
• The first argument is the format control string.
• It contains some literal characters to be displayed, and it contains the
conversion specifier %d indicating that an integer will be printed.
• The second argument specifies the value to be printed.
• Notice that the conversion specifier for an integer is the same in both
printf and scanf.
Calculations in printf Statements
• We could have combined the previous two statements into the
statement
• printf( "Sum is %d\n", integer1 + integer2 );
• The right brace, }, at line 21 indicates that the end of function
main has been reached.
© 2016 Pearson Education, Ltd. All rights reserved.
32
Example: Printing sum of 2 numbers

Output:

33
34
© 2016 Pearson Education, Ltd. All rights reserved. 35
Plan for Today
• Recap from the last week
• printf() and scanf() in C
• Memory Concept
• Variables in C
• Data Types

36
Memory Concepts
• Variable names such as integer1, integer2 and sum actually correspond to locations
in the computer’s memory.
• Every variable has a name, a type and a value.
• In the addition program of above example, when the statement
• scanf( "%d", &integer1 ); // read an integer
• is executed, the value entered by the user is placed into a memory location to which the
name integer1 has been assigned.
• Suppose the user enters the number 45 as the value for integer1.
• The computer will place 45 into location integer1 as shown.

Memory location showing the name and value of a variable

© 2016 Pearson Education, Ltd. All rights reserved.


37
Memory Concepts (Cont.)
• Whenever a value is placed in a memory location, the value replaces the previous
value in that location; thus, this process is said to be destructive.
• When the statement
• scanf( "%d", &integer2 ); // read an integer
executes, suppose the user enters the value 72.
• This value is placed into location integer2, and memory appears as below:

Memory locations after both variables are input

• These locations are not necessarily adjacent in memory.


© 2016 Pearson Education, Ltd. All rights reserved.
38
Memory Concepts (Cont.)

• Once the program has obtained values for integer1 and integer2, it adds
these values and places the total into variable sum.
• sum = integer1 + integer2; // assign total to sum
• replaces whatever value was stored in sum.
• This occurs when the calculated total of integer1 and integer2 is placed
into location sum (destroying the value already in sum).
• The values of integer1 and integer2 appear exactly as they did before
they were used in the calculation.
• After sum is calculated, memory appears as:

© 2016 Pearson Education, Ltd. All rights reserved. 39


Memory locations after a calculation

40
Memory Concepts (Cont.)

• The values of integer1 and integer2 appear exactly as they did before they were
used in the calculation
• They were used, but not destroyed, as the computer performed the calculation.
• Thus, when a value is read from a memory location, the process is said to be
nondestructive.

© 2016 Pearson Education, Ltd. All rights reserved. 41


Plan for Today
• Recap from the last week
• Algorithms
• printf() and scanf() in C
• Memory Concept
• Variables in C
• Data Types

42
Variables in C
A variable is a named link/reference to a value stored in the system’s memory. It is used to
store data. Its value can be changed, and it can be reused many times.
It is a way to represent memory location through symbol so that it can be easily identified.
Let's see the syntax to declare a variable:

type variable_list;

• The example of declaring the variable: • We can also provide values while declaring the
variables:
int a; Here, a, b, c are
float b; variables. The int, int a=10,b=20; //declaring 2 variable of integer
char c float, char are the float f=20.8;
data types. char c='A';

43
Variables in C :
Rules for defining variables
• A variable can have alphabets, digits, and underscore.
• A variable name can start with the alphabet, and underscore only. It can't start with a digit.
• No whitespace is allowed within the variable name.
• A variable name must not be any reserved word or keyword, e.g. int, float, etc.
• Upper and lowercase letters are distinct because C is case-sensitive: so a1 and A1 are
different identifiers

44
List of 32 reserved word or keyword in C:

We will learn about all the C language keywords later.

45
Variables in C :
Rules for defining variables
Some Tips :
➢ Choosing meaningful variable names helps make a program self-
documenting which means fewer comments and explanations are
needed.
➢ Multiple-word variable names can help make a program more
readable.
• either separate the words with underscores or
total_score
• begin each word after the first with a capital letter
totalScore
➢ Place a space after each comma (,) to make programs more readable

46
Pop Quiz

Are the variable names below correct or incorrect? Why?

• int money owed

47
Pop Quiz

Are the variable names below correct or incorrect? Why?

• int money owed


• int total_count

48
Pop Quiz

Are the variable names below correct or incorrect? Why?

• int money owed


• int total_count
• int score2

49
Pop Quiz

Are the variable names below correct or incorrect? Why?

• int money owed


• int total_count
• int score2
• int 2ndscore

50
Pop Quiz

Are the variable names below correct or incorrect? Why?

• int money owed


• int total_count
• int score2
• int 2ndscore
• int int

51
Variables in C :
Types of Variables
There are many types of variables in c:
1. local variable
2. global variable
3. static variable
4. automatic variable
5. external variable

52
Variables in C : Types of Variables (we’ll see later)
Local Variable Global Variable
A variable that is declared inside the function or block is It is declared outside the function or block.
called a local variable. • Any function can change the value of the global variable.
• It must be declared at the start of the block. It is available to all the functions.
• You must have to initialize the local variable before it is • It must be declared at the start of the block.
used.
int value=20;//global variable
void function1(){ void function1(){
int x=10;//local variable int x=10;//local variable
} }
Static Variable
A variable that is declared with the static keyword is called static variable.
It retains its value between multiple function calls. The lifetime is the entire program execution
void function1(){
int x=10;//local variable
static int y=10;//static variable Output:
x=x+1;
y=y+1;
printf("%d,%d",x,y);
}
53
Variables in C : Types of Variables (we’ll see later)
Automatic Variable External Variable
All variables in C that are declared inside the block, are We can share a variable in multiple C source files by using an
automatic variables by default. We can explicitly declare an external variable. To declare an external variable, you need
automatic variable using auto keyword. to use extern keyword.

void main(){ myfile.h


int x=10; //local variable (also automatic)
auto int y=20;//automatic variable extern int x=10; //external variable (also global)
}
program1.c

#include "myfile.h"
#include <stdio.h>
void printValue(){
printf("Global variable: %d", global_variable);
}

54
Plan for Today
• Recap from the last week
• Algorithms
• printf() and scanf() in C
• Memory Concept
• Variables in C
• Data Types

55
Data Types
Data types specify how we enter data into our programs and what type of data we
enter.
• So they are used in declaring variables or functions of different types.
• The type of a variable determines how much space it occupies in storage
and how the bit pattern stored is interpreted.

Data type determines the type of data a variable will hold.


• If a variable x is declared as int. it means x can hold only integer values.

56
Data Types
There are 2 general categories of data types:
1. Basic data types:
These are fundamental data types in C namely:
• integer (int),
• floating point (float),
• character (char)
2. Derived data types:
Derived data types are nothing but primary datatypes but a little twisted
or grouped together like: array, structure, union and pointer.
3. Void data type
• void

57
Data Types (cont).
Character Type: char, unsigned char, signed char
• holds characters- things like letters, punctuation, and spaces.
• In a computer, characters are stored as numbers, so char holds integer values
that represent characters.
• The format specifier %c can be used for example in a printf() call to display
the value of a char variable at the terminal.

Example:

58
Data Types (cont).
Standard integers: int, signed int, short int, long int
• Integers are used to store whole numbers that can have both zero, positive and negative
values but no decimal values. For example: 0, -5, 10
• The unsigned int can be positive and zero but not negative,
• The storage size of int data type is 2 or 4 or 8 byte, depend upon the processor in the CPU
• %d is used as the format specifier
Ex of declaring an integer variable:

59
Data Types (cont).
Floating point type: float, double,
• Floating types are used to store real numbers.
• A floating-point constant is distinguished by the presence of a decimal point.
• Example: 3., 125.8, and −.0001 are all valid examples of floating-point constants.
• Storage size of float data type is 4. This also varies depend upon the processor in the CPU
• We can use up-to 6 digits after decimal using float data type. For example, 10.456789 can
be stored in a variable using float data type.
• double allows up-to 10 digits after decimal.
• format specifier %f and %lf and are used for float and double, respectively.
Example:

Floating-point numbers can also be


represented in exponential:

60
Data Types (cont).
void type: void
• void is an empty data type that has no value.
• Usually used to specify the type of functions which returns nothing.
• For example, if a function is not returning anything, its return type
should be void.
• Note that, you cannot create variables of void type!
• We will get acquainted to this datatype as we start learning more advanced
topics in C language, like functions, pointers etc.

61
Data Types (cont).
Depending on the precision and range required, you can use one of the following datatypes:

• The unsigned version has roughly double the range of its signed
counterparts.
• Signed and unsigned characters differ only when used in
arithmetic expressions

62
You can always check the size of a variable using the sizeof() operator.

#include <stdio.h>
int main() {
short a;
long b;
long long c;
long double d;

printf("size of short = %d bytes\n", sizeof(a));


printf("size of long = %d bytes\n", sizeof(b));
printf("size of long long = %d bytes\n", sizeof(c));
printf("size of long double= %d bytes\n", sizeof(d)) Output:
;
return 0;
}

63
Summary of commonly used
types in C programming for
quick access

64
Data Types (cont.)
Declarations

The general format for a declaration is:


type variable-name[=value]

Examples:
• char x; /∗uninitialized ∗/
• char x=‘A’; /∗intialized to ’ A’∗/
• char x=‘A’, y=‘B’; /∗multiple variables initialized ∗/
• char x=y=‘Z’; /∗multiple initializations ∗/

66
Exercise: Using the Basic Data Types

Output:

67
That’s it for today.
See you next week!

68

You might also like