C programming is a widely used programming language. The document provides an overview of key concepts in C programming including variables, data types, operators, decision and loop control statements, functions, pointers, arrays, strings, structures, and input/output functions. It also provides examples to illustrate concepts like arrays, strings, functions, pointers, and structures. The main function is the entry point for all C programs where code execution begins.
The document discusses various code optimization techniques that can be used to improve the efficiency of a program without changing its functionality. It covers techniques like using appropriate data types, avoiding global variables, using arrays instead of switch-case statements, combining loops, putting loops inside functions, and early termination of loops. Optimizing variables, control structures, functions and loops can help reduce memory usage and improve execution speed of a program.
Code optimization techniques aim to improve the efficiency of code without changing its output. Some key techniques include:
- Using appropriate variable types like unsigned integers to improve performance.
- Avoiding global variables which prevent register allocation and introduce overhead.
- Optimizing control structures like replacing if-else with switch.
- Loop optimizations like unrolling small loops, combining nested loops, and early termination.
- Function optimizations like putting loops inside functions and minimizing parameter passing.
- Other techniques like code motion to move invariant code out of loops.
This document provides an overview of the C programming language. It covers C fundamentals like data types and operators. It also discusses various control structures like decision making (if-else), loops (for, while, do-while), case control (switch) and functions. Additionally, it explains input/output operations, arrays and string handling in C. The document is presented as lecture notes with sections and subsections on different C concepts along with examples.
Detailing about basics of C language and its control structure for learning C Language for beginners. It covers looping statement , control statement etc.
This document discusses various concepts related to C programming including data types, operators, decision making statements, and loops. It begins with an example "Hello World" C program and explains each part. It then covers various data types in C like integer, float, char, etc. along with their sizes and ranges. Different types of operators like arithmetic, logical, assignment, increment/decrement are described. Decision making statements like if, if-else, if-else ladder, nested if, switch case are explained with examples. Finally, it briefly introduces the three types of loops in C - while, do-while, and for loops.
The document provides an overview of fundamental programming concepts in C language. It begins by comparing the steps to learning English and C, then discusses algorithms, flowcharts, tokens, data types, operators, control structures like if/else, switch, loops (while, do-while, for). It also covers nested loops, and illustrates an infinite loop that repeats until the user enters 'n'. The key topics covered include basic syntax, flow control, and programming constructs in C.
At the end of this lecture students should be able to;
Describe the looping structures in C programming language.
Practice the control flow of different looping structures in C programming language.
Practice the variants in control flow of different looping structures in C programming language.
Apply taught concepts for writing programs.
This C program takes in an integer from the user and converts it to its binary equivalent. It uses bitwise operators like right shift and AND to extract each bit and check if it is 1 or 0. A loop shifts the number by 31, 30, 29 ... 1, 0 bits and ANDs it with 1 each time to extract the bits, printing 1 for each bit that is 1 and 0 for each bit that is 0, effectively converting the decimal number to its 32-bit binary representation.
The document introduces different types of loops in C programming including while, for, and do-while loops. It explains that loops allow repeated execution of a block of code until a certain condition is met. The key types of loops are pretest and post-test loops, which differ in when the loop condition is evaluated. It provides examples of implementing various loops in C and using concepts like initialization, updating, nesting, and break/continue statements.
Control flow statements determine the order in which program instructions are executed. They include conditional branches (if/else), loops (while, for, do-while), and jumps. Arrays allow storing multiple values of the same type together in contiguous memory locations that can be individually referenced using an index. Multi-dimensional arrays generalize this by storing arrays inside other arrays, allowing modeling of matrices. They require nested loops for processing all elements.
Computer programming subject notes. Quick easy notes for C Programming.Cheat ...DR B.Surendiran .
The document provides an overview of C programming concepts including data types, variables, operators, conditional statements, loops, functions, arrays and more.
It begins with basic explanations and examples of comments, print statements, data types, input/output functions. Next, it covers conditional statements like if-else and examples to check even/odd and prime numbers. Loops like for and while are explained along with examples to iterate, count and print patterns. Other topics include functions, arrays, strings, structures and examples programs for calculations, pattern printing and sorting. Overall, the document serves as a useful reference for learning C programming fundamentals and common programming concepts.
This document provides an overview of an intermediate computer programming course at the University of Gondar in Ethiopia. The course code is CoEng2111 and it is taught by instructor Wondimu B. Topics that will be covered in the course include C++ basics, arrays, strings, functions, and recursion. The course materials are presented over several pages that define concepts, provide code examples, and explain key ideas like variables, data types, operators, and array implementation in C++.
The document provides instructions for a C++ programming assignment involving functions, pointers, arrays, and calculating pi. It includes 6 problems to solve:
1. Write functions to demonstrate default arguments, constant arguments, and random number generation.
2. Analyze sample code and identify errors in provided code snippets.
3. Write functions to calculate sums of various data types.
4. Use a Monte Carlo simulation to approximate pi by simulating dart throws on a circle and square.
5. Write functions to print, reverse, and transpose arrays.
6. Write functions to operate on strings and pointers.
This document contains C program code snippets and explanations for various programming problems including:
1) Finding perfect, Armstrong, and prime numbers as well as reversing, summing digits, and checking palindromes of numbers.
2) Converting between decimal and binary, multiplying matrices, and calculating LCM and factorial.
3) Checking for leap years and strong, palindrome, and generic root of numbers.
This document contains examples and explanations of various C programming concepts related to pointers, arrays, functions and preprocessor directives. It provides code snippets to demonstrate pointer operations, passing arrays to functions, macro definitions, enumerations and for loop expressions.
This document provides an overview of the C programming language. It covers various C language concepts like data types, operators, control structures, arrays, strings, functions and more. The document is divided into 9 sections with each section covering a specific C concept. For example, section 1 provides an introduction to C including its history, the difference between compilers and interpreters. Section 2 covers data types, constants and variables in C. Section 3 discusses operators and expressions. Section 4 explains various control structures like if-else, switch case etc. Section 5 is about looping constructs like while, do-while and for loops. Section 6 demonstrates looping with patterns. Section 7 describes arrays in C including 1D and 2D arrays. Section 8 covers
Here is a C program to produce a spiral array as described in the task:
#include <stdio.h>
int main() {
int n = 5;
int arr[n][n];
int num = 1;
int rowBegin = 0;
int rowEnd = n-1;
int colBegin = 0;
int colEnd = n-1;
while(rowBegin <= rowEnd && colBegin <= colEnd) {
// Top row
for(int i=colBegin; i<=colEnd; i++) {
arr[rowBegin][i] = num++;
}
rowBegin++;
// Right column
for(int i=rowBegin;
The document discusses repetition structures in C programming such as for loops, while loops, and nested loops. It provides examples of calculating a series sum using a for loop, checking if a number is prime using a for loop and selection statement inside the loop, and calculating an alternating series using a for loop. It also demonstrates the use of break and continue statements inside loops. Finally, it presents some homework problems involving loop structures.
This document provides an introduction to C++ programming concepts including basic syntax, variables, data types, operators, conditionals, and loops. It begins with an overview of basic printing, variables, comments, input/output, and the modulus operator. Examples are given for declaring integer, float, and char variables and performing arithmetic operations. Concepts covered for conditionals include if/else, else if ladders, ternary operators, and switch statements. Examples are provided for taking input and printing output based on conditions. The document concludes with an introduction to loops, focusing on the for loop syntax and using loops to print patterns and tables. Homework questions are provided throughout for additional practice.
C programming uses basic elements like expressions, statements, blocks and functions. Expressions combine constants, variables and operators, while statements end with semicolons. A block of statements is treated as a single statement. Standard library functions include printf(), exit() and scanf(). Control structures like if-else, switch, for, while and do-while statements are used for decision making and looping.
The document discusses C programming concepts including control statements, loops, relational operators, data types, arrays, and functions. It provides code examples to demonstrate while, for, do-while loops, if/else statements, functions, arrays, and more. Various outputs are shown for the example code snippets.
The document contains 14 code snippets that provide solutions to common programming problems in C including: printing patterns like numbers, stars, triangles using loops; finding sum of digits, checking palindrome, Armstrong number; sorting arrays using bubble, selection sort; string operations like concatenation; matrix addition; factorial; checking even-odd; Floyd's triangle. Each code snippet includes the header files, function definitions and main function to accept input, call functions and print output.
The document contains 14 code snippets that provide solutions to common programming problems in C including: printing patterns like numbers, stars, triangles using loops; finding sum of digits, checking palindrome, Armstrong number; sorting arrays using bubble sort, selection sort; string operations like concatenation; matrix addition; factorial calculation; checking even/odd number. Each code snippet includes the header files, function definitions and main function to accept input, call functions and print output.
The document discusses C programming concepts including operators, loops, functions, pointers, and file handling. It contains sample code to demonstrate:
1) Summing integers entered interactively using a while loop.
2) Calculating the average length of text lines using global variables and functions.
3) Adding and subtracting numbers using pointer variables and dereferencing operators.
4) Checking for a null pointer and using it as a placeholder.
5) Searching a specified file for a given character using command line arguments.
SVD is a powerful matrix factorization technique used in machine learning, data science, and AI. It helps with dimensionality reduction, image compression, noise filtering, and more.
Mastering SVD can give you an edge in handling complex data efficiently!
Ad
More Related Content
Similar to Introduction to C Programming -Lecture 3 (20)
At the end of this lecture students should be able to;
Describe the looping structures in C programming language.
Practice the control flow of different looping structures in C programming language.
Practice the variants in control flow of different looping structures in C programming language.
Apply taught concepts for writing programs.
This C program takes in an integer from the user and converts it to its binary equivalent. It uses bitwise operators like right shift and AND to extract each bit and check if it is 1 or 0. A loop shifts the number by 31, 30, 29 ... 1, 0 bits and ANDs it with 1 each time to extract the bits, printing 1 for each bit that is 1 and 0 for each bit that is 0, effectively converting the decimal number to its 32-bit binary representation.
The document introduces different types of loops in C programming including while, for, and do-while loops. It explains that loops allow repeated execution of a block of code until a certain condition is met. The key types of loops are pretest and post-test loops, which differ in when the loop condition is evaluated. It provides examples of implementing various loops in C and using concepts like initialization, updating, nesting, and break/continue statements.
Control flow statements determine the order in which program instructions are executed. They include conditional branches (if/else), loops (while, for, do-while), and jumps. Arrays allow storing multiple values of the same type together in contiguous memory locations that can be individually referenced using an index. Multi-dimensional arrays generalize this by storing arrays inside other arrays, allowing modeling of matrices. They require nested loops for processing all elements.
Computer programming subject notes. Quick easy notes for C Programming.Cheat ...DR B.Surendiran .
The document provides an overview of C programming concepts including data types, variables, operators, conditional statements, loops, functions, arrays and more.
It begins with basic explanations and examples of comments, print statements, data types, input/output functions. Next, it covers conditional statements like if-else and examples to check even/odd and prime numbers. Loops like for and while are explained along with examples to iterate, count and print patterns. Other topics include functions, arrays, strings, structures and examples programs for calculations, pattern printing and sorting. Overall, the document serves as a useful reference for learning C programming fundamentals and common programming concepts.
This document provides an overview of an intermediate computer programming course at the University of Gondar in Ethiopia. The course code is CoEng2111 and it is taught by instructor Wondimu B. Topics that will be covered in the course include C++ basics, arrays, strings, functions, and recursion. The course materials are presented over several pages that define concepts, provide code examples, and explain key ideas like variables, data types, operators, and array implementation in C++.
The document provides instructions for a C++ programming assignment involving functions, pointers, arrays, and calculating pi. It includes 6 problems to solve:
1. Write functions to demonstrate default arguments, constant arguments, and random number generation.
2. Analyze sample code and identify errors in provided code snippets.
3. Write functions to calculate sums of various data types.
4. Use a Monte Carlo simulation to approximate pi by simulating dart throws on a circle and square.
5. Write functions to print, reverse, and transpose arrays.
6. Write functions to operate on strings and pointers.
This document contains C program code snippets and explanations for various programming problems including:
1) Finding perfect, Armstrong, and prime numbers as well as reversing, summing digits, and checking palindromes of numbers.
2) Converting between decimal and binary, multiplying matrices, and calculating LCM and factorial.
3) Checking for leap years and strong, palindrome, and generic root of numbers.
This document contains examples and explanations of various C programming concepts related to pointers, arrays, functions and preprocessor directives. It provides code snippets to demonstrate pointer operations, passing arrays to functions, macro definitions, enumerations and for loop expressions.
This document provides an overview of the C programming language. It covers various C language concepts like data types, operators, control structures, arrays, strings, functions and more. The document is divided into 9 sections with each section covering a specific C concept. For example, section 1 provides an introduction to C including its history, the difference between compilers and interpreters. Section 2 covers data types, constants and variables in C. Section 3 discusses operators and expressions. Section 4 explains various control structures like if-else, switch case etc. Section 5 is about looping constructs like while, do-while and for loops. Section 6 demonstrates looping with patterns. Section 7 describes arrays in C including 1D and 2D arrays. Section 8 covers
Here is a C program to produce a spiral array as described in the task:
#include <stdio.h>
int main() {
int n = 5;
int arr[n][n];
int num = 1;
int rowBegin = 0;
int rowEnd = n-1;
int colBegin = 0;
int colEnd = n-1;
while(rowBegin <= rowEnd && colBegin <= colEnd) {
// Top row
for(int i=colBegin; i<=colEnd; i++) {
arr[rowBegin][i] = num++;
}
rowBegin++;
// Right column
for(int i=rowBegin;
The document discusses repetition structures in C programming such as for loops, while loops, and nested loops. It provides examples of calculating a series sum using a for loop, checking if a number is prime using a for loop and selection statement inside the loop, and calculating an alternating series using a for loop. It also demonstrates the use of break and continue statements inside loops. Finally, it presents some homework problems involving loop structures.
This document provides an introduction to C++ programming concepts including basic syntax, variables, data types, operators, conditionals, and loops. It begins with an overview of basic printing, variables, comments, input/output, and the modulus operator. Examples are given for declaring integer, float, and char variables and performing arithmetic operations. Concepts covered for conditionals include if/else, else if ladders, ternary operators, and switch statements. Examples are provided for taking input and printing output based on conditions. The document concludes with an introduction to loops, focusing on the for loop syntax and using loops to print patterns and tables. Homework questions are provided throughout for additional practice.
C programming uses basic elements like expressions, statements, blocks and functions. Expressions combine constants, variables and operators, while statements end with semicolons. A block of statements is treated as a single statement. Standard library functions include printf(), exit() and scanf(). Control structures like if-else, switch, for, while and do-while statements are used for decision making and looping.
The document discusses C programming concepts including control statements, loops, relational operators, data types, arrays, and functions. It provides code examples to demonstrate while, for, do-while loops, if/else statements, functions, arrays, and more. Various outputs are shown for the example code snippets.
The document contains 14 code snippets that provide solutions to common programming problems in C including: printing patterns like numbers, stars, triangles using loops; finding sum of digits, checking palindrome, Armstrong number; sorting arrays using bubble, selection sort; string operations like concatenation; matrix addition; factorial; checking even-odd; Floyd's triangle. Each code snippet includes the header files, function definitions and main function to accept input, call functions and print output.
The document contains 14 code snippets that provide solutions to common programming problems in C including: printing patterns like numbers, stars, triangles using loops; finding sum of digits, checking palindrome, Armstrong number; sorting arrays using bubble sort, selection sort; string operations like concatenation; matrix addition; factorial calculation; checking even/odd number. Each code snippet includes the header files, function definitions and main function to accept input, call functions and print output.
The document discusses C programming concepts including operators, loops, functions, pointers, and file handling. It contains sample code to demonstrate:
1) Summing integers entered interactively using a while loop.
2) Calculating the average length of text lines using global variables and functions.
3) Adding and subtracting numbers using pointer variables and dereferencing operators.
4) Checking for a null pointer and using it as a placeholder.
5) Searching a specified file for a given character using command line arguments.
SVD is a powerful matrix factorization technique used in machine learning, data science, and AI. It helps with dimensionality reduction, image compression, noise filtering, and more.
Mastering SVD can give you an edge in handling complex data efficiently!
"Feed Water Heaters in Thermal Power Plants: Types, Working, and Efficiency G...Infopitaara
A feed water heater is a device used in power plants to preheat water before it enters the boiler. It plays a critical role in improving the overall efficiency of the power generation process, especially in thermal power plants.
🔧 Function of a Feed Water Heater:
It uses steam extracted from the turbine to preheat the feed water.
This reduces the fuel required to convert water into steam in the boiler.
It supports Regenerative Rankine Cycle, increasing plant efficiency.
🔍 Types of Feed Water Heaters:
Open Feed Water Heater (Direct Contact)
Steam and water come into direct contact.
Mixing occurs, and heat is transferred directly.
Common in low-pressure stages.
Closed Feed Water Heater (Surface Type)
Steam and water are separated by tubes.
Heat is transferred through tube walls.
Common in high-pressure systems.
⚙️ Advantages:
Improves thermal efficiency.
Reduces fuel consumption.
Lowers thermal stress on boiler components.
Minimizes corrosion by removing dissolved gases.
Sorting Order and Stability in Sorting.
Concept of Internal and External Sorting.
Bubble Sort,
Insertion Sort,
Selection Sort,
Quick Sort and
Merge Sort,
Radix Sort, and
Shell Sort,
External Sorting, Time complexity analysis of Sorting Algorithms.
☁️ GDG Cloud Munich: Build With AI Workshop - Introduction to Vertex AI! ☁️
Join us for an exciting #BuildWithAi workshop on the 28th of April, 2025 at the Google Office in Munich!
Dive into the world of AI with our "Introduction to Vertex AI" session, presented by Google Cloud expert Randy Gupta.
RICS Membership-(The Royal Institution of Chartered Surveyors).pdfMohamedAbdelkader115
Glad to be one of only 14 members inside Kuwait to hold this credential.
Please check the members inside kuwait from this link:
https://www.rics.org/networking/find-a-member.html?firstname=&lastname=&town=&country=Kuwait&member_grade=(AssocRICS)&expert_witness=&accrediation=&page=1
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...Infopitaara
A Boiler Feed Pump (BFP) is a critical component in thermal power plants. It supplies high-pressure water (feedwater) to the boiler, ensuring continuous steam generation.
⚙️ How a Boiler Feed Pump Works
Water Collection:
Feedwater is collected from the deaerator or feedwater tank.
Pressurization:
The pump increases water pressure using multiple impellers/stages in centrifugal types.
Discharge to Boiler:
Pressurized water is then supplied to the boiler drum or economizer section, depending on design.
🌀 Types of Boiler Feed Pumps
Centrifugal Pumps (most common):
Multistage for higher pressure.
Used in large thermal power stations.
Positive Displacement Pumps (less common):
For smaller or specific applications.
Precise flow control but less efficient for large volumes.
🛠️ Key Operations and Controls
Recirculation Line: Protects the pump from overheating at low flow.
Throttle Valve: Regulates flow based on boiler demand.
Control System: Often automated via DCS/PLC for variable load conditions.
Sealing & Cooling Systems: Prevent leakage and maintain pump health.
⚠️ Common BFP Issues
Cavitation due to low NPSH (Net Positive Suction Head).
Seal or bearing failure.
Overheating from improper flow or recirculation.
Passenger car unit (PCU) of a vehicle type depends on vehicular characteristics, stream characteristics, roadway characteristics, environmental factors, climate conditions and control conditions. Keeping in view various factors affecting PCU, a model was developed taking a volume to capacity ratio and percentage share of particular vehicle type as independent parameters. A microscopic traffic simulation model VISSIM has been used in present study for generating traffic flow data which some time very difficult to obtain from field survey. A comparison study was carried out with the purpose of verifying when the adaptive neuro-fuzzy inference system (ANFIS), artificial neural network (ANN) and multiple linear regression (MLR) models are appropriate for prediction of PCUs of different vehicle types. From the results observed that ANFIS model estimates were closer to the corresponding simulated PCU values compared to MLR and ANN models. It is concluded that the ANFIS model showed greater potential in predicting PCUs from v/c ratio and proportional share for all type of vehicles whereas MLR and ANN models did not perform well.
Fluid mechanics is the branch of physics concerned with the mechanics of fluids (liquids, gases, and plasmas) and the forces on them. Originally applied to water (hydromechanics), it found applications in a wide range of disciplines, including mechanical, aerospace, civil, chemical, and biomedical engineering, as well as geophysics, oceanography, meteorology, astrophysics, and biology.
It can be divided into fluid statics, the study of various fluids at rest, and fluid dynamics.
Fluid statics, also known as hydrostatics, is the study of fluids at rest, specifically when there's no relative motion between fluid particles. It focuses on the conditions under which fluids are in stable equilibrium and doesn't involve fluid motion.
Fluid kinematics is the branch of fluid mechanics that focuses on describing and analyzing the motion of fluids, such as liquids and gases, without considering the forces that cause the motion. It deals with the geometrical and temporal aspects of fluid flow, including velocity and acceleration. Fluid dynamics, on the other hand, considers the forces acting on the fluid.
Fluid dynamics is the study of the effect of forces on fluid motion. It is a branch of continuum mechanics, a subject which models matter without using the information that it is made out of atoms; that is, it models matter from a macroscopic viewpoint rather than from microscopic.
Fluid mechanics, especially fluid dynamics, is an active field of research, typically mathematically complex. Many problems are partly or wholly unsolved and are best addressed by numerical methods, typically using computers. A modern discipline, called computational fluid dynamics (CFD), is devoted to this approach. Particle image velocimetry, an experimental method for visualizing and analyzing fluid flow, also takes advantage of the highly visual nature of fluid flow.
Fundamentally, every fluid mechanical system is assumed to obey the basic laws :
Conservation of mass
Conservation of energy
Conservation of momentum
The continuum assumption
For example, the assumption that mass is conserved means that for any fixed control volume (for example, a spherical volume)—enclosed by a control surface—the rate of change of the mass contained in that volume is equal to the rate at which mass is passing through the surface from outside to inside, minus the rate at which mass is passing from inside to outside. This can be expressed as an equation in integral form over the control volume.
The continuum assumption is an idealization of continuum mechanics under which fluids can be treated as continuous, even though, on a microscopic scale, they are composed of molecules. Under the continuum assumption, macroscopic (observed/measurable) properties such as density, pressure, temperature, and bulk velocity are taken to be well-defined at "infinitesimal" volume elements—small in comparison to the characteristic length scale of the system, but large in comparison to molecular length scale
The Fluke 925 is a vane anemometer, a handheld device designed to measure wind speed, air flow (volume), and temperature. It features a separate sensor and display unit, allowing greater flexibility and ease of use in tight or hard-to-reach spaces. The Fluke 925 is particularly suitable for HVAC (heating, ventilation, and air conditioning) maintenance in both residential and commercial buildings, offering a durable and cost-effective solution for routine airflow diagnostics.
4. Loops
#include <stdio.h>
int main () {
printf(”Hello World");
printf(”Hello World");
printf(”Hello World");
printf(”Hello World");
printf(”Hello World");
printf(”Hello World");
printf(”Hello World");
printf(”Hello World");
printf(”Hello World");
printf(”Hello World");
return 0;
}
What if someone asks you to print 'Hello World'
10 times?
- One way is to write the printf statement 10 times.
But that is definitely not a good idea if you have
to write it 500 times!
Three types of loops in C:
1. for
2. while
3. do while
5. 1) For Loop
for (initialization; test condition; increment or decrement) {
// code to be executed
}
#include <stdio.h>
int main() {
for (int count = 1; count <= 10; count = count + 1) {
printf("%dn", count);
}
return 0;
}
8. Example 1
#include <stdio.h>
int main() {
int i = 1, number = 0; // Declare the variables
printf("Enter a number: ");
scanf("%d", &number);
// for (Initialization ; Condition ; Inc/Dec )
for (i = 1; i <= 10; i++) {
printf("%d * %d = %dn", number, i, (number * i));
}
return 0;
}
9. Example 2
#include <stdio.h>
int main()
{
unsigned long n, j;
printf("Enter a number: ");
scanf("%li", &n);
for (j = 2; j <= n / 2; j++)
if (n % j == 0)
{
printf("It's not prime; divisible by %in", j);
return 0; //exit from the program
}
printf("It's prime!");
return 0;
}
10. Example 3
#include <stdio.h>
int main() {
int number = 0, sum = 0; // Declare the variables
printf("Enter a positive integer: ");
scanf("%d", &number); // Take the number
// for (Initialization ; Condition ; Inc/Dec )
for (int i = 1; i <= number; i++) {
sum = sum + i;
}
printf("Sum = %d", sum);
return 0;
}
11. Multiple Initialization and Test Expressions
#include <stdio.h>
int main() {
for (int i = 1, j = 5; j > 0; i++, j--) {
printf("i = %i, j = %in", i, j);
}
return 0;
}
Output:
12. Infinite For Loop
#include <stdio.h>
int main() {
for ( ; ; ) {
printf("Infinite Loop!n");
}
return 0;
}
Infinitive for loop in C
To make a for loop infinite, we need not give any expression in the syntax. Instead of that,
we need to provide two semicolons to validate the syntax of the for loop. This will work as an
infinite for loop.
17. 3) Do-While Loop
o The do while loop is a post tested loop. Using the do-while loop, we can repeat the execution of
several parts of the statements. The do-while loop is mainly used in the case where we need to
execute the loop at least once.
do {
// code to be executed
} while (condition);
#include <stdio.h>
int main() {
int count = 1;
do {
printf("Hello Worldn");
count++;
} while (count <= 10); // stop condition
return 0;
}
18. int x = 0
do {
printf("Hello");
x = x + 1;
} while (x < 50);
2
3) Do-While Loop – Example
Example:
1
3
4
19. Which type of loop to use?
– The for loop is appropriate when you know in advance how many times the
loop will be executed.
– The while and do while loops are used when you don’t know in advance
when the loop will terminate.
– The while loop when you may not want to execute the loop body even once.
– The do while loop when you’re sure you want to execute the loop body at
least once.
20. Task 3
– Write a C Program of a calculator using do-while loop.
21. Break Statement
– The break is a keyword in C which is used to bring the program control
out of the loop or switch.
– The break statement breaks the loop one by one, i.e., in the case of
nested loops, it breaks the inner loop first and then proceeds to outer
loops.
– The break statement in C can be used in the following two scenarios:
• With switch case
• With loops
23. Break Statement – Example
#include <stdio.h>
int main() {
int i;
for (i = 0; i < 10; i = i + 1) {
printf("%d ", i);
if (i == 5)
break;
}
printf("came outside of loop i = %d", i);
return 0;
}
24. Continue Statement
● The continue statement in C language is used to bring the program
control to the beginning of the loop.
● The continue statement skips some lines of code inside the loop and
continues with the next iteration.
● It is mainly used for a condition so that we can skip some code for a
particular condition.
26. Continue Statement (Cont.)
#include <stdio.h>
int main() {
int i;
for (i = 0; i < 10; i = i + 1) {
printf("%dn", i);
if (i == 5)
continue;
}
return 0;
}
28. Arrays in C
– An array is a multiple values of the same data type that can be stored
with only one variable name.
– The use of arrays allows for the development of smaller and more clearly
readable programs.
A
B
C
D
E
F
0
1
2
3
4
5
Array indices generally start with zero;
the first element of an array is zero
elements away from the start, the
next is one element away from the
start, and so on.
Tip:
29. Arrays in C (Cont.)
– Consider a scenario where you need to store 100 students scores in the exam
and then calculate the average.
int student1, student2, student3 … student100;
scanf("%i", student1);
scanf("%i", student2);
…
scanf("%i", student100);
float average = (student1 + student2 + student3
…. student100) / 100.0
Why don't we have a single
variable that holds all the
students variables ?!
30. Arrays in C (Cont.)
Array
30 89 97 89 68 22 17 63 55 40
0 1 2 3 4 5 6 7 8 9
Array Length = 10
First Index = 0
Last index = 9
← Array indices
← Array values
int arr[10];
Tip: Arrays in programming are similar to vectors or matrices in
mathematics.
All the array elements occupy
contiguous space in memory.
name no. elements
The topmost element is arr[9], there’s no arr[10]
32. Total size of the array
#include <stdio.h>
int main()
{
int arr[5]= { 10, 20, 30, 40, 50 };
printf("Total size of arr: %in", sizeof(arr)); // 5 ints * 4 bytes
for (int i = 0; i < 5; i++)
printf("%in", arr[i]);
return 0;
}
– It’s not feasible to enter the size of the array statically, thus, there should be away
to use a dynamic way.
33. No. elements in the array
#include <stdio.h>
int main() {
// Index: 0 1 2 3 4
int arr[5] = { 10, 20, 30, 40, 50 };
int no_elements = sizeof(arr) / sizeof(int);
printf("No. Elements: %in", no_elements);
for (int i = 0; i < no_elements; i++)
printf("%in", arr[i]);
return 0;
}
Example:
34. /*
no. elements = 5 integers
size of int = 4 bytes
total size = no. elements x size of int
= 5 4
= 20 bytes
no. elements = total size / size of int
= 20 / 4
= 5
*/
35. Contiguous space in memory
#include <stdio.h>
int main() {
int arr[5];
printf("Size of int: %in", sizeof(int));
for (int i = 0; i < 5; i++)
printf("Address of arr[%d] is %pn", i, &arr[i]);
return 0;
}
Example:
36. Accessing array elements
Array
40 55 63 17 22 68 89 97 89 30
0 1 2 3 4 5 6 7 8 9
Index = 8
arr[8];
– You can use array subscript (or index) to access any element stored in an array,
by using a numeric index in square brackets [] .
arr[5];
37. Accessing array elements
– Arrays are a real convenience for many problems, but there is not a lot that C will
do with them for you automatically.
– In particular, you can neither set all elements of an array a once nor assign one
array to another; both of the assignments
arr = 0; /* WRONG */
int arr2[10];
arr2 = arr; /* WRONG */
for(int i = 0; i < 10; i++)
arr[i] = 0;
for(int i = 0; i < 10; i++)
arr2[i] = arr[i];
illegal
legal
38. Index out of bounds
– There's no index out of bounds checking in C/C++, thus, it may produce
unexpected output when using an out of bound index.
// This C program compiles fine as index out of bound is not checked in C.
#include <stdio.h>
int main() {
int arr[2];
printf("%d ", arr[3]);
printf("%d ", arr[-2]);
return 0;
}
39. Array Declaration
– It’s possible to initialize some or all elements of an array when the array is
defined.
int arr[10] = {40, 55, 63, 17, 22, 68, 89, 97, 89, 30};
int arr[10] = {40, 55, 63, 17, 22, 68, 89};
9 8 7 6 5 4 3 2 1 0 ← index
int arr[] = {40, 55, 63, 17, 22};
Same as arr[5]
40. Array Declaration
– It is possible to initialize some or all elements of an array when the array is
defined.
int a[10] = {40, 55, 63, 17, 22, 68, 89, 97, 89, 30};
int a[10] = {40, 55, 63, 17, 22, 68, 89};
0 1 2 3 4 5 6 7 8 9 ← index
int a[] = {40, 55, 63, 17, 22};
Tip: Arrays are not limited to type int; you can have arrays of char or double or any other
type, but keep in mind that all the elements should be of the same data type.
41. Initializing and Printing array elements
– Arrays are a real convenience for many problems, but there is not a lot that C will
do with them for you automatically.
#include <stdio.h>
int main() {
int arr[] = {10, 20, 30, 40, 50};
int size = sizeof(arr) / sizeof(int);
printf("Size of arr[] = %dn", size);
for (int i = 0; i < size; i++)
printf("arr[%d] = %dn", i, arr[i]);
return 0;
}
42. #include <iostream>
using namespace std;
int main()
{
int month, day, total_days;
int days_per_month[12] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
cout << "nEnter a month (1 to 12): "; //get date
cin >> month;
cout << "Enter a day (1 to 31): ";
cin >> day;
total_days = day; //separate days
for (int j = 0; j < month - 1; j++) //add days each month
total_days += days_per_month[j];
cout << "Total days from start of year is: " << total_days << endl;
return 0;
}
43. Arrays of Arrays (Multidimensional Arrays)
– We can use array of arrays which is organized as matrices and can be represented
as a collection of rows and columns.
0 1 2
0 40 55 63
1 17 22 68
2 89 97 89
3 30 15 27
Columns
Rows
int arr[4][3] = { {40, 55, 63}, {17, 22, 68}, {89, 97, 89}, {30, 15, 27} };
0 1 2 3
0 1 2 0 1 2 0 1 2 0 1 2
• In the 1D array, we don't need to specify the size of the array if the
declaration and initialization are being done simultaneously.
• However, this will not work with 2D arrays, you have to define at
least the second dimension of the array.
44. Printing the ND array elements
#include <stdio.h>
int main() {
int arr[][3] = {
{10, 20, 30},
{40, 50, 60},
{70, 80, 90}
};
int rows = sizeof(arr) / sizeof(arr[0]);
int columns = sizeof(arr[0]) / sizeof(arr[0][0]);
for (int i = 0; i < rows; i++)
for (int j = 0; j < columns; j++)
printf("arr[%d][%d] = %dn", i, j, arr[i][j]);
return 0;
}
45. Array of Strings
#include <stdio.h>
int main()
{
const int DAYS = 7; //number of strings in array
const int MAX = 10; //maximum size of each string
//array of strings
char star[DAYS][MAX] = { "Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday" };
for (int j = 0; j < DAYS; j++) //display every string
printf("%sn", star[j]);
return 0;
}
48. Strings in C
– In C programming, a string is a sequence/array of characters
terminated with a null character 0.
H e l l o W o r l d 0
char c[] = "Hello World";
End of string
char c[] = "abcd";
char c[50] = "abcd";
char c[] = { 'a', 'b', 'c', 'd', '0' };
char c[5] = { 'a', 'b', 'c', 'd', '0' };
← index
0 1 2 3 4 5 6 7 8 9 10 11
49. Strings in C
char c[100];
c = "C programming"; // Error!
#include <stdio.h>
int main() {
char name[20];
printf("Enter name: ");
scanf("%s", name); // no & used
printf("Your name is %s.", name);
return 0;
}
1
2
50. Printing String Values
#include <stdio.h>
int main()
{
char str[] = "Hello World!";
// Method #1
printf("str = %sn", str);
// Method #2
for (int i = 0; i < sizeof(str) / sizeof(char); ++i)
printf("%c", str[i]);
return 0;
}
51. A more efficient way
#include <stdio.h>
int main()
{
char str[] = "Hello World!";
// Method #1
printf("str = %sn", str);
// Method #2
for (int i = 0, arr_size = sizeof(str) / sizeof(char); i < arr_size; ++i)
printf("%c", str[i]);
return 0;
}
52. Strings in C
#include <stdio.h>
int main()
{
char name[30];
printf("Enter name: ");
fgets(name, sizeof(name), stdin); // read string
printf("Name: ");
puts(name); // display string
return 0;
}
53. More about strings
– Note that that character ‘H’ is different from the string “H”.
char str[] = "Hello";
str[0] = "H";
char str[] = "Hello";
str[0] = 'H';
/* WRONG */ /* VALID */
– To convert a string to int you can the function atoi().
#include <stdlib.h>
char str[] = "123";
int x = atoi(str);
54. More about strings
– The following is correct since we are dealing with character representation of
digits ('0' to '9'). Characters in C are represented by their ASCII values, and
the ASCII value of character '0' is 48, '1' is 49, and so on.
– In other words, you subtract the ASCII value.
printf("%i", '1' - '0');
char state[5][3] = {"AA","BB","CC","DD","EE" };
– Strings multidimensional array:
55. Strings in C
– Commonly used String functions
strlen() calculates the length of a string
strcpy() copies a string to another
strcmp() compares two strings
strcat() concatenates two strings
#include <string.h>
56. strlen() – Length of the string
#include <stdio.h>
#include <string.h>
int main() {
char name[] = "Mohamed Gamal";
printf("The length is: %d", strlen(name));
return 0;
}
o strlen(): returns the actual string size, excluding 0.
o sizeof(): return the string size, including 0.
57. Example
#include <stdio.h>
#include <string.h> //for strlen()
int main()
{ //initialized string
char str1[] = "Oh, Captain, my Captain! our fearful trip is done";
char str2[80]; //empty string
int j;
for (j = 0; j < strlen(str1); j++) //copy strlen characters
str2[j] = str1[j]; // from str1 to str2
str2[j] = '0'; //insert NULL at end
printf("%s", str2); //display str2
return 0;
}
58. strcpy() – Copy a string into another
#include <stdio.h>
#include <string.h>
int main() {
char name[] = "Mohamed Gamal";
char copy[14];
strcpy(copy, name); // destination, source
printf("Source string: %s", name);
printf("Copied string: %s", copy);
return 0;
}
59. strcmp() – Compare two strings
#include <stdio.h>
#include <string.h>
int main() {
char name1[] = "Mohamed Gamal";
char name2[] = "Thomas Jack";
int result = strcmp(name1, name2); // 0: same, otherwise: different
if (result == 0) {
printf("They are the same!");
}
else {
printf("They are different!");
}
return 0;
}
60. strcat() – Concatenate two strings
#include <stdio.h>
#include <string.h>
int main() {
char str1[20] = "Mohamed ";
char str2[] = "Gamal";
// Concatenate str1 and str2, the result is stored in str1.
strcat(str1, str2);
printf("Concated String: %s", str1);
return 0;
}
62. Operators Shortcuts
– C provides another set of shortcuts, in their simplest forms, they
look like this:
++i or i++ or i += 1 Add 1 to i
--i or i-- or i -= 1 Subtract 1 from i
i *= 2 Multiply i by 2
i /= 2 Divide i by 2
int i = 5;
printf("%d", i++);
int i = 5;
printf("%d", ++i);
Prefix
Infix
Postfix
Tip: be careful when using such operators since they may be ambiguous sometimes.
63. Exercises
1. Which of the following terms describes data that remains the same
throughout a program?
a) Constant
b) Variable
c) Integer
d) float
2. Which data type uses the most memory and provides the more
precision?
a) float
b) char
c) int
d) double
64. Exercises
3. Which data type does not support fractional values?
a) float
b) int
c) long float
d) double
4. Which data type requires only one byte of memory?
a) char
b) int
c) float
d) double
65. Exercises
5. Which of the following are valid variable names?
a) sam
b) SAM
c) hi_cost
d) 9%d4
e) howdoyoudothis
6. List some rules for forming variables names.
7. Explain the two different usages of division operator with int and
float data types.
66. Exercises
8. Which of the following is the correct order of evaluation for the
below expression?
z = x + y * z / 4 % 2 – 1
a) / % + - =
b) = * / % + -
c) / * % - + =
d) * % / - + =
67. Exercises
9. What value is returned by the following code fragment?
int i = 7, y = 0;
y = y + i;
if(i < 8)
printf("The value is less than eight.n");
a) 7
b) The value is less than eight.
c) 8
d) No value is returned, since the test is false.
68. Exercises
10. What would this code print?
for (int i = 0; i < 3; i = i + 1)
printf("an");
printf("bn");
printf("cn");
69. Exercises
10. How many times will the following message be printed?
int x, y;
for (x = 10, y = 0; x < 100; x = x + 10, y = y + 1)
printf("x = %dn", x);
a) 1 time
b) 9 times
c) 10 times
d) 100 times
70. Exercises
1. Which data type is used for array subscripts (i.e., indices)?
a) char only
b) int only
c) char and int only
d) int, float, and char only
2. Given the following code fragment, what is the value of arg1[5]?
int arg1[] = {1, 2, 3, 4, 5};
a) 0
b) 4
c) 5
d) Not a meaningful value.
71. Exercises
3. Given the following code fragment, which of the following is correct?
num[3] = 9;
--num[3];
a) num[3] = 9
b) num[2] = 9
c) num[3] = 8
d) num[2] = 8
72. Exercises
3. Which of the following declares a float array called worksheet[], with
30 rows and 50 columns?
a) float worksheet array[30][50];
b) float worksheet[50][30];
c) float worksheet[30][50];
d) worksheet[30][50] = float;
4. The shorthand expression for x = x + 10 is:
a) x += 10;
b) +x = 10;
c) x =+ 10;
d) x = 10+;