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

Computer Programming I: Grammar and Basic Elements of C Language Year 2020-2021

This document provides an overview of a lecture on basic elements of the C programming language. The objectives are to define key concepts like data types, variables, constants, and operators. It will cover declaring variables and constants, choosing suitable data types, and displaying data with different formats. The lecture contents include basic C program elements, identifiers, data types, variables and constants, assignment statements, expressions, and formatted input/output.

Uploaded by

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

Computer Programming I: Grammar and Basic Elements of C Language Year 2020-2021

This document provides an overview of a lecture on basic elements of the C programming language. The objectives are to define key concepts like data types, variables, constants, and operators. It will cover declaring variables and constants, choosing suitable data types, and displaying data with different formats. The lecture contents include basic C program elements, identifiers, data types, variables and constants, assignment statements, expressions, and formatted input/output.

Uploaded by

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

Computer Programming I

Bachelor in Telecommunication Technologies Engineering

Lecture 2
Grammar and basic elements of C language
Year 2020-2021
Objectives
1. Define the following concepts
• Data type
• Identifier
• Variable
• Constant
• Operator
• Expression
2. Study the data types and their features (size, range, memory allocation)
3. Get to know the operators and the data types they operate upon
4. Choose the suitable data type for each variable or constant in a program
5. Declare variables and constants
6. Display data with different formats

Computer Programming I Lecture 2 2


Contents
1. Basic elements of a C program
2. Identifiers
3. Data types, variables and constants
• Declaration and initialization of variables
4. The assignment statement
• Expressions
5. Formatted input/output

Computer Programming I Lecture 2 3


Key concepts
• Variables and constants: data handled by a program
• Declarations: evidence of the data (variables and
constants) and functions to be used in a program
• Data type: definition of the value set a datum can take
and which operations can be made upon it.
• Operators: determine which calculations can be made
upon variables
• Expressions: combination of variables, constants and/or
functions by means of operators in order to obtain new
values
Computer Programming I Lecture 2 4
Basic elements of a C program
Elements Examples
Compiler directives #include <stdio.h>
#include <math.h>
#define NTC_WEIGHT 0.5
Variables float NTC, NPC, NPR;
int first_number;
=> declaration of variables
Expressions discount = price * DISCOUNT_PERCENT / 100;
= => Assignment statement
value == desired_value
== => Relational operator
Statements discount = price * DISCOUNT_PERCENT / 100;
int first_number;
Comments // Calculate the selling price
/* Swap the letters in a word … */
Computer Programming I Lecture 2 5
Contents
1. Basic elements of a C program
2. Identifiers
3. Data types, variables and constants
• Declaration and initialization of variables
4. The assignment statement
• Expressions
5. Formatted input/output

Computer Programming I Lecture 2 6


Identifiers
• A C identifier is:
– Source code view => a name used to identify any item in a C
program
– Compiler view => a reference to the memory location of the
item
• Starts with a letter or an underscore: '_'
• Followed by 0 or more letters, underscores or digits
• Uppercase and lowercase letters are significant: X and x
are different identifiers
• User-defined length, but characters after the 31st are
ignored
Computer Programming I Lecture 2 7
Identifiers
• #define PI 3.14159 // symbolic constant
• char letter = 'a'; // 'a' is the value of letter
• char name[] = "Pedro"; // name[0] is 'P'
• int real_club_celta = 2;
• float radius = 2.18;
• double matrix[5][5];
• float* dir_radius = &radius;

Computer Programming I Lecture 2 8


Reserved identifiers in C
• The following identifiers can not be used to name variables,
constants, functions, …
auto break case char const continue
default do double else enum extern
float for goto if int long
register return short signed sizeof static
struct switch typedef union unsigned void
volatile while

• The use of goto is strictly forbidden in Computer Programming I


Computer Programming I Lecture 2 9
Correct identifiers?
1) a
2) 9
3) a9
4) 9a
5) _9
6) 9_
7) name length
8) name_length
9) nameLength
10)NAMELENGTH
11)name;length
12)%success
13)union

Computer Programming I Lecture 2 10


Contents
1. Basic elements of a C program
2. Identifiers
3. Data types, variables and constants
• Declaration and initialization of variables
4. The assignment statement
• Expressions
5. Formatted input/output

Computer Programming I Lecture 2 11


