Summary

This document appears to contain programming exercises focusing on Do-while, Switch, and Pointer statements in C. It includes various examples and explanations.

Full Transcript

Exercises Do-while Switch Pointer Switch / Do-while While Do … Basic Difference:...

Exercises Do-while Switch Pointer Switch / Do-while While Do … Basic Difference: While While loop, the condition statement is at the beginning of the loop. In Do-While loop, the condition statement is at the end of the loop. While loop is checked once before the condition and is executed only if the condition is true. Do while loop can be executed at least once even if the condition is false. Flow Chart Explanation: Step 1) Start the do-while loop Flow Chart Explanation: Step 2) The body of do-while loop is executed Step 1) Start of while loop Step 3) The test expression or condition is evaluated Step 2) The test expression or condition is Step 4) If the test expression is true, the compiler executes evaluated the body of do-while loop Step 3) Next, if the test expression is true, the Step 5) Next, if the test expression is false, the compiler program executes the body of do-while loop executes the statements after the loop body Step 4) If the test expression is false, the program Step 6) Statements that come after the loop body are outside while loop is executed executed While While Do While This loop will execute the Do … It checks the condition first and then executes statement(s) statement(s) at least once, then the condition is checked. While While loop allows initialization of Do while loop allows initialization of counter variables before starting the counter variables before and after body of a loop. starting the body of a loop. It is an entry controlled loop. It is an exit controlled loop. We do not need to add a semicolon at We need to add a semicolon at the the end of a while condition. end of the while condition. In case of a single statement, we do Brackets are always needed. need to add brackets. In this loop, the condition is The loop condition is specified after mentioned at the starting of the loop. the block is executed. Statement(s) can be executed zero Statement is executed at least once. times if the condition is false. Write a C Program for UAV Operation Concept Solution 2: This solution is using Do- Solution 1: This solution is using While While loop Switch-Case A switch statement allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable being switched on is checked for each switch case. The switch-case statement is a decision-making statement in C. The if- else statement provides two alternative actions to be performed, whereas the switch-case construct is a multi-way branching statement. A switch statement in C simplifies multi-way choices by evaluating a single variable against multiple values, executing specific code based on the match. It allows a variable to be tested for equality against a list of values. Write C code for Simple Calculator (Using Switch-Case) A simple ATM: This ATM only allows withdrawal, deposit, and balance inquiry transactions. Pointers Why We Use Pointer? Features of Pointers: Pointers save memory space. To use memory more effectively. Because the pointer knows the address of a variable or object. Passing a unique value in a function (We can pass pointers to a function or method as a parameter. For example, void Print(data_type* argument)) Execution time with pointers is faster because data are manipulated with the address, that is, direct access to memory location. Pointers are used with data structures. They are useful for representing two-dimensional and multi-dimensional arrays. Programming more effectively in data structures such as Linked Lists, Tree etc. (used in most Basic Data structures). An array, of any type can be accessed with the help of pointers, without considering its subscript range. We can use pointers for arrays. I'll talk about pointer arithmetic later. Pointers are used for file handling. Memory is accessed efficiently with the pointers. The pointer assigns and releases the memory as well. Hence it can be said the Memory of pointers is dynamically allocated. Pointers are used to allocate memory dynamically. By calling the functions (malloc, free, realloc, calloc) provided by the C programming language, we can dynamically create/place/delete a memory that we have created ourselves on the memory. Notes Advantages of using Pointers Here, are pros/benefits of using Pointers Pointers are variables which store the address of other variables in C++. More than one variable can be modified and returned by function using pointers. Memory can be dynamically allocated and de-allocated using pointers. Pointers help in simplifying the complexity of the program. The execution speed of a program improves by using pointers. Summary: A pointer refers to a variable holding address of another variable. Each pointer has a valid data type. A pointer is a symbolic representation of a memory address. Pointers allow programs to simulate call-by-reference and create and manipulate dynamic data structures. Arrays and pointers use a related concept. The array name denotes the array’s base. If you want to assign the address of an array to a pointer, don’t use an ampersand (&). If there is no specific address to assign a pointer variable, assign it a NULL. Pointer -The physical area where the data is kept in the computer memory can be defined as the address. The address is associated with both hardware and software. In terms of hardware, the address consists of a number in the memory. - The microprocessor can only access a region in memory with the address information of that region. -Object addresses are determined jointly by the compiler and the operating system that installed the program on most systems. - The addresses of the objects cannot be known precisely before the program is loaded and cannot be determined in advance by the programmer. - The program writer or user can see the addresses of the objects only during the run time of the program. Pointer is the type of variable in which the address of the place in the memory area is stored. Pointers are assigned not the data, but the starting addresses of the memory cells where that data is stored in the memory. A pointer, like any other variable, is a numeric variable. For this reason, it should be declared in the program before it is used. Creating Pointers Syntax You learned from the previous chapter, that we can get the memory address of a variable by using the «&» operator: int myAge = 43; // an int variable printf("%d", myAge); // Outputs the value of myAge (43) printf("%p", &myAge); // Outputs the memory address of myAge (0x7ffe5367e044) A pointer however, is a variable that stores the memory address as its value. A pointer variable points to a data type(like int or string) of the same type, and is created with the* operator. The address of the variable you're working with is assigned to the pointer. Pointer Note: Pointers cannot work on their own and cannot take values, so they have to refer to another variable. In English : -Here, the pointer named "y" takes the variable named x as a reference and we can say «y equals the address of x". - In other words, the variable "y" is a pointer that can hold the address of any variable of type integer. -Also, we define y as int *y, that is, as an integer pointer so that we can assign the memory address of x to the variable y. -In the y=&x operation, the * sign is omitted to assign the reference value (ie address) of the variable x to y. This is a similar operation to other variables (int, char, etc.). In Turkish : -Burada "y" isimli işaretçi x isimli değişkeni referans olarak almaktadır ve “y eşittir x’nun adresi" diyebilmekteyiz. -Diğer bir deyişle, "y" değişkeni integer tipindeki herhangi bir değişkenin adresini tutabilecek olan bir işaretçidir. -Ayrıca, y değişkenine x'in bellek adresini atayabilmemiz için y'yi int *y şeklinde yani integer pointer olarak tanımlıyoruz. - y=&x işleminde y’ye x değişkenin referans değerinin (yani adresi) atanması için * işareti koyulmamıştır. Bu diğer değişkenlerde (int, char v.b.) yapılan işlemin bir benzeridir. Defining Pointer Type Variables (Memory) (The address of memory) There are two equivalent ways to access and modify variable content in C. Direct access, we use the variable name directly. Indirect access, we use a pointer to the variable. Address-of operator myvar=25; baz = *foo; foo = &myvar; bar=myvar; First, we have assigned the value 25 to myvar (a variable whose address in memory we assumed to be 1776). The second statement assigns foo the address of myvar, which we have assumed to be 1776. Finally, the third statement, assigns the value contained in myvar to bar. This is a standard assignment operation, as already done many times in earlier baz = foo; // baz equal to foo (1776) chapters. baz = *foo; // baz equal to value pointed to by foo (25) c The main difference between the second and third statements is the appearance of the address-of operator (&). The variable that stores the address of another variable (like foo in the previous example) is what in C is called a pointer. Pointers are a very powerful feature of the language that has many uses in lower level programming. A bit later, we will see how to declare and use pointers. Example: The program will show different values on each computer and each time the program is opened. Because the addresses taken from ram are uncertain. Examples: Examples Examples Examples Let’s Explain! Create a pointer variable with the name ptr, that points to a string variable, by using the asterisk sign* (string* ptr).Note that the type of the pointer has to match the type of the variable you're working with. Use the & operator to store the memory address of the You can also change the pointer's value. But note variable called student, and assign it to the pointer. that this will also change the value of the original variable: Now, ptr holds the value of student's memory address. Examples C program to demonstrate that compiler internally uses pointer arithmetic to access array elements. Pointer Arithmetic There are two types of arithmetic operations that can be performed on the pointer: 1. Sum 2. Subtraction. However, the value to be added or subtracted must be an integer. When the value of the pointer variable is increased by 1, the variable becomes a points to the next data block. The new value that the variable will take depends on what type of data block the pointer variable points to. Each time a pointer is incremented, a pointer of the same type is stored in memory. the next value, when decremented, is stored in memory shows the previous value. Example Using Arrays Printing the contents of the array to the screen with the help of a pointer Note : The sizeof() operator is a function which returns the size of any data type, expression, array, etc. It takes the data type or expression as a part of argument which is mandatory and returns the result *p++ // same as *(p++): increment pointer, and dereference unincremented address which is size of that data type in bytes. *++p // same as *(++p): increment pointer, and dereference incremented address ++*p // same as ++(*p): dereference pointer, and increment the value it points to (*p)++ // dereference pointer, and post-increment the value it points to Example // I define a function like this, it takes a pointer as a parameter, and de-references the value of this pointer, multiplies it by 2.54, and then assigns it to that value. *ptr *= 2.54; // We multiplied the value that came with the *ptr pointer by the number 2.54 and converted it to centimeters. We de-reference with the * sign we use on the far left and get the value of the pointer. the other * is the multiplication event we use because we multiply and add on. Change your variable using pointer Code Explanation: 1.Create a prototype of a function named test that will take two integer parameters. 2.Call the main() function. We will add the program logic inside its body. 3.Declare two integer variables a and b, each with a value of 5. 4.Print some text on the console. The endl (end line) will move the cursor to begin printing in the next line. 5.Print the value of variable a on the console alongside other text. The endl (end line) will move the cursor to begin printing in the next line. 6.Print the value of variable b on the console alongside other text. The endl (end line) will move the cursor to begin printing in the next line. 7.Create a function named test() that takes in the addresses of variable a and b as the parameters. 8.Print some text on the console. The \n will create a new blank line before the text is printed. The endl (end line) will move the cursor to begin printing in the next line after the text is printed. 9.Print the value of variable a on the console alongside other text. The endl (end line) will move the cursor to begin printing in the next line. 10.Print the value of variable b on the console alongside other text. The endl (end line) will move the cursor to begin printing in the next line. 11.The program must return value upon successful completion. 12.End of the body of the main() function. 13.Defining the function test(). The function should take two integer pointer variables *n1 and *n2. 14.Assigning the pointer variable *n1 a value of 10. Solutions of swap problem using different methods Example : Changing initial Solution 2 – Solution 3 – values using pointers and Function used method Method used together with function and pointer functions. C program to demonstrate that we can change local values of one function in another using pointers. a b Solution 1 – The simplest method We declare the function responsible for swapping the two variable values, which takes two integer pointers as parameters and returns any value when it is called. In the main function, we declare and initialize two integer variables (‘a’ and ‘b’) then we print their values respectively. We call the swap() function by passing the address of the two variables as arguments using the ampersand symbol. After that, we print the new swapped values of variables. Here we define the swap() function content which takes two integer variable addresses as parameters and declare a temporary integer variable used as a third storage box to save one of the value variables which will be put to the second variable. Save the content of the first variable pointed by ‘x’ in the temporary variable. Store the second variable pointed by y in the first variable pointed by x. Example: Double Pointer (Pointer to Pointer) Note: We already know that a pointer points to a location in memory and thus used to store address of variables. So, when we define a pointer to pointer. The first pointer is used to store the address of second pointer. That is why they are also known as double pointers. Example

Use Quizgecko on...
Browser
Browser