C Programming Language - JETS Format - Oct 2020
C Programming Language - JETS Format - Oct 2020
Introduction to
Programming Using C
Introduction to Programming
Content
• Introduction
• Programming Languages Levels
• Programming Techniques History
• How Do Programming Languages Work?
• C Program Structure
• Some of basics in C Program
Algorithms
Instructions
+
Data
Data
Structure
4
• Low-Level Languages
• Fundamentals language for computer processors,
• 0’s and 1’s that represent high and low electrical voltage (Machine Language),
• Modified to use symbolic operation code to represent the machine operation code
(Assembly Language)
• High-Level Languages
• Use English like statements, executed by operating system (in most cases)
• C, C++, Pascal, Java, ….
• Very High-Level Languages
• Usually domain-specific languages, limited to a very specific application, purpose, or
type of task, and they are often scripting languages
• PLAN, Prolog, LISP
5
main
• Programming model that organizes software design around data, or objects, rather
than functions.
• An object can be defined as a data field that has unique attributes and behavior.
• A Class is the template of objects that describe the same data but each one has
different values of attributes.
• Reusability of the classes is one of the advantages of this technique.
• Details will be clear in Object-Oriented Programming using C++ course …
• Interpreted Languages
• It depends on an interpreter program that reads the source code and translates it on the
fly into computations and system calls- line by line.
• The source has to be re-interpreted (and the interpreter present) each time the code is
executed. Basic and most of scripting languages (HTML)
• Compiled Languages
• Compiled languages get translated into executable file, no need to recompile again –if
there is no changes – run the executable directly. C, C++, Pascal
• Compiled & Interpreted Languages
• Compiler translate to intermediate code and need the interpreter to run that
intermediate code. Java
10
11
• You can include just one library using one include statement
• Must be the first of the file
• Has two forms:
• #include <stdio.h>
• #include “d:\\myNewLib\\extern.h”
13
• #define
• It is used to define a replacement text with another after the statement directly till
the end of the file before starting the compilation.
• Ex:
• #define PI 3.14
• ----
• printf (“%f”, PI); // the replacement done before start compilation the o/p is “3.14”
• Ex:
• #define one 1
• #define two one+one
• #define four two*two
• Macro is another type of text replacement but with using the function operator ().
• Ex:
• #define SUM( X , Y) X+Y
• -------
• -------
• printf(“%d”, SUM(3, 8)); // o/p will be 11
• printf(“%d”, SUM(-4, 3)); // o/p will be -1
15
• Structure mean record with number of fields which they are non-homogeneous in
most cases
• It will be clear in the 4th lecture.
16
• The scope of them is global; these variables are accessible by all the functions of
the program.
• It is not preferable to use it without strong reasons; use it if and only if you have to
use it. Why?
• They are saved in a part of the memory sections allocated to the program, this part
is called: Heap Memory
17
18
19
• It is the part to write the structure of functions you designed it to your program
• It is the full functions; Header and body for each one
20
• Case sensitive.
• Braces, and blocks: {}
• Delimiters after each statements – except include and define: ;
• Basic input and output functions:
• printf
• scanf
• getch
• clrscr
21
* The ANSI/IEEE Standard 754-1985 for Binary Floating-Point Arithmetic ("the IEEE standard" or "IEEE 754“)
22
23
• Operators in C
• Control Statements in C
• Branching Statements
• Looping Statements
• Break Statement
• Continue Statement
• Comments in C
• Introduction to Magic Box Assignment
27
28
Widening
(implicit casting)
Narrowing
(requires explicit casting)
30
• The following table shows all the arithmetic operators supported by the C language. Assume
variable A holds 10 and variable B holds 20 then
31
int x=30600;
5% 2= 1
int y=15236;
5 % -2 = 1 int z=x*y/x;
-5 % 2 = -1
-5 % -2 = -1
Unexpected results
32
• The following table shows all the relational operators supported by C. Assume variable A
holds 10 and variable B holds 20 then:
Operator Description Example
== Checks if the values of two operands are equal or not. If yes, then the condition becomes true. (A == B) is not true.
!= Checks if the values of two operands are equal or not. If the values are not equal, then the (A != B) is true.
condition becomes true.
> Checks if the value of left operand is greater than the value of right operand. If yes, then the (A > B) is not true.
condition becomes true.
< Checks if the value of left operand is less than the value of right operand. If yes, then the (A < B) is true.
condition becomes true.
>= Checks if the value of left operand is greater than or equal to the value of right operand. If yes, (A >= B) is not true.
then the condition becomes true.
<= Checks if the value of left operand is less than or equal to the value of right operand. If yes, (A <= B) is true.
then the condition becomes true. 33
• Bitwise operator works on bits and perform bit-by-bit operation. The truth tables for &, |,
and ^ is as follows:
p q p&q p|q p^q
0 0 0 0 0
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1
34
• The following table lists the bitwise operators supported by C. Assume variable 'A' holds 7 and
variable 'B' holds 5, then
Operator Description Example
& Binary AND Operator copies a bit to the result if it (A & B) = 5, i.e., 0000 0101
exists in both operands.
35
• Following table shows all the logical Short-Circuit operators supported by C language.
Assume variable A holds 1 and variable B holds 0, then
&& Short-Circuit AND Operator. If left operand equal false the (A && B) is false= 0.
result will be false without check on the right operand.
36
• The following table lists the bitwise Shift operators supported by C. Assume variable 'A' holds
60, then:
<< Binary Left Shift Operator. The left operands value is moved left
by the number of bits specified by the right operand. A << 2 = 240 i.e., 1111 0000
>> Binary Right Shift Operator. The left operands value is moved
right by the number of bits specified by the right operand. A >> 2 = 15 i.e., 0000 1111
37
• The following table lists the assignment operators supported by the C language:
Operator Description Example
= Simple assignment operator. Assigns values from right side
C = A + B will assign the value of A + B to C
operands to left side operand
+= Add AND assignment operator. It adds the right operand to the
C += A is equivalent to C = C + A
left operand and assign the result to the left operand.
-= Subtract AND assignment operator. It subtracts the right operand
C -= A is equivalent to C = C - A
from the left operand and assigns the result to the left operand.
*= Multiply AND assignment operator. It multiplies the right operand
C *= A is equivalent to C = C * A
with the left operand and assigns the result to the left operand.
/= Divide AND assignment operator. It divides the left operand with
C /= A is equivalent to C = C / A
the right operand and assigns the result to the left operand.
%= Modulus AND assignment operator. It takes modulus using two
C %= A is equivalent to C = C % A
operands and assigns the result to the left operand. 38
• The following table lists the assignment operators supported by the C language:
39
• There are a few other important operators including sizeof and ternary supported by the C Language.
Operator Description Example
sizeof() Returns the size of a variable. sizeof(a), where a is float, will return 4.
& Returns the address of a variable. &a; returns the logical address of the variable a.
42
43
if( Condition(s) )
{ int grade = 48;
…
… //true statements if(grade > 60)
… printf(“Pass”);
} else
[else] {
{ printf(“Fail”);
… }
… //false statements
…
}
44
switch(myVariable){
case value1: • int
… • char
…
break; • enum
case value2:
…
…
break;
default:
…
}
45
• For statement: The for loop is used when the number of iterations is predetermined.
• Its syntax:
47
• While Statement: The while loop is used when the termination condition occurs unexpectedly
and is checked at the beginning.
• Its syntax:
int x = 0;
while (condition(s))
{ while (x<10) {
… printf(“%d\n”, x);
…
…
x++;
} }
48
• Do .. While Statement: The do..while loop is used when the termination condition occurs
unexpectedly and is checked at the end.
• Its syntax:
do int x = 0;
{
… do{
…
… printf(“%d\n”, x);
x++;
} } while (x<10);
while(condition(s));
49
......
while(age <= 65)
{
……
balance = payment * l;
if (balance >= 25000)
break;
}
......
50
......
for( year=2000; year<= 2099; year++){
if (year % 4 == 0)
continue;
printf(“Y = %d”, year)
}
......
51
52
• You have the following box and need to put the numbers from 1 to 9 in each cell without
repeating and with another constraint: the summation of each row equals to 15 and the
summation of each column equals to 15 and the summation of each diagonal equals to 15.
0 1 2
0 6 1 8
1 7 5 3
2 2 9 4
53
58
59
62
• And so the compiler generate a vector for arrays, it may be look like the following table:
• Ex: int arr[10];
Array Name Type Size Element Size Base Address … …
arr Int 10 2 1000
64
4 55 1008
1010
The address computing: 5 55
6 123 1012
base + index * element size;
7 55 1014
Case arr[6]:
8 55 1016
1000+6*2 = 1012
9 55 1018
Case arr[12]
10 55 1020
1000+12*2= 1024
11 55 1022
12 55 1024
66
• Ex:
int i , arr[10];
for(i = 0 ; i < 10 ; i ++)
scanf(“%d”, & arr[i]);
for (i = 9; i >=0 ; i --)
printf(“%d”, arr[i]);
67
• Declaration of N dimension:
• Data_Type Array_Name [Dim1_Size] [Dim2_Size] [Dim3_Size] …. [DimN_Size]; 68
0 55 1008
3 55 1022
55 1024
69
70
72
• Each key in the keyboard has an ASCII code, which is limited by one byte.
• At the first of computer generation the keyboard was limited not like today; there
was arrows or page up or down of function keys, …. etc.
• So, the new added keys needed ASCII code to be manipulated, so the Extended
Keys are appeared.
• Its ASCII encapsulated in two bytes, the lowest byte equals null and the second
byte has a code.
• When you pressed on an extended key there was 2 bytes are stored in the keyboard
local buffer.
• The following program clarify how to now any key if it is normal or extended and
print its code.
73
• Structure Meaning
• Structure definition (Abstract level)
• Structure declaration (Abstract level)
• Accessing Structure Members (Abstract level)
• Structure implementation in the memory (Implementation level)
• Array of Structures
• Introduction to highlight menu
78
Age float 4 2
Salary float 4 6
deduct float 4 10 1068
Bonus float 4 14
Name char[51] 51 18
69
e1.Salary = 333.3;
The offset of the field ‘Salary’ is added to the address if variable e1to reach to the
address of the field and store the data.
empArr[2].salary = 2315.6;
gets(empArr[3].Name);
scanf(“%f”,&empArr[0].bonus);
empArr[4].Name[2] = ‘T’;
• Note: if we use typedef keyword when defining the structure we can use the alias
name directly without need to use the struct keyword
11/23/2020 Copyright reserved ITI 2019 88
4.7 Introduction to Highlight Menu Assignment
New
Display
Exit
• up arrow, down arrow, home, end, enter and escape.
do{
0- clear the user screen
1- draw the menu with highlighted current item
2- read the pressed key from the user
3- take the suitable action dependent on the pressed key
}while(!terminated);
ch = getch();
• Modularity
• Function Header and prototype
• Function Parameters and Return Data Type
• Function Body
• Functions Arguments
• Sequence Passing arguments in C
• Recursion and its Constraints
• Introduction to Pointers
• Call by Value and Call by Address
103
104
• Function may have no return datatype, and may have no list of input parameters;
write void in both places.
• Function may have no return datatype, and may have list of input parameters; write
void at the beginning of header and write the type and name for each input
parameter.
• Function may have return datatype, and may have no list of input parameters; write
the return data type in the header of function –either primitive or complex- and
void in place of list of input parameters
• Function may have return datatype, and may have list of input parameters; write
the return data type in the header of function –either primitive or complex- and
write the type and name for each input parameter.
108
• The term parameter refers to any declaration within the parentheses following the
function name in a function declaration or definition; the term argument refers to
any expression within the parentheses of a function call.
• The following rules apply to parameters and arguments of C functions:
• Except for functions with variable-length argument lists, the number of arguments in a function
call must be the same as the number of parameters in the function definition. Or no parameters
nor arguments
• The maximum number of arguments (and corresponding parameters) is 253 for a single
function.
• Arguments are separated by commas. However, the comma is not an operator in this context
• Arguments are passed by value; that is, when a function is called, the parameter receives a copy
of the argument's value
• The scope of function parameters is the function itself. Therefore, parameters of the same name
in different functions are unrelated.
109
• We pass different arguments into some functions. Now one questions may come in
our mind, that what the order of evaluation of the function parameters. Is it left to
right, or right to left?
• To check the evaluation order we will use a simple program. Here some parameters
are passing. From the output we can find how they are evaluated.
110
#include<stdio.h>
void test_function(int x, int y, int z) {
printf("The value of x: %d\n", x);
printf("The value of y: %d\n", y);
printf("The value of z: %d\n", z);
}
main() {
int a = 10;
test_function(a++, a++, a++);
}
111
• From this output we can easily understand the evaluation sequence. At first the z is
taken, so it is holding 10, then y is taken, so it is 11, and finally x is taken. So the
value is 12.
112
• The return value for main indicates how the program exited. Normal exit is
represented by a 0 return value from main. Abnormal exit is signaled by a non-zero
return.
• As old fashion in C programming the values 1, 2, or 3 represent abnormal
termination and represent the following state for each value:
• 1 : abnormal exit without saying the reason
• 2 : abnormal exit for memory problem (could not allocate memory, …)
• 3 : abnormal exit for I/O problem (could not change driver mode, …)
• In general the using values are:
• Return 0 for normal exit : like calling function exit(0)
• Return non-zero value for abnormal exit: like calling function exit(1)
113
• How a particular problem is solved using recursion? The idea is to represent a problem in
terms of one or more smaller problems, and add one or more base conditions that stop the
recursion. For example, we compute factorial n if we know factorial of (n-1). The base case
for factorial would be n = 1. We return 1 when n = 1.
• Why Stack Overflow error occurs in recursion? If the base case is not reached or not
defined, then the stack overflow problem may arise.
• How memory is allocated to different function calls in recursion? When any function is
called from main(), the memory is allocated to it on the stack. A recursive function calls
itself, the memory for a called function is allocated on top of memory allocated to calling
function and different copy of local variables is created for each function call. When the base
case is reached, the function returns its value to the function by whom it is called and
memory is de-allocated and the process continues.
115
• Iteration version:
int Fact( int n)
{
int result=1, i;
for( i = n; i > 1; i--)
result *= i;
return result;
}
116
• Recursive version:
int RFact( int n)
{
if (n == 1)
return 1;
return n * Rfact( n-1 );
}
117
RFact(5)= 5 *
RFact(4) = 4 * Rfact(1)
Rfact(3) = 3 * return 1
Rfact(2)
RFact(2) = 2 *
return 2 * Rfact (1)
RFact(1) = 1 Rfact(3)
return 3 * Rfact (2)
Rfact(4)
return 4* Rfact (3)
Rfact(5)
return 5* Rfact (4)
• The following example generates the Fibonacci series for a given number using a
recursive function
int fib (int i) {
if(i == 1 || i == 2) {
return 1;
}
return fib (i-1) + fib (i-2);
}
119
int main(void) {
int i;
return 0;
}
120
Fib (3) Fib (2) Fib (2) Fib (1) Fib (2) Fib (1)
122
3 6 8 9 12 13
Fib (3) Fib (2) Fib (2) Fib (1) Fib (2) Fib (1)
4 5
123
124
}
11/23/2020 Copyright reserved ITI 2019 145
}
6.4 Pointer Comparisons
• The output will be as follow:
Address of arr[0] = fff0
Value of arr[0] = 10
Address of arr[1] = fff2
Value of arr[1] = 100
Address of arr[2] = fff4
Value of arr[2] = 200 arr
ptr 10 fff0
0
ptr 1 100 fff2
2 fff4
ptr 200
swap function
3265
5
temp
11/23/2020 Copyright reserved ITI 2019 150
6.6 Using Pointers to call by address: Passing
pointers to functions in C
• The solving of the above problem by using pointer to call the function and pass the
address of the variables as arguments not the values of the variables; Call by address.
As the following function: swap2
void swap2 (int * A, int * B)
{ int temp;
temp = *A;
*A = *B;
*B = temp;
}
• The using of this function will be as follow:
1002 x 5 7 y 1000
swap2 function
3265
5
temp
return NULL;
}