Data types
Simple Structured
Character Array
Integer Struct
Real Union
File
Only one component Several components

Computer Programming I Lecture 2 12


Simple data types in C
Data type Description Range Size Example
short Short signed integer -32768 … 32767 2 bytes -25
int Signed integer -2147483648 … 2147483647 4 bytes 65536
long Long signed integer -9223372036854775808 … 8 bytes 26214456
long int 9223372036854775807
unsigned short Short unsigned integer 0 … 65535 2 bytes 34
unsigned int Unsigned integer 0 … 4294967295 4 bytes 164000
unsigned long Long unsigned integer 0 … 18446744073709551615 4 bytes 70000000
float Real floating-point (precision: 7 digits) 3.4e-38 … 3.4e+38 4 bytes 3.24
double Real floating-point (precision: 15 digits) 1.7e-308 … 1.7e+308 8 bytes 0.0000045
char Characters: alphabetic, digits, punctuation -128 … 127 1 byte 'a' '@' '7'
marks, special characters
unsigned char The shortest integer 0 … 255 1 byte 'B'
pointer The address of another variable 8 bytes

Computer Programming I Lecture 2 13


Simple data types in C
• The sizes are compiler-dependent
• {int} ≠ Z
– {int} is a finite subset of Z
– All the integer numbers, but only those in a given range
• {float} ≠ R
– {float} is a finite subset of R
– NOT all the real numbers
– ”Between 2 distinct real numbers there are infinitely many numbers”
– That is not true for float or double data types
– And only those numbers in a given range

Computer Programming I Lecture 2 14


Variable's attributes
Attribute Examples
Identifier letter real_club_celta radius

Type char int float

Value 'a' 2 2.18

Address &letter &real_club_celta &radius

• Scope: can be accessed only in the block where the


variable was declared
– And only in those sentences below the declaration

Computer Programming I Lecture 2 15


Scope
#include <stdio.h>
int main ( ) {
float base = 2.18, height = 3.2;
if (height > 3) {
float base = height;
printf ("base is %.2f\n", base); // 3.20 is written
}
printf ("base is %.2f\n", base); // 2.18 is written
return 0;
}

Computer Programming I Lecture 2 16


char type variables
char letter = 'a';
• In the address &letter, the ascii code for 'a' is stored as an
integer (97)
char name[] = "Pedro";
• The string "Pedro" occupies 6 characters:
– 'P', 'e', 'd', 'r', 'o', '\0'
– '\0' is the end of string character.
– name[0] is 'P', … name[4] is 'o', name[5] is '\0'

Computer Programming I Lecture 2 17


Variables
• Their value can change along the program's execution
• Declaration and (optional) initialization:
< Data type > < identifier > [ = < initial value > ] ;

char letter = 'a'; // 'a' is the value of letter


char name[] = "Pedro"; // name[0] is 'P'
int real_club_celta; // no initialization
float radius = 2.18;
double matrix[5][5] = { 5 }; // initializes just 1 element
float* dir_radius = &radius;

Computer Programming I Lecture 2 18


Declaration and initialization
• Which actions are carried out with this statement?
float radius = 2.18;
• A contiguous block of 4 bytes of primary memory is reserved for
storing a float variable
• The address of the block's initial byte is associated to the identifier
of the variable in the memory assignment table
• The value 2.18 is stored in those bytes with the appropriate format

Computer Programming I Lecture 2 19


Declaration and initialization
• Which actions are carried out with this statement?
float* dir_radius = &radius;
• A contiguous block of 8 bytes of primary memory is reserved for
storing a float* variable (i.e. an address)
• The address of the block's initial byte is associated to the identifier
of the variable in the memory assignment table
• The value &radius (i.e. the address of radius) is stored in those
bytes with the appropriate format

Computer Programming I Lecture 2 20


Declaration and initialization
address
type size identifier value
(&identifier)
char 1 letter 'a' 1000
char[ ] 6 name "Pedro" 1001
int 4 real_club_celta 2 1007
float 4 radius 2.18 1011
double[ ][ ] 200 matrix 0 1015
float* 8 dir_radius 1011 1215

Computer Programming I Lecture 2 21


Declared constants
• Memory is reserved for allocating them
• just as with variables
• But their value doesn't change along the program's execution
• Declaration AND initialization:
const < Data type > < identifier > = < initial value > ;

