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

Week 1 - Basic Machine Organization and Program Execution

Here are the steps to print all prime numbers between two given numbers: 1. Take input of two numbers x and y from the user. 2. Iterate from x to y using a for loop. 3. Initialize a flag variable as 1 for each number. 4. Check if the number is perfectly divisible by any number between 2 and half of the number. 5. If divisible, set flag to 0. 6. After full check, if flag is still 1, print the number as it is prime. So the full code would look like: #include <stdio.h> int main() { int x, y, flag; printf("

Uploaded by

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

Week 1 - Basic Machine Organization and Program Execution

Here are the steps to print all prime numbers between two given numbers: 1. Take input of two numbers x and y from the user. 2. Iterate from x to y using a for loop. 3. Initialize a flag variable as 1 for each number. 4. Check if the number is perfectly divisible by any number between 2 and half of the number. 5. If divisible, set flag to 0. 6. After full check, if flag is still 1, print the number as it is prime. So the full code would look like: #include <stdio.h> int main() { int x, y, flag; printf("

Uploaded by

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

CSE 121 – Advanced C Programming

Dr. Nawal El Boghdady


[email protected]

WEEK 1: BASIC MACHINE ORGANIZATION AND PROGRAM EXECUTION


Welcome to CSE 121!

COURSE IMPORTANT ASSIGNMENT LABS ACADEMIC PRACTICE,


SYLLABUS DATES AND SUBMISSIONS INTEGRITY PRACTICE,
LOGISTICS POLICY PRACTICE!
Outline
Overview of Computer Systems

Computer Organization

Data Hierarchy

Setting up our environments


C Refresher:
Variables, Selection, Loops, Arrays
Overview of
Computer Systems
Overview of Computers
A machine which performs billions of operations per second

Needs to be informed of EXACTLY what to do (instructions)

These instructions are called programs => We create those using programming languages, e.g.
C++ (more later)

Source: pinterest.ch 5
History of Computers
Alan Turing (1912-1954)

Developed universal machine (Turing


machine) that in theory could be
programmed to solve any mathematical
problem

Mechanical machine used to crack Enigma


code

A ‘halting’ machine

Foundation over which modern theories of


computation were built

6
The Turing Machine

Source: The Imitation Game 7


Computer
Organization
Computer Organization

Process

Input Output

Source: Dr. Basma Hassan – CSE 021


Computer Architecture
•Von Neumann architecture: data
and instructions share the same
memory and signal pathways.
• 32-bit architecture Control Unit
• 64-bit architecture Input Output
Devices Devices
Arithmetic Logic Unit
•Contrast: Harvard architecture: (ALU)
data and instructions DO NOT
share the same memory and
pathways.
Memory Unit
•What is a potential problem with
Primary Secondary
the Harvard architecture? Storage Storage

Source: Dr. Basma Hassan – CSE 021


Data Hierarchy
Data Hierarchy

•Bits make up a Character


• Multiple character encoding schemes: e.g.
• Unicode
• ASCII

•Multiple characters make up a field

•Multiple fields make up a record

•Multiple records constitute a file

•Multiple files make up a database


How big is big data?
C Development
Environment
C Development Environment
Setting up our IDEs
Installing and Running Visual
Studio
This is a good source to follow:

https://docs.microsoft.com/en-us/cpp/build/vscpp-step-0-installation?view=msvc-170#visual-
studio-2022-installation
Creating a Visual Studio Project
Configuring Visual Studio for C
1. Right-click the project’s node— —in the and select to display the project’s dialog.

2. In the drop-down list, change to .

3. In the drop-down list, change to .

4. In the left column, expand the node, then select .

5. In the right column, click in the field to the right of , click the down arrow, then select

6. In the left column, in the node, select .

7. In the right column, at the end of the value for , insert ;_CRT_SECURE_NO_WARNINGS

8. In the left column, in the node, select .

9. In the right column, click in the field to the right of , click the down arrow, then select .

10. Click to save the changes.


Setting up CLion on Windows

We can get a free student license using our


EUI email addresses now!

CLion is a cross-platform IDE: works on


Windows, Mac, and Linux
Setting up CLion on Windows
If your compilation on Windows
runs in an infinite loop, kindly
do the following:

Go to Windows’ Settings, Time