const int NUM_STUDENTS = 20;


const float PI = 3.14159;
const char LETTER_A = 'A';

Computer Programming I Lecture 2 22


Symbolic constants
• Memory is NOT reserved for allocating them
• The compiler just substitutes their identifier by their value
before translating the source code into machine code
• Definition:
#define < identifier > < constant value >

– Careful: no final ';'

#define NUM_STUDENTS 20
#define PI 3.14159F
#define LETTER_A 'A'

Computer Programming I Lecture 2 23


Symbolic constants
#define NUM_STUDENTS 20 /* int */
#define NUM_STUDENTS 20L /* long int */
#define NUM_STUDENTS 20U /* unsigned int */
#define NUM_STUDENTS 20UL /* unsigned long int */
#define REAL 1e-2 /* double */
#define PI 3.14F /* float */
#define PI 3.14 /* double */
#define PI 3.14L /* long double */
#define TEN 0xA /* integer in hexadecimal notation */
#define CAPITAL_A 'A' /* char */
#define CAPITAL_A '\101' /* char: ASCII value in octal */
#define CAPITAL_A '\x41' /* char: ASCII value in hexadecimal */

Computer Programming I Lecture 2 24


Contents
1. Basic elements of a C program
2. Identifiers
3. Data types, variables and constants
• Declaration and initialization of variables
4. The assignment statement
• Expressions
5. Formatted input/output

Computer Programming I Lecture 2 25


Arithmetic expressions
• Variables and constants linked by:
– Binary operators: operand operator operand
• +,-,*,/,%
• / : quotient if integer operands
• % : modulus or remainder of integer quotient
• Example: 4.5 - 5
– Unary operators: operator operand
• + , - , sizeof , (<type>)
• Example: -9.5
– Increment (++) and decrement (--):
• pre- is different from post-
– Same side effect: the variable is incremented (or decremented)
– Uses a different value in the expression: the new value vs the original value

Computer Programming I Lecture 2 26


Assignment statement
• Takes the following form:
variable = expression;
– Evaluates the expression in the right hand side, and
– Stores the resulting value in the variable
• ≠ equation
– a = a + 1; is a correct statement
• Take a's value, sum 1 to it, and store the result back in a
• Compressed forms:
variable += expression; ó variable = variable + expression;
variable -= expression; ó variable = variable – expression;
variable *= expression; ó variable = variable * expression;
variable /= expression; ó variable = variable / expression;
variable %= expression; ó variable = variable % expression;

Computer Programming I Lecture 2 27


Arithmetic operators
int x, y;
float v;
Arithmetic Compressed Operation Example Compressed Result
operator form example

+ += Addition x=4.5+3; x=7


y=x+4; y=11
v=4.5+3; v=7.5
x=x+y; x+=y x=18

- -= Subtraction x=4.5-3; x=1


y=x-4; y=-3
v=4.5-3; v=1.5
x=x-y; x-=y x=4

Computer Programming I Lecture 2 28


Arithmetic operators
Arithmetic Compressed form Operation Example Compressed example Result
operator
* *= Multiplication x=4.5*3; x=13
y=x*2; y=26
v=4.5*3; v=13.5
v=4*3; v=12.0
x=x*y; x*=y x=338
/ /= Division x=4/3; x=1
(if integer operands x=4.0/3.0; x=1
=> v=4/3; v=1.0
integer quotient). v=4.0/3; v=1.33
v=(float) 4/3; v=1.33
x=25; x=25
y=3; y=3
x=x/3; x/=3; x=8
x=x/y; x/=y; x=2
Computer Programming I Lecture 2 29
Arithmetic operators
Arithmetic Compressed Operation Example Compressed example Result
operator form
% %= Modulus x=15%2; x=1
v=(15%2)/2; v=0.0
v=((float) (15%2))/2; v=0.5
x=20; x=20
y=3; y=3
x=x%12; x%=12; x=8
x=x%y; x%=y; x=2
++ Increment x=7; x=7;
y=x++; y=7; x=8;
x=7; x=7;
y=++x; y=8; x=8;
-- Decrement x=7; x=7;
y=x--; y=7; x=6;
x=7; x=7;
y=--x; y=6; x=6;

Computer Programming I Lecture 2 30


Relational operators
Relational Operation Example Result
operator int res;
== Equal to res= 'h'=='p'; res=0 (FALSE)
!= Different from res= 'a'!='b'; res=1 (TRUE)
< Lower than res= 7<15; res=1 (TRUE)
res= (7>8) > (9>6); res=0 (FALSE)
> Greater than res= 22>11; res=1 (TRUE)
<= Lower than or equal to res= 15<=2; res=0 (FALSE)
>= Greater than or equal to res= 35>=20; res=1 (TRUE)

Computer Programming I Lecture 2 31


Logical operators
Logical Operation Example Result
operator int X, Y;
! Negation X= (!(7>15)); X=1
Y= (!0); Y=1
&& Conjunction (AND) X= (35>20) && (20<=23) ; X=1
Y= 0 && 1; Y=0
|| Disjunction (OR) X= (35>20) || (20<=18); X=1
Y= 0||1; Y=1

Expressions linked by these operators are evaluated left to


right, and evaluation stops as soon as the result is known
Computer Programming I Lecture 2 32
int x = 10; int y = 4; float a = 10.0; float b = 10.0;

Correct assignment statements? Result?


a = b; a = b / y;
a = a; a = x / y;
5 = a;
x /= y;
a + b = x + y;
a /= y;
a -= b;
a =- b; x -= ++y;
x = a; x -= y++;
a = x; x %= y;
x = a % y;
Computer Programming I Lecture 2 33
Type conversion
• Conversion rules: if an expression combines operands
with different types, the operation is carried out in the
wider type, with the following hierarchy:
– char < unsigned char < short < unsigned short < int <
unsigned int < float < double
• Expressions that can lead to an information loss, as
assigning a float to an integer, generate a warning, but
are not illegal.

Computer Programming I Lecture 2 34


Precedence and evaluation order
Operators Hierarchy Order
() higher Left-to-right
!, ++, --, & Right-to-left
*, /, %
+, -
<, >, <=, >=
Left-to-right
==, !=
|
&&, ||
=, +=, -=, *=, /=, %= lower Right-to-left

Computer Programming I Lecture 2 35


Data representation

Computer Programming I Lecture 2 36


Contents
1. Basic elements of a C program
2. Identifiers
3. Data types, variables and constants
• Declaration and initialization of variables
4. The assignment statement
• Expressions
5. Formatted input/output

Computer Programming I Lecture 2 37


Formatted output: printf()
printf ("format", args);
fprintf (stdout, "format", args);

• Both print formatted output to standard output (the computer


screen)
• args is an optional list of arguments: values to be printed
• "format" is a string of characters specifying the format:
– Ordinary characters are copied unchanged to standard output
• there are some “special but ordinary” characters:
– '\n' => a new-line character
– '\t' => a tab character
– Conversion specifiers produce the conversion and printing of the next
argument. There is a 1 to 1 correspondence: specifiers <-> arguments

Computer Programming I Lecture 2 38


Conversion specifiers
int a = 67; float x = 0.067;
char n[ ] = "pedro"; char c = 'X';

• %d => arg is expected to be an integer, and is printed in decimal notation


– %Nd => arg is printed in a N-character wide field.
• Example: printf ("number = |%10d|", a); => number = | 67|
– %ld => arg is expected to be a long int
• %f => arg is expected to be a real, and is printed in floating point notation
– %N.Mf => arg is printed in a N-character wide field, and with M decimal digits
• Example: printf ("number = |%10.4f|", x); => number = | 0.0670|
• %e => arg is expected to be a real, and is printed in engineering notation
• Example: printf ("number = |%10.4e|", x); => number = | 6.7000e-2|
• %s => arg is expected to be a string
– %Ns => arg is printed in a N-character wide field, padded with blanks
– The end-of-string character ('\0') is not printed
• Example: printf ("name = |%10s|", n); => name = | pedro|
• %c => arg is expected to be character
– %Nc => arg is printed in a N-character wide field, padded with blanks
• Example: printf ("char = |%10c|", c); => char = | X|

Computer Programming I Lecture 2 39