and Date, turn off 'Set time
automatically' and turn it back
on.
Refreshing our C
Hello World

Libraries

Main function definition: Entry point to the program


Escape Sequences
Data Types
2 and 2.0 are not the same number
◦ A whole number such as 2 is of type int
◦ A real number such as 2.0 is of type double

Numbers of type int are stored as exact values


Numbers of type double may be stored as approximate
values due to limitations on number of significant
digits that can be represented
This is very important later when we try to implement checks for equality:
◦ Is 3.0 = 3.0????
Data Types

Which data types are missing from this


table?
Variable Declaration
int x;
Declaration
float y;

double z, sum;

x = 7; Initialization

float y = 3.2; Declaration AND


Initialization
Adding Numbers

Why do we use the & in scanf:


scanf(“%d”, &integer2)???
In other words, what would happen if I forget
the & sign?
Selection: If Statements
int a = 5;

int b = 6;

if (a > b)
printf(a);
else
printf(b);
Selection: Switch Statements
Write A C++ program that takes as an input the letter grade of a student in a course (grade) to compute and display its equivalent numeric
value according to the following rules:

grade Numeric Value

A 4.0

B 3.0

C 2.0

D 1.0

F 0.0

Allow the program to accept the letter grade uppercase or lower case.

Write your program twice, once using nested-if statement and second using switch statement.
Switch Statements – Nested If
//Output the student's GPA based on their letter grade

#include <stdio.h>
int main(void)
{
char grade;
printf("Enter your letter grade\n");
scanf_s("%c", & grade);

printf("The GPA is: ");

//Nested if
if ((grade == 'a') || (grade == 'A'))
printf("4.0\n");
else
if ((grade == 'b') || (grade == 'B'))
printf("3.0\n");
else
if ((grade == 'c') || (grade == 'C'))
printf("2.0\n");
else
if ((grade == 'd') || (grade == 'D'))
printf("1.0\n");
else
if ((grade == 'f') || (grade == 'F'))
printf("0.0\n");
}
Selections: Switch Statement
//switch case 'D’:
switch (grade) printf("1.0\n");
{ break;
case ‘a’: case 'f’:
printf("4.0\n"); printf("0.0\n");
break; break;
case 'A’: case 'F’:
printf("4.0\n"); printf("0.0\n");
break; break;
case 'b’:
printf("3.0\n"); }
break;
case 'B’:
printf("3.0\n");
break;
case 'c’:
printf("2.0\n");
break;
case 'C’:
printf("2.0\n");
break;
case 'd’:
printf("1.0\n");
break;
Iteration: For Loops
Implement the program that counts from 1-100 using a for loop:

for (int i = 1; i <= 100; i++)

printf(“%d\n”, i);

}
Iteration: While Loops versus
For Loops
Write a program that adds the numbers between 1 and 10 inclusive:
int sum = 0;
int n = 1;
while(n <= 10) // add the numbers 1 - 10
{
sum = sum + n;
n++;
}
sum = 0;
for (n = 1; n <= 10; n++) //add the numbers 1 - 10
sum = sum + n;
When to Choose For Loops and
When to Choose While Loops

A while-loop is typically used

◦ When a for-loop is not appropriate.


◦ One example is if you want your computer to do nothing until the user presses a key.
while (!key_press); //you cannot specify this in a for-loop!

◦ When there are circumstances for which the loop body should not be executed at all (like when you have to
tell the user to input an even number)
Output all Prime Numbers
between X and Y
/******************************************************************************

Printing Prime Numbers in a Range


*******************************************************************************/

#include <stdio.h>

void main()
{
int x, y, flag;
// Iterate to check if i is prime
printf("Enter two numbers:\n");
// or not
scanf_s("%d %d", &x, &y);
for (int j = 2; j <= i / 2; ++j) {
if (i % j == 0) {
flag = 0;
// Traverse each number in the
break;
// interval with the help of for loop
}
for (int i = x; i <= y; i++)
}
{
// flag = 1 means i is prime
// Skip 0 and 1 as they are
// and flag = 0 means i is not prime
// neither prime nor composite
if (flag == 1)
if (i == 1 || i == 0)
printf("%d ", i);
continue;
}
// flag variable to tell
}
// if i is prime or not
flag = 1;
Output all Prime Numbers
between X and Y: Output
Arrays
I want to store the grades of all my 70+ students in this class