Correct outputs?
int a = 7; printf ("%d\n", a);
int b = 50000; printf ("%d - %f - %s\n", a, x, n);
float x = 0.039; printf ("%8d\n", a);
printf ("%3d\n", b);
char n[] = "programming";
printf ("%10.2d\n", a);
printf ("%10.2f\n", a);
printf ("%10.2f\n", x);
printf ("%10f\n", x);
printf ("%.2f\n", x);
printf ("%20s\n", n);
printf ("%5s\n", n);
printf ("%4c\n", n[3]);
Computer Programming I Lecture 2 40
Formatted input: scanf()
scanf ("format", args);
fscanf (stdin, "format", args);

• Both read formatted input from standard input (the keyboard)


• args is an optional list of arguments: addresses of variables to be filled
• "format" is the specification of the format. A string of characters, of which:
– White characters (space, tab, new-line) match any amount of white space
(including none) in the input
– An ordinary character must match the next character of input
– A conversion specifier produces the conversion of the next characters in the input:
• The specifiers are similar to those of printf(), but
• %s => an end-of-string character ('\0') is added to the converted string
• If conversion is correct, the formatted value is stored in the address given by the next argument
• If it fails, the function returns indicating the failure

Computer Programming I Lecture 2 41


Formatting rules
specifiers rules
%d, %f, %e • Skip preceding white-space characters
• When a non-white-space characters is found:
%Nd, %Nf, %Ne • While the next character abides to the type definition, extract it
• Stop (and leave the remaining characters in the input) when:
• A white-space character (space, tab, new-line) is found
• A character that offends the type definition is found
• The (optional) field width has been reached
• Convert the extracted characters to the type format, and store the result
%s • Skip preceding white-space characters
• When a non-white-space characters is found:
%Ns • Extract it
• Stop (and leave the remaining characters in the input) when:
• A white-space character (space, tab, new-line) is found
• The (optional) field width has been reached
• Append a '\0' character to the extracted characters, and store the resulting string
%c • Extract the following character (whatever it is, including white-space)
• Stop when the (optional) field width is found (the first char by default)
%Nc • Store the extracted character(s)

Computer Programming I Lecture 2 42


int a; float x; char n[10];

Correct inputs?
• Input line • Function call
25 54.32e-1 Pedro scanf ("%d", &a);
scanf ("%d %f %s", &a, &x, n);

56789 45a72 scanf ("%d %f %s", &a, &x, n);


scanf ("%2d %f %2s", &a, &x, n);
scanf ("%s %f %d", n, &x, &a);

56789 45.72 scanf ("%d %f %s", &a, &x, n);


scanf ("%2d %f %2s", &a, &x, n);
Computer Programming I Lecture 2 43
Input/output of chars and lines
c = fgetc(stdin);
• obtains the next input character (if present) from standard input
fputc (c, stdout);
• writes the character c to standard output
fgets (string, size, stdin);
• reads at most one less than the number of characters specified by size
from standard input and stores them in the string
– A '\0' is always appended
– If a '\n' is found, the input stops after it, but the '\n' is copied too

fputs (string, stdout);


• writes the string to standard output

Computer Programming I Lecture 2 44


Characters testing and conversion
function Return value
isalpha(c) • Non-zero if c is an alphabetic ascii letter. Zero otherwise
isupper(c) • Non-zero if c is an upper-case alphabetic ascii letter. Zero otherwise
islower(c) • Non-zero if c is an lower-case alphabetic ascii letter. Zero otherwise
isdigit(c) • Non-zero if c is a decimal digit. Zero otherwise
isspace(c) • Non-zero if c is a space, a tab or a new-line character. Zero otherwise
tolower(c) • If c is an upper-case letter, returns the corresponding lower-case letter; otherwise, c's value is
returned unchanged
toupper(c) • If c is an lower-case letter, returns the corresponding upper-case letter; otherwise, c's value is
returned unchanged

• Require:
#include <ctype.h>
Computer Programming I Lecture 2 45
References
• Brian W. Kernighan & Dennis M. Ritchie, The C Programming
Language, 1995, Prentice Hall.
• Manuel Caeiro Rodríguez, Enrique Costa Montenegro, Ubaldo
García Palomares, Cristina López Bravo, J, Practicar
Programación en C, 2014, Andavira.
• Learn C Programming,
https://www.tutorialspoint.com/cprogramming/
• Learn C Programming,
https://www.programiz.com/c-programming
• Stephen G. Kochan, Programming in C, 2014, Addison Wesley.
Computer Programming I Lecture 2 46

You might also like