Will I create 70 variables: s1, s2…s70??

What are the problems of this approach?

That is why we use the second type of data structure we learnt (after variables) called arrays.

Arrays are continuous blocks of memory slots booked for the same data type. We can define how
many slots we want and what the data type of all the slots is going to be.

We can only assign ONE data type to ALL the slots.


Arrays
•How do I declare arrays?
• int a[5]; //indices: 0,1,2,3,4; accepts int data type only
• float b[3]; //indices: 0,1,2; accepts floats

•How do I initialize arrays?


• I need to loop on all elements of the array to set them a value!
Arrays
C Exercise
Programs
Exercise 1
We go back to the example of the area of the circle:

1. Ask user to enter radius of the circle: ‘Please enter radius in meters’

2. Take the radius value and store it in a place (variables)

3. Compute the area of the circle following the equation 𝐴 = 𝜋𝑟 2 and store it in a variable

4. Display/output the computed value to the user: ‘The area of the circle is….m2’
Exercise 1
// Area of the circle the circle in meters.\n");
scanf_s("%f", &r);
#define _USE_MATH_DEFINES //We will
discuss these macros in detail //Compute the area
towards the end of the course a = M_PI * pow(r, 2);

#include<stdio.h> printf("The area of the circle is %f


#include<math.h> m^2.\n", a);

int main() return 0;


{
//Variable declaration
float r, a; }

//Prompt user to enter the radius in


meters
printf("Please enter the radius of
Exercise 2
Write a C program that takes three scores of a student in three tests to compute and display the
sum of the best-two scores.
Exercise 2
#include <stdio.h> //To be able to do this successfully, we need a third dummy variable, we call this
'temp' to store the value of one
void main() //of the variables we need to swap.
min = score3;
{
max2 = temp;
int score1, score2, score3, min, max1, max2, sum, temp;
}
printf("Please enter the three scores\n“);
scanf_s(“%d %d %d“, &score1, &score2, &score3);
sum = max1 + max2;
printf("The sum of the best two scores is: %d\n“, sum);
//Assume one of the scores is the min, and thus the other two are the best:
min = score1; max1 = score2; max2 = score3;
//Always debug/trace your code with sample input:
/*score1 = 20, score2 = 30, score3 = 40. In this situation, your program must
if (score2 < min) display 70 as the minimum score
{ score1 = 25, score2 = 10, score3 = 45. Here, the output should be 70
temp = min; //temp is a temporary holder for the value of min. It might not be score1 = 50, score2 = 100, score3 = 15. Here, the output should be 150
needed inside this if statement,
score1 = 100, score2 = 50, score3 = 12. Here, the output should be 150
//but it is definitely needed in the one below to avoid the value of min being
overwritten. Try commenting this
//assignment statement and see what happens!
min = score2; */
max1 = temp;
}

}
if (score3 < min)
{
temp = min; //These three assignment statements are what we call a 'swap' operation,
where we swap the values of two variables.
Exercise 3
Write a C program that sorts the elements of an array from smallest to largest.

Use Bubble sorting:


◦ Bubble sorting loops through the entire array and compares each element to the one before it (i-1 entry). If
the element stored at index i is less than that stored at index i-1, swap them.
◦ Do this for the whole array
◦ Then repeat this procedure until there are no more elements to swap.
Exercise 3: Bubble Sort
Exercise 3
while (swapped)
//Bubble Sort
{
swapped = false;
#include <stdio.h>
for (int i = 1; i < size; i++) //here we start
#include<stdbool.h>
at 1 because we want to test the i-1 index!
{
void main()
if (arr[i] < arr[i - 1])
{
{
enum { size = 5 }; //initializing constants in C
temp = arr[i - 1];
int arr[size];
arr[i - 1] = arr[i];
arr[i] = temp;
printf("Enter the %d array items\n", size);
swapped = true;
for (int i = 0; i < size; i++)
}
scanf_s("%d", &arr[i]);
}
}
bool swapped = true;
int temp; //will be used for the swapping algorithm
//output sorted array:
printf("The sorted array is: \n");

for (int i = 0; i < size; i++)


{
printf("%d ", arr[i]);
}
}
Exercise 3 Output

You might also like