This is the Complete course of C Programming Language for Beginners. All Topics of C programming Language are covered in this single power point presentation.
Visit: www.cyberlabzone.com
The document provides an overview of the C programming language. It discusses that C was developed at Bell Labs in the 1970s and is a general purpose language closely associated with UNIX. It then covers C's character set, keywords, basic program structure including header files and library functions, data types, variables, constants, and provides a simple "Hello World" example program.
This PPT is for First year engineering student,It covered all about C Programming according to Rajastha Technical University Kota.
flowchart, pseudo code, Programming Languages and Language Translators, Identifiers, Constants, Variables, Basic Data Types, Operators, Expressions, type casting, Input / Output Statement, Scope Rules and Storage classes, Preprocessor and Macro Substitution.
Unions allow a variable to hold objects of different types in the same memory location. All members of a union share the same memory location, which is the size of the largest member. This means unions save memory by storing all members in one block, but the programmer must ensure the correct member is being accessed based on the data currently stored. The example program defines a union called Student containing different data types, reads values into members, and displays the members to demonstrate unions share the same memory location.
This document provides notes on programming in C from a class on the subject. It covers basics of C programming including data types, constants, operators, expressions, input/output statements, decision making statements, looping statements and more. It discusses the structure of a C program and includes comments, preprocessor directives, global variable declarations and the main function. It also covers the history and applications of C, types of programming languages, and an introduction to programming paradigms and C as a programming language.
The document discusses artificial intelligence, including its history from early computers in the 1940s to modern applications. It covers why AI is useful for tasks like quality control that humans struggle with, and how AI is applied in expert systems, natural language processing, speech recognition, computer vision, and robotics. The document also briefly mentions some advantages of AI like reduced errors and improved efficiency, as well as disadvantages such as high costs and potential unemployment.
This video by Simplilearn will explain to you Introduction to C Programming Language. Introduction to C Programming Language Tutorial For Beginners will explain to you the C language's history, C's importance, its features, real-world applications, and some of its advantages and disadvantages.
00:00 Introduction to C
1:42-History of C language
Dennis Ritchie, a computer scientist, could identify the gaps and tap out the best features from both B and BCPL languages to invent a new hybrid.
Hence, C was born in 1972 at Bell Laboratories. A remarkably simple and highly readable programming language resulted in groundbreaking advancements in the IT industry.
2:48-Importance and unraveling the powerful capabilities of C,
The widespread use of C started to take over the IT industry. Unraveling the potential of C, the designers began to discover new possibilities that led them to focus on the big picture.
3:56-C's cutting-edge features
The designers at Bell Laboratories ensured that their programming language solved the issues with B and BCPL and the ones they had foreseen.
6:35-The popular real-world applications of C
-UNIX operating system
-google file system
-Mozilla
-Graphical user interface
8:30-The advantages and disadvantages of C
10:34-The popular IT companies and their domains that employ C
· MasterCard
· IBM
· Flipkart
· Dell
· Twitter
· GitHub and twitch
11:09-First c program.
🔥 Explore our FREE courses with completion certificates: https://www.simplilearn.com/skillup-f...
✅Subscribe to our Channel to learn more about the top Technologies: https://bit.ly/2VT4WtH
⏩ Check out the C++ Programming training videos: https://www.youtube.com/playlist?list...
#IntroductiontoCProgrammingLanguage #CLanguage #CProgramming #CProgram #CProgrammingLanguage #LearnCProgramming #HowToCodeInCForBeginners #CTutorialForBeginners #LearnCProgramming #Simplilearn
Dennis Ritchie, a computer scientist, was able to identify the gaps and tap out the best features from both B and BCPL languages to invent a new hybrid.
Hence, C was born in 1972 at Bell Laboratories. A remarkably simple and highly readable programming language resulted in groundbreaking advancements in the IT industry.
✅What is C++ Programming?
C++ is an enhanced and extended version of C programming language, developed by Bjarne Stroustrup in 1979 as part of his Ph.D. project. Bjarne developed what he called ‘C with Classes’ (later renamed C++) because he felt limited by the existing programming languages that were not ideal for large scale projects. He used C to build what he wanted because C was already a general-purpose language that was efficient and fast in its operations.
✅C++ Career Prospects:
With just C++ programming expertise, you will have excellent job opportunities, salaries, and career prospects. However, for a career based on programming languages such as Java and Python (which are in more demand than C++) or for careers based on front-end, back-end, and full-stack
The document discusses research methodology and defines key concepts such as research problem, objectives of research, characteristics of research, scientific method, and hypothesis. It provides details on formulating the research problem, reviewing literature, and formulating a hypothesis. The research process involves defining the problem, reviewing concepts and theories, formulating a hypothesis, designing the research, collecting and analyzing data, and reporting findings. Variables and types of variables in formulating a hypothesis are also explained.
The document discusses inheritance in C++. It defines inheritance as deriving a class from another class, allowing code reuse and fast development. There are different types of inheritance in C++: single inheritance where a class inherits from one base class; multiple inheritance where a class inherits from more than one base class; multilevel inheritance where a derived class inherits from another derived class; hierarchical inheritance where multiple subclasses inherit from a single base class; and hybrid inheritance which combines different inheritance types. Examples of each inheritance type are provided in C++ code snippets.
Static Data Members and Member FunctionsMOHIT AGARWAL
Static data members and static member functions in C++ classes are shared by all objects of that class. Static data members are initialized to zero when the first object is created and shared across all instances, while static member functions can only access other static members and are called using the class name and scope resolution operator. The example program demonstrates a class with a static data member "count" that is incremented and accessed by multiple objects to assign increasing code values, and a static member function "showcount" that prints the shared count value.
Operator overloading allows user-defined types in C++ to behave similarly to built-in types when operators are used on them. It allows operators to have special meanings depending on the context. Some key points made in the document include:
- Operator overloading enhances the extensibility of C++ by allowing user-defined types to work with operators like addition, subtraction, etc.
- Common operators that can be overloaded include arithmetic operators, increment/decrement, input/output, function call, and subscript operators.
- To overload an operator, a member or friend function is declared with the same name as the operator being overloaded. This function performs the desired operation on the class type.
-
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;
Constructors are special class functions which performs initialization of every object. The Compiler calls the Constructor whenever an object is created. Destructor on the other hand is used to destroy the class object.
A pointer is a variable whose value is the address of another variable, i.e., direct address of the memory location. Like any variable or constant, you must declare a pointer before you can use it to store any variable address.
There are few important operations, which we will do with the help of pointers very frequently. (a) we define a pointer variable (b) assign the address of a variable to a pointer and (c) finally access the value at the address available in the pointer variable. This is done by using unary operator * that returns the value of the variable located at the address specified by its operand.
C programs are composed of six types of tokens: keywords, identifiers, constants, strings, special symbols, and operators. Keywords are reserved words that serve as building blocks for statements and cannot be used as names. Identifiers name variables, functions, and arrays and must begin with a letter. Constants represent fixed values and come in numeric, character, and string forms. Special symbols include braces, parentheses, and brackets that indicate code blocks, function calls, and arrays. Operators perform arithmetic, assignment, comparison, logic, and other operations.
Data types in C include primary (fundamental) types like integers and floating-point numbers, as well as derived and user-defined types. Primary types include integers of various sizes (char, short, int, long) that can be signed or unsigned, and floating-point types like float, double, and long double. Integer types have size and value ranges that depend on the machine, such as 8-bit char from -128 to 127. Floating-point types have prescribed sizes and precision levels. User can define their own types using typedef to create new type names, or enum to define enumeration types with named values.
The aim of this list of programming languages is to include all notable programming languages in existence, both those in current use and ... Note: This page does not list esoteric programming languages. .... Computer programming portal ...
C++ is most often used programming language. This slide will help you to gain more knowledge on C++ programming. In this slide you will learn the fundamentals of C++ programming. The slide will also help you to fetch more details on Object Oriented Programming concepts. Each of the concept under Object Oriented Programming is explained in detail and in more smoother way as it will helpful for everyone to understand.
View study notes of Function overloading .you can also visit Tutorialfocus.net to get complete description step wise of the concerned topic.Other topics and notes of C++ are also explained.
The document provides an introduction to C programming, covering topics such as what a program is, programming languages, the history of C, and the development stages of a C program. It discusses the key components of a C program including preprocessing directives, the main function, and program layout. Examples are provided to illustrate C code structure and the use of variables, keywords, operators, input/output functions, and formatting output with printf.
1) A friend function allows access to private and protected members of a class. It is declared inside the class using the keyword "friend".
2) A friend function is not a member function - it is defined outside of the class and does not have access to non-static members using the class object. However, it can access private and protected members of the class.
3) In the example, the Temperature class declares the temp function as a friend. This allows temp to directly access and modify the private celsius member, something that regular non-member functions cannot do. The friend declaration gives temp special access privileges.
Here is a potential solution to the problem in C++:
#include <iostream>
using namespace std;
int main() {
int num1, num2, num3;
cout << "Enter three numbers: ";
cin >> num1 >> num2 >> num3;
int total = num1 + num2 + num3;
float average = total / 3.0;
cout << "The numbers entered were: " << num1 << ", " << num2 << ", " << num3 << endl;
cout << "Their average is: " << average;
return 0;
}
Some key points:
- Use cin to input the 3 numbers from the
1. Arrays allow storing of multiple elements of the same data type under a single name. They can be one-dimensional, two-dimensional, or multi-dimensional. Strings are arrays of characters terminated by a null character.
2. Common array operations include declaring and initializing arrays, accessing elements using indexes, and performing element-by-element operations. Strings have specialized functions for operations like length calculation, copying, comparison and concatenation.
3. Pointers allow working with arrays by reference rather than value and are useful for passing arrays to functions. Structures group together different data types under one name and unions allow storing different data types in the same memory space.
Type casting is converting a variable from one data type to another. It is done explicitly using a cast operator like (type_name). It is best to cast to a higher data type to avoid data loss as casting to a lower type may truncate the value. There are two types of casting in C - implicit casting which happens automatically during assignment, and explicit casting which requires a cast operator. Implicit casting is done when assigning a value to a compatible type while explicit casting is needed when types are incompatible.
The document discusses strings in C programming. It defines strings as sequences of characters stored as character arrays that are terminated with a null character. It covers string literals, declaring and initializing string variables, reading and writing strings, and common string manipulation functions like strlen(), strcpy(), strcmp(), and strcat(). These functions allow operations on strings like getting the length, copying strings, comparing strings, and concatenating strings.
The document discusses various operators in C programming language. It classifies operators into arithmetic, relational, logical, bitwise, assignment and special operators. It provides examples of using different operators and explains their precedence rules and associativity.
The document discusses inheritance in C++. It defines inheritance as deriving a class from another class, allowing code reuse and fast development. There are different types of inheritance in C++: single inheritance where a class inherits from one base class; multiple inheritance where a class inherits from more than one base class; multilevel inheritance where a derived class inherits from another derived class; hierarchical inheritance where multiple subclasses inherit from a single base class; and hybrid inheritance which combines different inheritance types. Examples of each inheritance type are provided in C++ code snippets.
Static Data Members and Member FunctionsMOHIT AGARWAL
Static data members and static member functions in C++ classes are shared by all objects of that class. Static data members are initialized to zero when the first object is created and shared across all instances, while static member functions can only access other static members and are called using the class name and scope resolution operator. The example program demonstrates a class with a static data member "count" that is incremented and accessed by multiple objects to assign increasing code values, and a static member function "showcount" that prints the shared count value.
Operator overloading allows user-defined types in C++ to behave similarly to built-in types when operators are used on them. It allows operators to have special meanings depending on the context. Some key points made in the document include:
- Operator overloading enhances the extensibility of C++ by allowing user-defined types to work with operators like addition, subtraction, etc.
- Common operators that can be overloaded include arithmetic operators, increment/decrement, input/output, function call, and subscript operators.
- To overload an operator, a member or friend function is declared with the same name as the operator being overloaded. This function performs the desired operation on the class type.
-
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;
Constructors are special class functions which performs initialization of every object. The Compiler calls the Constructor whenever an object is created. Destructor on the other hand is used to destroy the class object.
A pointer is a variable whose value is the address of another variable, i.e., direct address of the memory location. Like any variable or constant, you must declare a pointer before you can use it to store any variable address.
There are few important operations, which we will do with the help of pointers very frequently. (a) we define a pointer variable (b) assign the address of a variable to a pointer and (c) finally access the value at the address available in the pointer variable. This is done by using unary operator * that returns the value of the variable located at the address specified by its operand.
C programs are composed of six types of tokens: keywords, identifiers, constants, strings, special symbols, and operators. Keywords are reserved words that serve as building blocks for statements and cannot be used as names. Identifiers name variables, functions, and arrays and must begin with a letter. Constants represent fixed values and come in numeric, character, and string forms. Special symbols include braces, parentheses, and brackets that indicate code blocks, function calls, and arrays. Operators perform arithmetic, assignment, comparison, logic, and other operations.
Data types in C include primary (fundamental) types like integers and floating-point numbers, as well as derived and user-defined types. Primary types include integers of various sizes (char, short, int, long) that can be signed or unsigned, and floating-point types like float, double, and long double. Integer types have size and value ranges that depend on the machine, such as 8-bit char from -128 to 127. Floating-point types have prescribed sizes and precision levels. User can define their own types using typedef to create new type names, or enum to define enumeration types with named values.
The aim of this list of programming languages is to include all notable programming languages in existence, both those in current use and ... Note: This page does not list esoteric programming languages. .... Computer programming portal ...
C++ is most often used programming language. This slide will help you to gain more knowledge on C++ programming. In this slide you will learn the fundamentals of C++ programming. The slide will also help you to fetch more details on Object Oriented Programming concepts. Each of the concept under Object Oriented Programming is explained in detail and in more smoother way as it will helpful for everyone to understand.
View study notes of Function overloading .you can also visit Tutorialfocus.net to get complete description step wise of the concerned topic.Other topics and notes of C++ are also explained.
The document provides an introduction to C programming, covering topics such as what a program is, programming languages, the history of C, and the development stages of a C program. It discusses the key components of a C program including preprocessing directives, the main function, and program layout. Examples are provided to illustrate C code structure and the use of variables, keywords, operators, input/output functions, and formatting output with printf.
1) A friend function allows access to private and protected members of a class. It is declared inside the class using the keyword "friend".
2) A friend function is not a member function - it is defined outside of the class and does not have access to non-static members using the class object. However, it can access private and protected members of the class.
3) In the example, the Temperature class declares the temp function as a friend. This allows temp to directly access and modify the private celsius member, something that regular non-member functions cannot do. The friend declaration gives temp special access privileges.
Here is a potential solution to the problem in C++:
#include <iostream>
using namespace std;
int main() {
int num1, num2, num3;
cout << "Enter three numbers: ";
cin >> num1 >> num2 >> num3;
int total = num1 + num2 + num3;
float average = total / 3.0;
cout << "The numbers entered were: " << num1 << ", " << num2 << ", " << num3 << endl;
cout << "Their average is: " << average;
return 0;
}
Some key points:
- Use cin to input the 3 numbers from the
1. Arrays allow storing of multiple elements of the same data type under a single name. They can be one-dimensional, two-dimensional, or multi-dimensional. Strings are arrays of characters terminated by a null character.
2. Common array operations include declaring and initializing arrays, accessing elements using indexes, and performing element-by-element operations. Strings have specialized functions for operations like length calculation, copying, comparison and concatenation.
3. Pointers allow working with arrays by reference rather than value and are useful for passing arrays to functions. Structures group together different data types under one name and unions allow storing different data types in the same memory space.
Type casting is converting a variable from one data type to another. It is done explicitly using a cast operator like (type_name). It is best to cast to a higher data type to avoid data loss as casting to a lower type may truncate the value. There are two types of casting in C - implicit casting which happens automatically during assignment, and explicit casting which requires a cast operator. Implicit casting is done when assigning a value to a compatible type while explicit casting is needed when types are incompatible.
The document discusses strings in C programming. It defines strings as sequences of characters stored as character arrays that are terminated with a null character. It covers string literals, declaring and initializing string variables, reading and writing strings, and common string manipulation functions like strlen(), strcpy(), strcmp(), and strcat(). These functions allow operations on strings like getting the length, copying strings, comparing strings, and concatenating strings.
The document discusses various operators in C programming language. It classifies operators into arithmetic, relational, logical, bitwise, assignment and special operators. It provides examples of using different operators and explains their precedence rules and associativity.
C Programming Language Tutorial for beginners - JavaTpointJavaTpoint.Com
JavaTpoint share a presentation of C Programming language for beginners and professionals. now in this slideshare you will be learned basics of c programming language, what is c programming language, history of c programming, installing turbo c, features of c programming language, datatypes of c language, operaters in c, control statement of c language, c language functions, c array, pointer in c programming, and structure and union.
This C tutorial covers every topic in C with the programming exercises. This is the most extensive tutorial on C you will get your hands on. I hope you will love the presentation. All the best. Happy learning.
Feedbacks are most welcome. Send your feedbacks to [email protected]. You can download this document in PDF format from the link, http://www.slideshare.net/dwivedi2512/learning-c-an-extensive-guide-to-learn-the-c-language
This document provides an overview of the C programming language. It discusses the origins and development of C from the B programming language. Some key features and benefits of C discussed include its low-level capabilities as a second-generation language, structured programming approach, use of functions and libraries, and support for pointers, memory allocation, recursion, and bit manipulation. The document also covers C's fundamental and derived data types, defining variables and strings, and the structure of C functions including single-level functions.
This document provides an introduction to the C programming language. It covers C program structure, variables, expressions, operators, input/output, loops, decision making statements, arrays, strings, functions, pointers, structures, unions, file input/output and dynamic memory allocation. The document uses examples and explanations to introduce basic C syntax and concepts.
SULTHAN's - C Programming Language notesSULTHAN BASHA
This book contains programming techniques, learning objectives of C language. And it will help for data structures concepts also. This is very useful to the beginners.
c++ programming Unit 3 variables,data typesAAKASH KUMAR
This document discusses variables and data types in C++. It defines variables as storage locations that can hold values of a particular data type. Variables must be declared with a data type and can optionally be initialized. The document covers integer, float, and character data types. It also provides examples of declaring, initializing, and using variables in simple programs to calculate sums and areas.
The document discusses the C programming language. It covers basic C concepts like data types, variables, operators, expressions, and functions. It provides examples of simple C code demonstrating how to declare variables, use arithmetic operators, write conditional expressions, and define functions with the main() method. The document is intended to teach beginners the fundamentals of writing C programs.
This document contains information about a student named Jitin J Pillai enrolled in the Instrumentation and Control branch of B.E. at Shantilal Shah Government Engineering College in Bhavnagar, Gujarat, India. It provides an overview of the basics of C programming including introductions to preprocessing, compiling, linking, variable types, operator precedence, type conversion, control flow, and scope rules.
Importance of loops in any programming language is immense, they allow us to reduce the number of lines in a code, making our code more readable and efficient.
The document provides information on problem solving techniques using algorithms and pseudocode. It discusses key terms, the software development method of problem solving, and basic algorithm control structures like sequence, selection and repetition. It also covers developing algorithms, using pseudocode to represent algorithms, variables, control structures like if-then-else statements and looping constructs. Examples are provided to demonstrate how to represent problems algorithmically using pseudocode and how to develop and test algorithms using a desk checking table.
The document provides information on the C programming language. It discusses that C was developed by Dennis Ritchie at Bell Labs in 1972 and is a general purpose programming language well suited for business and scientific applications. It describes the basic structure of a C program including sections for links, definitions, variables, functions, and input/output statements. It also covers various C language concepts like data types, operators, decision making statements, looping statements, functions, and more.
This document provides an overview of C programming basics including character sets, tokens, keywords, variables, data types, and control statements in C language. Some key points include:
- The C character set includes lowercase/uppercase letters, digits, special characters, whitespace, and escape sequences.
- Tokens in C include operators, special symbols, string constants, identifiers, and keywords. There are 32 reserved keywords that should be in lowercase.
- Variables are named locations in memory that hold values. They are declared with a data type and initialized by assigning a value.
- C has primary data types like int, float, char, and double. Derived types include arrays, pointers, unions, structures,
C is a procedural programming language. It was developed in the early 1970s and is still widely used. The document provides an overview of key aspects of C including data types, variables, constants, operators, control statements like if/else, and functions. It also discusses C programming concepts like low-level vs high-level languages, header files, comments, escape sequences, and more. The document serves as a useful introduction and reference for someone learning the basics of the C programming language.
1 CMPS 12M Introduction to Data Structures Lab La.docxtarifarmarie
1
CMPS 12M
Introduction to Data Structures Lab
Lab Assignment 3
The purpose of this lab assignment is to introduce the C programming language, including standard input-output
functions, command line arguments, File IO, and compilation with Makefiles.
Introduction to C
If you are not already familiar with C (or even if you are) it is recommended that you purchase a good C reference
such as C for Java Programmers: a Primer by Charlie McDowell (Lulu.com 2007). The C programming
language is, in a certain sense, the grandparent of Java (C++ being its parent). Java is known as an Object Oriented
Programming (OOP) language, which means that data structures and the procedures which operate on them are
grouped together into one language construct, namely the class. Common behavior amongst classes is specified
explicitly through the mechanism of inheritance. The C programming language on the other hand does not
directly support OOP, although it can be implemented with some effort. C is known as a procedural programming
language, which means that data structures and functions (i.e. procedures) are separate language constructs. There
are no classes, no objects, and no inheritance. New data types in C are created using the typedef and struct
constructs, which will be illustrated in future lab assignments. There is however much common syntax between
Java and C. Many control structures such as loops (while, do-while, for), and branching (if, if-else, switch) are
virtually identical in the two languages. One major difference is in the way program input and output is handled,
both to and from standard IO devices (keyboard and terminal window), and to and from files. The following is
an example of a "Hello World!" program in C.
Example
/*
* hello.c
* Prints "Hello World!" to stdout
*/
#include <stdio.h>
int main(){
printf("Hello World!\n");
return 0;
}
Comments in C are specified by bracketing them between the strings /* and */, and may span several lines. For
instance /* comment */ or
/* comment
comment */
or
/*
* comment
* comment
*/
are all acceptable. With the right compiler flags, Java/C++ style comments are also acceptable.
// comment
// comment
2
You may use any style you like, but throughout this document we will use the older C style /*comments*/.
Any line beginning with # is known as a preprocessor directive. The preprocessor performs the first phase of
compilation wherein these directives, which are literal text substitutions, are performed, making the program
ready for later stages of compilation. The line #include<stdio.h> inserts the standard library header file
stdio.h, which specifies functions for performing standard input-output operations. Notice that preprocessor
commands in C do not end in a semicolon. One can also specify constant macros using the #define preprocessor
directive as follows.
.
This document provides an overview of embedded systems programming. It discusses that embedded computers are used as part of larger systems to control physical devices. Reliability is often critical and resources are limited. Application areas include microcontrollers, real-time response requirements, and possible organization of embedded systems. C is discussed as a commonly used programming language for embedded systems due to its efficiency, ability to handle low-level activities, and ability to be compiled on different computers.
The document provides an overview of the C programming language. It begins with a brief history of C and how it evolved from the B programming language to support UNIX. It describes C as a systems programming language that is close to hardware but with higher-level constructs than assembly. The rest of the document outlines key C language concepts like data types, variables, operators, functions, and control structures. It provides examples of how to use basic programming elements like if/else statements and switch statements.
Here is the class Book with the requested attributes and member functions:
#include <iostream>
using namespace std;
class Book {
private:
string title;
string author;
string publisher;
float price;
public:
Book() {
title = "No title";
author = "No author";
publisher = "No publisher";
price = 0.0;
}
void display_data() {
cout << "Title: " << title << endl;
cout << "Author: " << author << endl;
cout << "Publisher: " << publisher << endl;
cout << "Price: " << price << endl;
}
Programming C Language Tutorial. Its an Learning document for base programming. Its an copied data from some websites and books. I tried to make more easier through this documents.
The document provides an overview of C programming basics including:
- A brief history of the C programming language and why it is commonly used in embedded systems.
- The basic structure of a C program including comments, header files, functions, and data types.
- How to declare and initialize variables in C including different data types.
- Operators and expressions in C including arithmetic, relational, logical, and bitwise operators.
- Decision making and control flow in C using if/else statements and switch cases.
- Instructions to ask questions and contact the instructor for help.
The main function serves as the starting point for program execution. It controls program flow by calling other functions. A program typically ends at the end of main. All C programs must have a main function which takes no arguments and returns an int. Main contains the core logic that runs the program. Preprocessor directives like #include add functionality by including header files. Macros defined with #define are text replacements that occur before compilation. Conditional compilation with #ifdef/#ifndef includes or excludes blocks of code based on symbol definitions.
C is mother language of all programming language.
It is a system programming language. It is a procedure-oriented programming language. It is also called mid-level programming language.
C evolved from a language called B, written by Ken Thompson at Bell Labs in 1970. Ken used B to write one of the first implementations of UNIX. B in turn was a descendant of the language BCPL (developed at Cambridge (UK) in 1967), with most of its instructions removed.
So many instructions were removed in going from BCPL to B, that Dennis Ritchie of Bell Labs put some back in (in 1972), and called the language C.
The famous book The C Programming Language was written by Kernighan and Ritchie in 1978, and was the definitive reference book on C for almost a decade.
The original C was still too limiting, and not standardized, and so in 1983, an ANSI committee was established to formalize the language definition.
It has taken until now (ten years later) for the ANSI ( American National Standard Institute) standard to become well accepted and almost universally supported by compilers.
IIM.Com-FIT-Unit2(14.9.2021 TO 30.9.2021).pptxrajkumar490591
This document discusses various topics related to C programming language including:
- The structure of a typical C program which includes header files inclusion, main method declaration, variable declaration, function body, and return statement.
- Different types of variables in C like local, global, static, automatic, and external variables. Local variables are declared within a function while global variables are declared outside. Static variables retain their value between function calls.
- Key concepts like data types, valid variable names, compilers, linkers, and how a C program is executed after compilation.
C Introduction and bascis of high level programmingvipulkondekar
The document provides an introduction to the C programming language. It discusses C's history as a language developed in the 1970s alongside UNIX to enable low-level access to hardware for efficiency. C takes a middle path between low-level assembly and high-level languages like Java, providing direct memory access through pointers as well as functions and basic type checking. The document outlines some dangers of C like lack of encapsulation and weak type checking. It also covers key aspects of programming in C like separate compilation of files, use of comments and preprocessor directives, function prototypes, and the main function.
Introduction to cpp language and all the required information relating to itPushkarNiroula1
C++ is an object-oriented programming language developed in the early 1980s as an extension of C with additional features like classes, inheritance, and function overloading. A simple C++ program prints a string to the screen using the cout output stream and iostream header. C++ programs typically contain functions, comments, and use operators like << for output and >> for input.
The document provides an introduction to the C programming language. It discusses that C was developed in the 1970s to write operating system kernels like UNIX where efficiency is crucial. C takes a middle path between low-level assembly languages and high-level languages like Java by providing direct memory access through pointers but also code structure through functions. While this gives C performance benefits, it also makes C prone to errors if programmers are not disciplined as C does not prevent programs from doing dangerous actions. The document also covers key aspects of the C language like separate compilation, the preprocessor, function prototypes, and the main function.
The document provides an overview of the C programming language, including its history, characteristics, environment, structure, data types, variables, decision making, looping, libraries, and uses. It describes how C was developed at Bell Labs in the early 1970s and later standardized. The summary highlights C's small fixed set of keywords, static typing, use of headers and functions, and popularity for systems programming and performance-critical applications due to its efficiency and ability to access hardware.
This document is the table of contents for a book on C programming. It lists 88 example C programs that are intended to teach C concepts in an evolutionary manner. The programs cover basics like input/output, variables, data types, operators, loops, conditional statements, arrays, functions, pointers, structures, file I/O and more. The programs are presented from simplest to more complex to help programmers learn each new element of the C language.
The document provides an introduction to the C programming language. It discusses C's history as a systems programming language developed alongside UNIX in the 1970s. It describes C's characteristics as a middle-level language that provides low-level access to hardware while including some high-level features like functions. It also notes potential dangers in C like a lack of type safety and memory management. The document explains the separate compilation process in C and provides examples of common C code structures like main functions and the use of preprocessor directives and library functions.
This document discusses the basic structure of C++ programs. It covers preprocessor directives, header files, the main function, and return statements. It provides examples of a simple Hello World program structure and explains each part. It also lists common C++ header files and their purposes.
Learn c language Important topics ( Easy & Logical, & smart way of learning)Rohit Singh
Learn C language with an easy way including all important topics in C.
Learn c language Important topics ( Easy & Logical, & smart way of learning)
preprocessor Directive, Search Strategy, Header file, return 0 in C, return, main function, flow of execution, explicit return, function, return type and non return type function. Run- time Environment, type specifier, void keyword, 32 keyword in C, openning curly brace and closing curly brace, system library, single argument, String literal is an unnamed array with element of type char.
Deceptive Marketing (also known as “dark Marketing”) are tricks used in websites and apps that
make you do things that you didn’t mean to, like buying or signing up for something. The purpose of
this site is to spread awareness and to shame companies that use these patterns.
How does Deceptive Marketing work?
When you use websites and apps, you don’t read every word on every page—you skim read and
make assumptions. If a company wants to trick you into doing something, they can take advantage
of this by making a page look like it is saying one thing when it is in fact saying another. You can
defend yourself by learning about deceptive marketing.
Types of Deceptive Marketing
Trick questions
While filling in a form you respond to a question that tricks you into giving an answer you didn’t
intend. When glanced upon quickly the question appears to ask one thing, but when read carefully it
asks another thing entirely.
This is very common when registering with a service. Typically a series of checkboxes is shown, and
the meaning checkboxes is alternated so that ticking the first one means “opt out” and the second
means “opt in”. Confusing language is often also used. Currys PC World provides a good example of
this on their checkout collection
BRAIN Computer Interface (BCI) is a technique that
provides direct interface between the human brain and the
computer. BCI techniques are broadly classified into
invasive and non-invasive techniques. Non-invasive
techniques are becoming more popular and more research is
being done on this topic. There are various non-invasive BCI
techniques such as EEG, Electro-Oculography. EEG technique
deploys an electrode cap that is placed on the user’s scalp for
the acquisition of the EEG signal, which relates the scalp
potential differences to various complex actions. Classification
of the EEG signal has been made into several bands like alpha,
beta, delta, theta and mu suppression, each corresponding to
various states of being like relaxing, ranging over 8-14 Hz;
concentrating, ranging over 13-30 Hz; deep sleep, from 0-4
Hz; meditating from 4-8 Hz; moving your hands or legs or just
by imagining these motor actions respectively. As it is being
non-invasive in nature, it has an advantage over traditional
BMI, not being hazardous to health. With the advent of
technology the EEG acquisition devices are made more
compact, handy and wireless. Using the above mentioned
technique, a simple thought controlled wheelchair system has
been proposed in this paper. A section that briefly explains the
various blocks included in the system is also added in this
paper
Mechanism of fullerene synthesis in the ARC REACTOR (Vivek Chan 2013)Vivek Singh Chandel
A mathematical model for the arc reactor which takes into account a. cooling and mixing of carbon vapour with a buffer
gas, b . non-isothermal kinetics of carbon clusters growth and c. formation of soot particles and heterogeneous reactions at
their surface has been developed. The model gives quantitative coincidence of experimental data with calculated values both
for the fullerene yield and ratio C70rC60 in the products of the arc synthesis run under widely varied conditions. Numerical
analysis of the model has shown that experimental data obtained for the arc synthesis strictly constrain the choice of the
mechanism of fullerene formation.
[Vivek Chan 2013]
EEG Acquisition Device to Control Wheelchair Using ThoughtsVivek Singh Chandel
With the advancements in technology and health-care facilities, the number of senior citizens has increased and thus the number of elderly who find it difficult to walk. Hence there is a need for designing a wheelchair that is user friendly and involves fewer complexities. In this context, we propose a thought controlled wheelchair, which uses the captured signals from the brain and process it to control the wheelchair. This wheelchair can also be used by the physically challenged who depend on others for locomotion. Rehabilitation centers at hospitals can also make use of this wheelchair. In this paper, we explain the design and analysis of the thought-controlled wheelchair. In addition, we present some of the experiments that were carried out and the corresponding results in this paper.
http://www.vivek-chan.in
Full Shri Ramcharitmanas in Hindi Complete With Meaning (Ramayana)Vivek Singh Chandel
Ramcharitmanas (Devanāgarī: श्रीरामचरितमानस, IAST: ŚrīRāmacaritamānasa), also spelt as Ramacharitamanasa, is an epic poem in Awadhi dialect of Hindi, composed by the 16th-century Indian bhakti poet Goswami Tulsidas (c.1532–1623). Ramcharitmanas literally means "Lake of the deeds of Rama". Ramcharitmanas is considered as one of the greatest works of Hindi literature. The work has been acclaimed as "the living sum of Indian culture", "the tallest tree in the magic garden of medieval Indian poetry", "the greatest book of all devotional literature" and "the best and most trustworthy guide to the popular living faith of the Indian people".
The core of the work is considered by some to be a poetic retelling of the events of the Sanskrit epic Ramayana, centered on the narrative of Rama, the scion of the family tree of Raghu of the Sun Dynasty and the crown prince of Ayodhya who is also considered in Hindu tradition as one of the Avataras of Vishnu. However, Tulsidas never alludes to Ramcharitmanas as being a retelling of Valmiki Ramayana. He calls the epic Ramcharitmanas as the story of Rama was stored in the mind (Mānasa) of Shiva before he narrated the same to His consort Parvati. Tulsidas claims to have received the story through his guru, Narharidas. Tulsidas was unconscious (Acheta, Devanāgarī: अचेत) and the story was stored in his mind (Mānasa) for long before he wrote it down as Ramcharitmanas. The epic poem is, therefore, also referred to as Tulsikrit Ramayana (literally, The Ramayana composed by Tulsidas).
This document discusses various .NET system types and interfaces. It explains that base system types provide predefined data types, generics allow creation of type-safe collections, and nullable types allow value types to be assigned null values. It also covers exception handling using exception classes, customizing code with attributes, and implementing common interfaces like IComparable, ICloneable, and IDisposable.
CyberLab Training Division :
The .NET Framework is Microsoft's Managed Code programming model for building applications on Windows clients, servers, and mobile or embedded devices. Microsoft's .NET Framework is a software technology that is available with several Microsoft Windows operating systems. In the following sections describes , the basics of Microsoft .Net Frame work Technology and its related programming models.
What is Microsoft .Net Framework
what are the functions of microsoft .net framework?
Common Language Runtime in .Net Framework
How to Common Language Runtime
What is .Net Framework Class Library
What is Common Language Specification
What is Common Type System
What is Microsoft Intermediate Language
What is Portable Executable (PE) File Format
What is Microsoft Just In Time Compiler
How to Managed Code - Microsoft .Net Framework
What is .Net Framework Metadata
what is .Net Framework Assembly
What is Assembly Manifest
What is Global Assembly Cache
What is a .Net Satellite Assembly?
What are the contents of an Assembly?
How to Private Assembly and Shared Assembly
What is Microsoft .Net Strong Name
What is .Net Namespaces
What is Application Domain
What is Code Access Security
What is Garbage Collection
.Net Threads
For More Details.
Visit: http://www.cyberlabzone.com
CyberLab Training Division :
The .NET Framework is Microsoft's Managed Code programming model for building applications on Windows clients, servers, and mobile or embedded devices. Microsoft's .NET Framework is a software technology that is available with several Microsoft Windows operating systems. In the following sections describes , the basics of Microsoft .Net Frame work Technology and its related programming models.
What is Microsoft .Net Framework
what are the functions of microsoft .net framework?
Common Language Runtime in .Net Framework
How to Common Language Runtime
What is .Net Framework Class Library
What is Common Language Specification
What is Common Type System
What is Microsoft Intermediate Language
What is Portable Executable (PE) File Format
What is Microsoft Just In Time Compiler
How to Managed Code - Microsoft .Net Framework
What is .Net Framework Metadata
what is .Net Framework Assembly
What is Assembly Manifest
What is Global Assembly Cache
What is a .Net Satellite Assembly?
What are the contents of an Assembly?
How to Private Assembly and Shared Assembly
What is Microsoft .Net Strong Name
What is .Net Namespaces
What is Application Domain
What is Code Access Security
What is Garbage Collection
.Net Threads
For More Details.
Visit: http://www.cyberlabzone.com
CyberLab Training Division :
Intel VTune Amplifier is a commercial application for software performance analysis for 32 and 64-bit x86 based machines, and has both GUI and command line interfaces. It is available for both Linux and Microsoft Windows operating systems. Although basic features work on both Intel and AMD hardware, advanced hardware-based sampling requires an Intel-manufactured CPU.
Whether you are tuning for the first time or doing advanced performance optimization, Intel® VTune Amplifier provides a rich set of performance insight into CPU & GPU performance, threading performance & scalability, bandwidth, caching and much more. Analysis is faster and easier because VTune Amplifier understands common threading models and presents information at a higher level that is easier to interpret. Use its powerful analysis to sort, filter and visualize results on the timeline and on your source.
It is available as part of Intel Parallel Studio or as a stand-alone product.
VTune Amplifier assists in various kinds of code profiling including stack sampling, thread profiling and hardware event sampling. The profiler result consists of details such as time spent in each sub routine which can be drilled down to the instruction level. The time taken by the instructions are indicative of any stalls in the pipeline during instruction execution. The tool can be also used to analyze thread performance. The new GUI can filter data based on a selection in the timeline.
For More Details.
Visit: http://www.cyberlabzone.com
CyberLab Training Division :
Intel VTune Amplifier is a commercial application for software performance analysis for 32 and 64-bit x86 based machines, and has both GUI and command line interfaces. It is available for both Linux and Microsoft Windows operating systems. Although basic features work on both Intel and AMD hardware, advanced hardware-based sampling requires an Intel-manufactured CPU.
Whether you are tuning for the first time or doing advanced performance optimization, Intel® VTune Amplifier provides a rich set of performance insight into CPU & GPU performance, threading performance & scalability, bandwidth, caching and much more. Analysis is faster and easier because VTune Amplifier understands common threading models and presents information at a higher level that is easier to interpret. Use its powerful analysis to sort, filter and visualize results on the timeline and on your source.
It is available as part of Intel Parallel Studio or as a stand-alone product.
VTune Amplifier assists in various kinds of code profiling including stack sampling, thread profiling and hardware event sampling. The profiler result consists of details such as time spent in each sub routine which can be drilled down to the instruction level. The time taken by the instructions are indicative of any stalls in the pipeline during instruction execution. The tool can be also used to analyze thread performance. The new GUI can filter data based on a selection in the timeline.
For More Details.
Visit: http://www.cyberlabzone.com
This presentation discusses code optimization and performance tuning. It covers identifying time and space complexity of algorithms, examining programming constructs like loops and functions, and using performance libraries. Some key points include defining time complexity as the time taken by algorithm steps, optimizing loops by techniques like unrolling and reducing work inside loops, and the advantages of using pre-existing performance libraries like reducing errors and development time.
CyberLab Training Division :
Intel VTune Amplifier is a commercial application for software performance analysis for 32 and 64-bit x86 based machines, and has both GUI and command line interfaces. It is available for both Linux and Microsoft Windows operating systems. Although basic features work on both Intel and AMD hardware, advanced hardware-based sampling requires an Intel-manufactured CPU.
Whether you are tuning for the first time or doing advanced performance optimization, Intel® VTune Amplifier provides a rich set of performance insight into CPU & GPU performance, threading performance & scalability, bandwidth, caching and much more. Analysis is faster and easier because VTune Amplifier understands common threading models and presents information at a higher level that is easier to interpret. Use its powerful analysis to sort, filter and visualize results on the timeline and on your source.
It is available as part of Intel Parallel Studio or as a stand-alone product.
VTune Amplifier assists in various kinds of code profiling including stack sampling, thread profiling and hardware event sampling. The profiler result consists of details such as time spent in each sub routine which can be drilled down to the instruction level. The time taken by the instructions are indicative of any stalls in the pipeline during instruction execution. The tool can be also used to analyze thread performance. The new GUI can filter data based on a selection in the timeline.
For More Details.
Visit: http://www.cyberlabzone.com
CyberLab Training Division :
Intel VTune Amplifier is a commercial application for software performance analysis for 32 and 64-bit x86 based machines, and has both GUI and command line interfaces. It is available for both Linux and Microsoft Windows operating systems. Although basic features work on both Intel and AMD hardware, advanced hardware-based sampling requires an Intel-manufactured CPU.
Whether you are tuning for the first time or doing advanced performance optimization, Intel® VTune Amplifier provides a rich set of performance insight into CPU & GPU performance, threading performance & scalability, bandwidth, caching and much more. Analysis is faster and easier because VTune Amplifier understands common threading models and presents information at a higher level that is easier to interpret. Use its powerful analysis to sort, filter and visualize results on the timeline and on your source.
It is available as part of Intel Parallel Studio or as a stand-alone product.
VTune Amplifier assists in various kinds of code profiling including stack sampling, thread profiling and hardware event sampling. The profiler result consists of details such as time spent in each sub routine which can be drilled down to the instruction level. The time taken by the instructions are indicative of any stalls in the pipeline during instruction execution. The tool can be also used to analyze thread performance. The new GUI can filter data based on a selection in the timeline.
For More Details.
Visit: http://www.cyberlabzone.com
CyberLab Training Division :
Intel VTune Amplifier is a commercial application for software performance analysis for 32 and 64-bit x86 based machines, and has both GUI and command line interfaces. It is available for both Linux and Microsoft Windows operating systems. Although basic features work on both Intel and AMD hardware, advanced hardware-based sampling requires an Intel-manufactured CPU.
Whether you are tuning for the first time or doing advanced performance optimization, Intel® VTune Amplifier provides a rich set of performance insight into CPU & GPU performance, threading performance & scalability, bandwidth, caching and much more. Analysis is faster and easier because VTune Amplifier understands common threading models and presents information at a higher level that is easier to interpret. Use its powerful analysis to sort, filter and visualize results on the timeline and on your source.
It is available as part of Intel Parallel Studio or as a stand-alone product.
VTune Amplifier assists in various kinds of code profiling including stack sampling, thread profiling and hardware event sampling. The profiler result consists of details such as time spent in each sub routine which can be drilled down to the instruction level. The time taken by the instructions are indicative of any stalls in the pipeline during instruction execution. The tool can be also used to analyze thread performance. The new GUI can filter data based on a selection in the timeline.
For More Details.
Visit: http://www.cyberlabzone.com
CyberLab Training Division :
ASP.NET is a web application framework developed and marketed by Microsoft to allow programmers to build dynamic web sites. It allows you to use a full featured programming language such as C# or VB.NET to build web applications easily.
This tutorial covers all the basic elements of ASP.NET that a beginner would require to get started.
Audience
This tutorial has been prepared for the beginners to help them understand basic ASP.NET programming. After completing this tutorial you will find yourself at a moderate level of expertise in ASP.NET programming from where you can take yourself to next levels.
Prerequisites
Before proceeding with this tutorial, you should have a basic understanding of .NET programming language. As we are going to develop web-based applications using ASP.NET web application framework, it will be good if you have an understanding of other web technologies such as HTML, CSS, AJAX. etc
ASP.NET supports three different development models:
Web Pages, MVC (Model View Controller), and Web Forms.
For More Details.
Visit: http://www.cyberlabzone.com
CyberLab Training Division :
ASP.NET is a web application framework developed and marketed by Microsoft to allow programmers to build dynamic web sites. It allows you to use a full featured programming language such as C# or VB.NET to build web applications easily.
This tutorial covers all the basic elements of ASP.NET that a beginner would require to get started.
Audience
This tutorial has been prepared for the beginners to help them understand basic ASP.NET programming. After completing this tutorial you will find yourself at a moderate level of expertise in ASP.NET programming from where you can take yourself to next levels.
Prerequisites
Before proceeding with this tutorial, you should have a basic understanding of .NET programming language. As we are going to develop web-based applications using ASP.NET web application framework, it will be good if you have an understanding of other web technologies such as HTML, CSS, AJAX. etc
ASP.NET supports three different development models:
Web Pages, MVC (Model View Controller), and Web Forms.
For More Details.
Visit: http://www.cyberlabzone.com
CyberLab Training Division :
ASP.NET is a web application framework developed and marketed by Microsoft to allow programmers to build dynamic web sites. It allows you to use a full featured programming language such as C# or VB.NET to build web applications easily.
This tutorial covers all the basic elements of ASP.NET that a beginner would require to get started.
Audience
This tutorial has been prepared for the beginners to help them understand basic ASP.NET programming. After completing this tutorial you will find yourself at a moderate level of expertise in ASP.NET programming from where you can take yourself to next levels.
Prerequisites
Before proceeding with this tutorial, you should have a basic understanding of .NET programming language. As we are going to develop web-based applications using ASP.NET web application framework, it will be good if you have an understanding of other web technologies such as HTML, CSS, AJAX. etc
ASP.NET supports three different development models:
Web Pages, MVC (Model View Controller), and Web Forms.
For More Details.
Visit: http://www.cyberlabzone.com
CyberLab Training Division :
ASP.NET is a web application framework developed and marketed by Microsoft to allow programmers to build dynamic web sites. It allows you to use a full featured programming language such as C# or VB.NET to build web applications easily.
This tutorial covers all the basic elements of ASP.NET that a beginner would require to get started.
Audience
This tutorial has been prepared for the beginners to help them understand basic ASP.NET programming. After completing this tutorial you will find yourself at a moderate level of expertise in ASP.NET programming from where you can take yourself to next levels.
Prerequisites
Before proceeding with this tutorial, you should have a basic understanding of .NET programming language. As we are going to develop web-based applications using ASP.NET web application framework, it will be good if you have an understanding of other web technologies such as HTML, CSS, AJAX. etc
ASP.NET supports three different development models:
Web Pages, MVC (Model View Controller), and Web Forms.
For More Details.
Visit: http://www.cyberlabzone.com
Adam Grant: Transforming Work Culture Through Organizational PsychologyPrachi Shah
This presentation explores the groundbreaking work of Adam Grant, renowned organizational psychologist and bestselling author. It highlights his key theories on giving, motivation, leadership, and workplace dynamics that have revolutionized how organizations think about productivity, collaboration, and employee well-being. Ideal for students, HR professionals, and leadership enthusiasts, this deck includes insights from his major works like Give and Take, Originals, and Think Again, along with interactive elements for enhanced engagement.
How to Manage Allocations in Odoo 18 Time OffCeline George
Allocations in Odoo 18 Time Off allow you to assign a specific amount of time off (leave) to an employee. These allocations can be used to track and manage leave entitlements for employees, such as vacation days, sick leave, etc.
Search Engine Optimization (SEO) for Website SuccessMuneeb Rana
Unlock the essentials of Search Engine Optimization (SEO) with this concise, visually driven PowerPoint. Inside you’ll find:
✅ Clear definitions and core concepts of SEO
✅ A breakdown of On‑Page, Off‑Page, and Technical SEO
✅ Actionable best‑practice checklists for keyword research, content optimization, and link building
✅ A quick‑start toolkit featuring Google Analytics, Search Console, Ahrefs, SEMrush, and Moz
✅ Real‑world case study demonstrating a 70 % organic‑traffic lift
✅ Common challenges, algorithm updates, and tips for long‑term success
Whether you’re a digital‑marketing student, small‑business owner, or PR professional, this deck will help you boost visibility, build credibility, and drive sustainable traffic. Download, share, and start optimizing today!
Smart Borrowing: Everything You Need to Know About Short Term Loans in Indiafincrifcontent
Short term loans in India are becoming a go-to financial solution for individuals needing quick access to funds without long-term commitments. With fast approval, minimal documentation, and flexible tenures, these loans are ideal for handling emergencies, unexpected bills, or short-term goals. Understanding key aspects like short term loan features, eligibility, required documentation, and how to apply for a short term loan can help borrowers make informed decisions. Whether you're salaried or self-employed, short term loans offer convenience and speed. This guide walks you through the essentials so you can secure the right loan at the right time.
"Hymenoptera: A Diverse and Fascinating Order".pptxArshad Shaikh
Hymenoptera is a diverse order of insects that includes bees, wasps, ants, and sawflies. Characterized by their narrow waists and often social behavior, Hymenoptera play crucial roles in ecosystems as pollinators, predators, and decomposers, with many species exhibiting complex social structures and communication systems.
*Order Hemiptera:*
Hemiptera, commonly known as true bugs, is a large and diverse order of insects that includes cicadas, aphids, leafhoppers, and shield bugs. Characterized by their piercing-sucking mouthparts, Hemiptera feed on plant sap, other insects, or small animals. Many species are significant pests, while others are beneficial predators.
*Order Neuroptera:*
Neuroptera, also known as net-winged insects, is an order of insects that includes lacewings, antlions, and owlflies. Characterized by their delicate, net-like wing venation and large, often prominent eyes, Neuroptera are predators that feed on other insects, playing an important role in biological control. Many species have aquatic larvae, adding to their ecological diversity.
HOW YOU DOIN'?
Cool, cool, cool...
Because that's what she said after THE QUIZ CLUB OF PSGCAS' TV SHOW quiz.
Grab your popcorn and be seated.
QM: THARUN S A
BCom Accounting and Finance (2023-26)
THE QUIZ CLUB OF PSGCAS.
This presentation has been made keeping in mind the students of undergraduate and postgraduate level. To keep the facts in a natural form and to display the material in more detail, the help of various books, websites and online medium has been taken. Whatever medium the material or facts have been taken from, an attempt has been made by the presenter to give their reference at the end.
In the seventh century, the rule of Sindh state was in the hands of Rai dynasty. We know the names of five kings of this dynasty- Rai Divji, Rai Singhras, Rai Sahasi, Rai Sihras II and Rai Sahasi II. During the time of Rai Sihras II, Nimruz of Persia attacked Sindh and killed him. After the return of the Persians, Rai Sahasi II became the king. After killing him, one of his Brahmin ministers named Chach took over the throne. He married the widow of Rai Sahasi and became the ruler of entire Sindh by suppressing the rebellions of the governors.
RE-LIVE THE EUPHORIA!!!!
The Quiz club of PSGCAS brings to you a fun-filled breezy general quiz set from numismatics to sports to pop culture.
Re-live the Euphoria!!!
QM: Eiraiezhil R K,
BA Economics (2022-25),
The Quiz club of PSGCAS
Diptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptxArshad Shaikh
Diptera, commonly known as flies, is a large and diverse order of insects that includes mosquitoes, midges, gnats, and horseflies. Characterized by a single pair of wings (hindwings are modified into balancing organs called halteres), Diptera are found in almost every environment and play important roles in ecosystems as pollinators, decomposers, and food sources. Some species, however, are significant pests and disease vectors, transmitting diseases like malaria, dengue, and Zika virus.
Coleoptera, commonly known as beetles, is the largest order of insects, comprising approximately 400,000 described species. Beetles can be found in almost every habitat on Earth, exhibiting a wide range of morphological, behavioral, and ecological diversity. They have a hardened exoskeleton, with the forewings modified into elytra that protect the hind wings. Beetles play important roles in ecosystems as decomposers, pollinators, and food sources for other animals, while some species are considered pests in agriculture and forestry.
How to Create a Stage or a Pipeline in Odoo 18 CRMCeline George
In Odoo, the CRM (Customer Relationship Management) module’s pipeline is a visual representation of a company's sales process that helps sales teams track and manage their interactions with potential customers.
Stewart Butler - OECD - How to design and deliver higher technical education ...EduSkills OECD
Stewart Butler, Labour Market Economist at the OECD presents at the webinar 'How to design and deliver higher technical education to develop in-demand skills' on 3 June 2025. You can check out the webinar recording via our website - https://oecdedutoday.com/webinars/ .
You can check out the Higher Technical Education in England report via this link 👉 - https://www.oecd.org/en/publications/higher-technical-education-in-england-united-kingdom_7c00dff7-en.html
You can check out the pathways to professions report here 👉 https://www.oecd.org/en/publications/pathways-to-professions_a81152f4-en.html
Forestry Model Exit Exam_2025_Wollega University, Gimbi Campus.pdfChalaKelbessa
This is Forestry Exit Exam Model for 2025 from Department of Forestry at Wollega University, Gimbi Campus.
The exam contains forestry courses such as Dendrology, Forest Seed and Nursery Establishment, Plantation Establishment and Management, Silviculture, Forest Mensuration, Forest Biometry, Agroforestry, Biodiversity Conservation, Forest Business, Forest Fore, Forest Protection, Forest Management, Wood Processing and others that are related to Forestry.
2. www.cyberlabzone.com
Topics for C Language
1.Introduction to C language
2.Programming Languages
3.Data Types
4.Basic Input/Output (I/O)
5.Control Constructs
6.Array
7.Fuctions
8.Program Design Example
9.Pointers
10.Structures & Unions
11.File Operation in C
12.The C Preprocessor
13.Computational Complexity
3. www.cyberlabzone.com
Introduction to C languages
C is a traditional, Procedural language,i.e. one that requires the programmer to
provide step-by-step instructions for the processor (i.e., the main logic unit of a
computer).
The great success of C is due to its simplicity, efficiency,
flexibility and small memory requirements. It is also due to the portability of
programs that are written in it, i.e., the ability to be easily adapted to new
platforms (i.e., operating systems and processors).
C's great portability is in very large part a result of the fact that
compilers and libraries are available for numerous platforms. A compiler is a
specialized computer program that converts source code (i.e., the original,
human-readable form of a program typed into a computer by a programmer in a
programming language) into another language, usually machine language (also
called object code or machine code) so that it can be directly understood by
processors. A library is a collection of routines (also called subprograms,
procedures or functions) that perform operations which are commonly required
by programs.
4. www.cyberlabzone.com
Programming Languages
Programming Languages classified as ”Low Level/High Level”
1.Low Level
•Machine Language
(binary-based code; machine dependent)
• Assembly Language
(mnemonic form of machine language)
2.High Level
Closer to natural languages.
Generally, machine independent
Usually, several machine instructions are combined into one high-
level instruction.
Examples:
FORTRAN, COBOL,BASIC, Java, Pascal, Ada, PL/I, Lisp, C
GPSS,C++, Matlab
5. www.cyberlabzone.com
Processing a High-level Language
Program
Programs written in high-level languages must be converted to
machine language.
Two approaches:
(1) Compilation used with C, C++, Fortran,...
(2) Interpretation
Used with Matlab, Visual Basic,...
6. www.cyberlabzone.com
STEP 1) Use Dos Prompt to create a “Directory”. In this Directory
We write and save all Programme name source files with a suffix “.c”.
STEP 2)In Dos Prompt to compile the desired Programme we use “Ctrl
+F9” to get a desired result While programme is on the monitor .
STEP 3) Check the error if any caught by compiler, remove
that error and go back to step 2,repeat whole process again.
STEP 4) Run the program by using “Ctrl+F9” and for
OUTPUT we use “Alt+F5”
in the Dos prompt.
Compilation (In Window Environment)
7. www.cyberlabzone.com
C Program Examples
1. Requirements Specification (Problem Definition)
Write a simple C program to request the users’ SSN and print the message “Hello
(SSN)!” (where SSN is the value the user supplied) to the screen of the computer
monitor.
2. Analysis---Refine, Generalize, Decompose the problem definition
(i.e., identify sub problems, I/O, etc.)
Input = SSN
Output= A prompt for the SSN then
“Hello (SSN)!”
3. Design---Develop Algorithm
Pseudo-code Algorithm
print “Enter SSN (no dashes)”
read SSN
print “Hello (SSN) !”
4. Implementation --- Write the "Program" (Code)
8. www.cyberlabzone.com
C Examples
/* C Program to greet the user */
#include <stdio.h> /* makes the function printf “known” */
/* to the C compiler */
void main(void)
{
int ssn; /* variable ssn declared */
printf(”Please enter your SSN (no dashes):”);
scanf(”%d”,&ssn); /* read the SSN */
printf(”Hello %d !n”,ssn); /* print the message */
}
9. www.cyberlabzone.com
Main Function
#include ... /* preprocessor directive */
.
.
.
void main(void) /*function header*/
{ .
. /* function body */
.
}
In the following set of slides we will define the
component parts of the main function.
10. www.cyberlabzone.com
Preprocessor Directives
#include ... /* preprocessor directive */
.
.
.
void main(void)
{ .
.
.
}
Statements beginning with the symbol # are called preprocessor
directives. The #include directives allow the C program to access
libraries of functions that are not available directly in C. These
libraries are referred to as header files:
stdio.h standard input-output functions
math.h math functions
stdlib.h a “standard” library of functions
11. www.cyberlabzone.com
Main Function Header
#include ...
.
.
.
void main(void) /*function header*/
{ .
.
.
}
The “initial” input is any value(s) passed at initial execution, e.g.
>a.out 1.0 3.5
Typing the above at the Unix prompt attempts to pass the values 1.0
and 3.5 to main. At this point we will not do this. The header for the
programs in some C programs is of the form:
int main(void)
and there is a corresponding statement in the function body:
return (0);
main has no
“initial” input
values. (see
below)
main function
returns no value
12. www.cyberlabzone.com
Main Function (body)
#include ...
.
.
.
void main(void)
{ .
. /* function body */
.
}
• The body of a function is all the declarations and executable
statements between the braces (in the block). The declarations
must precede the executable statements in this block.
• When you run a program, the first statement executed is the first
(from the top of the file) executable statement in main. The
execution of statements proceeds until the terminating “}” right
brace is encountered or a return statement is executed.
a “block” in C is
defined by a set
of curly braces.
15. www.cyberlabzone.com
Variable Names
Variable Names - reference to memory locations storing data values.
A variable name is one example of an identifier in C.
An identifier can use a combination of letters, numerical digits, and
the underscore ( _ ) that starts with a letter. Only the first 31
characters of an identifier are recognized by most compilers.
Identifiers cannot be the same as a reserved word or keyword, such as
void, float, or return. Examples: x sum force2
rate_Of_Change
Examples of invalid variable names (why?):
2force rate-of-change x.5 return
C case-sensitive, so that the following three names all represent
different variables (i.e., different storage locations):
time Time TIME
16. www.cyberlabzone.com
#include <stdio.h>
void main(void)
{
int ssn;
printf(”Please enter your SSN (no dashes):”);
scanf(”%d”,&ssn);
printf(”Hello %d !n”,ssn);
}
The printf and scanf functions appear in
‘expression’ statements.
1st executable
statement
3rd executable
statement
2nd executable
statement
Executable Statements
17. www.cyberlabzone.com
Executable Statements
Statements are grouped by their type:
expression statement
do-while and while statements
for statement
if and if-else statements
return statement
switch statement
assignment statement
Every executable statement in C must be followed
by a “ ; “ semicolon.
18. www.cyberlabzone.com
Assignment Statement
•Interpretation: compute the value on the
right-hand-side of the = and put this value in memory at
location named (or tagged) by the name variable .
• an expression can be a constant, a variable or
operators with operands.
variable = expression;
19. www.cyberlabzone.com
Constants
Literal Constants(examples)
Numeric: 3 6.248 -7.25 1.5e4 (=15000)
Single Character: 'A' 'a' '9' '+' ' '
Character String: “Enter a positive number: ”
Symbolic Constants(example)
#define PI 3.14159265 /* preprocessor directive */
By default, constants declared in #define are of type
double.
Standard practice is to use all upper-case letters for the
constant name, to avoid confusion with a variable name.
A “constant” means you cannot change the value, e.g.
PI = 3.0;
will generate a compiler error from gcc.
20. www.cyberlabzone.com
Arithmetic Operators
- for integer arithmetic, the / operator yields an integer result, and
% gives the remainder after dividing two integers. E.g.,
5 / 3 1 5 / 6 0
5 % 3 2 5 % 6 5
(Note: division by 0 creates an "overflow" run-time error.)
- use arithmetic operators, with parentheses for grouping; e.g., (a
- b) / (2 * c)
e.g, without parentheses, the example above would evaluate b/2
first, then do the multiplication, then the subtraction.
+, - , * , / , % (modulus) (no ^ operator as in Matlab)
21. www.cyberlabzone.com
Rules of Precedence
( ) Higher
*, /, % (left to right for tie)
+, - (left to right for tie) Lower
Examples,
: x = 3 + 2 * 3; /* x now has the value 9 */
y = 3 * 2 % 3; /* y now has the value 0 */
- Precedence Order for Arithmetic Operators:
22. www.cyberlabzone.com
Understanding the Assignment
statement
• Example
int time;
.
.
.
time = 0;
.
0time
1200
Main Memory
Memory map after the
assignment statement
time = 0 is executed
.
unknowntime
1200
Main Memory
Memory map before the
assignment statement
time = 0 is executed
23. www.cyberlabzone.com
Understanding the Assignment
statement
• Example
double force;
force = 5.0;
.
.
.
force = force * 3.0;
.
15.0force
1400
Main Memory
Memory map after the
assignment statement
force = force * 3.0;
is executed
.
5.0force
1400
Main Memory
Memory map before the
assignment statement
force = force * 3.0;
but after
force = 5.0;
is executed
24. www.cyberlabzone.com
Character Values
Individual characters may be assign to variables of data-type
char.
Example: Write a program to prompt the user for a Y/ N
response. Print the users response to the screen.
#include <stdio.h>
void main(void)
{
char letter;
printf(“Please enter a response (Y/N):”);
scanf(“%c”,&letter);
printf(“Your response was: %c n”,letter);
}
25. www.cyberlabzone.com
Expression Statements
One form of a expression statement in C :
function(argument list) ;
Scanf function
accepts input from standard input device,
usually a keyboard
scanf("format string", &var1, &var2, ...);
The number of conversion specifiers should match the
number of variables that follow the “format string”.
%i,%d - decimal integer (d=decimal)
%f - float
%lf - double(where lf="long float")
%Lf - long double
%c - character
where “format string” is the string of conversion
specifiers for the various data types in the variable list.
e.g.,
26. www.cyberlabzone.com
Basic Input/Output (I/O)
sends output to standard output device,
usually a video monitor
printf("format string", output-list);
where ”format string” can contain characters to be output
and the conversion specifiers indicating type and position
of the output values. For output, we specify formats
conversion specifiers) a little differently than we do for
input. For example:
%i, %d -decimal integer
%o -octal integer
%x, %X -hex integer (use X for caps A - F)
%f -float, double
%c -character
%s -character string
Printf function
27. www.cyberlabzone.com
Output Control: Special characters
Each is represented by an escape sequence,
which is a backslash () and an escape character.
Examples are:
" - output double quotes
b – backspace
? - output question-mark character (?)
- output backslash character ()
n - new line
28. www.cyberlabzone.com
Output Control: Field Width
The number of print positions to be used in the output
of display values. For floating-point numbers, we can
also specify the number of digits to be displayed after
the decimal point.
Examples:
%3d - display an integer using 3 print positions.
%7.3f - display a floating-point number (float, or
double) using a total field width of 7 and with 3 places
after the decimal point.
29. www.cyberlabzone.com
Printf and scanf Examples
Example:
scanf("%i %f %lf %c", &n, &a, &x, &code);
Example:
printf("The sum of %i values is %f.n“,numValues,
sum);
printf("%sn", "Temperature Variations");
printf("The output is: n");
30. www.cyberlabzone.com
Comments
Comments in C are of the general form:
/* . . . */
Comments can be inserted anywhere you can put a space (blank).
Comments are ignored by the C compiler and not included in the
executable file.
The */ can be on the next line but then every character between
the /* and the */ is ignored by the C compiler.
31. www.cyberlabzone.com
Programming Errors
Syntax Errors
Run-time Errors
Logical Errors
The gcc compiler will catch these errors and give you
Error messages.
Example: x + 1 = x; (should be x = x+1; for a valid
assignment statement)
The gcc compiler will not catch these errors.
Example: User enters the value 0 and your code reads
this value into variable x, and then computes 1/x .
The gcc compiler will not catch these errors. Program
will run and not generate any error messages but
results outputted by the program are incorrect.
Example: User programs solution using the wrong
formula.
32. www.cyberlabzone.com
1. Problem Definition
Write a program that reads a number and computes the square root if
the number is non-negative.
2. Refine, Generalize, Decompose the problem definition
(i.e., identify subproblems, I/O, etc.)
Input = real number
Output=real number
3. Develop Algorithm
(processing steps to solve problem)
C problem examples
34. www.cyberlabzone.com
C program Example
/* C Program to compute the square root of a positive
number */
#include <stdio.h>
#include <math.h>
void main(void)
{
double value; /* Declare variables. */
printf(”Please enter a non-negative number :”); /* request
user input */
scanf("%lf", &value); /* read value */
/* Output the square root. */
if (value >= 0.0)
printf(”square_root(%f) = %f n", value,sqrt(value));
}
35. www.cyberlabzone.com
Selection Structures Decision statements
if(expression)
statement;
• if expression evaluates to true, the statement
is executed; otherwise execution passes to the
next statement in the program.
• if Selection Structure
if(value >= 0.0);
printf(”square_root(%f) = %f n", value,sqrt(value));
/* Error! Don’t put semicolon here */
/* This is an example of a logical error */
1. Problem Definition
Modify the previous program to notify the user when
the input is invalid.
37. www.cyberlabzone.com
C Program Examples (Modified)
/* C Program to compute the square root of a positive number */
#include <stdio.h>
#include <math.h>
void main(void)
{
double value; /* Declare variables. */
printf(”Please enter a non-negative number :”);/*request user input*/
scanf("%lf", &value); /* read value */
/* Output the square root. */
if (value >= 0.0)
printf(”square_root(%f) = %f n", value,sqrt(value));
else
printf(“invalid user input, please enter non-negative valuen”);
}
38. www.cyberlabzone.com
Math Library in C
- in header file math.h
Arguments (parameters) for each of the following
functions are assumed to be of type double. If not, a
type double copy is made for use in the function. To
compile a program that contains math functions you
need to use the -lm (Lm not 1m )option for gcc.
> gcc file.c -lm
See next slide
39. www.cyberlabzone.com
fabs (x) - |x|
sqrt (x) - square root of x
pow (x, a) - x to the power ‘a’
exp (x) - e to the power ‘x’ (e = 2.718281828 …)
log (x) - ln x = loge x
log10 (x) - log10 x
sin (x) - sine function (x in radians)
cos (x) - cosine function (x in radians)
tan (x) - tangent function (x in radians)
fmod (a, b) - remainder of a/b in floating-point
ceil (x) - smallest integer >= x
floor (x) - largest integer <= x
40. www.cyberlabzone.com
If- else Selection Structure
if (expression)
statement1;
else
statement2;
-if expression evaluates to true, statement1 is
executed and execution skips statement2
-If expression evaluates to false, execution skips
statement1 , statement2 is executed
Control Constructs
41. www.cyberlabzone.com
We can also execute multiple statements
when a given expression is true:
if (expression) {
if-statement1;
if-statement2;
if-statementn;
}
Example -
if(b < a){
temp = a;
a = b;
b = temp;
}
or
...
if (expression) {
if-statement1;
if-statement2;
if-statementn;
}
else {
else-statement1;
else-statement2;
else-statementm;
}
(what does this
code accomplish?)
...
...
If-else Selection Structure
42. www.cyberlabzone.com
C Problem Example
1. Problem Definition
Modify the previous program to compute the following:
You must check that the value is legal, i.e.
value >= 1.0 or value <= -1.0
0.1
2
value
44. www.cyberlabzone.com
/* C Program to compute the square root of */
/* value*value -1.0 */
#include <stdio.h>
#include <math.h>
void main(void)
{
double value; /* Declare variables. */
/* request user input*/
printf(”Please enter value >= 1.0 or <= -1.0 :”);
scanf("%lf", &value); /* read value */
/* Output the square root. */
if ((value >= 1.0) || (value <= -1.0))
printf(”square_root(%f) = %f n", value,sqrt(value*value - 1.0));
else {
printf(“invalid user inputn”);
printf(“input should be a value >= 1.0 or <= -1.0 n”);
}
}
C Problem Example (Modified)
45. www.cyberlabzone.com
Logical Expression (Relational Operator)
In logical expressions (which evaluate to true or
false), we can use the following Relational
operators:
Relational
Operator
Type of Test
== equal to (don’t use =)
!= not equal to
> greater than
>= greater than or equal to
< less than
<= less than or equal to
46. www.cyberlabzone.com
Logical Expression (Relational Operations)
Logical(Boolean)
Operators
&& and (true if both true)
|| or (true if at least one is true)
! not (a unary operator)
Operation
In logical expressions (which evaluate to true or
false), we can use the following Logical operators:
47. www.cyberlabzone.com
Logical Expressions
int ans, x = 3, y = 4;
ans = (x < 5)||(y >= 5); /* ans now has the value 1 */
ans = (x < 5)&&(y >= 5); /* ans now has the value 0 */
In C the value for False is represented by the value zero
and True is represented by any nonzero value. The value
False can be any zero value such as the number 0 or 0.0
or null character ‘ 0 ’ or the NULL pointer.
Example 2:
int x = 0; /* x declared as an integer variable */
/* and initialized to the value 0 */
if (x = 0) /* note the error, == should be used */
printf(“ x is zeron”); /*message not printed, why?*/
Example 1:
Caution: Avoid testing floating-
point numbers for equality! Why?
48. www.cyberlabzone.com
Nested if- else Selection Structure
1. Problem Definition
Write a program that returns a letter grade based on a quiz score. The input
will be the integer score from a 10 point quiz. The letter grades are assigned
by:
9 - 10 “A”
7 - 8 “B”
5 - 6 “C”
3 - 4 “D”
< 3 “F”
2. Refine, Generalize, Decompose the problem definition
(i.e., identify subproblems, I/O, etc.)
Input = integer score
Output=character “grade”
3. Develop Algorithm
(processing steps to solve problem)
53. www.cyberlabzone.com
C Problem Example
/* C Program to compute the letter grade for a quiz.
*/
#include <stdio.h>
void main(void)
{
int score; /* Declare variables. */
printf(”Please enter a score :”); /* request user input
*/
scanf("%i", &score); /* read value */
/* Output the grade */
/* continued on the next slide */
54. www.cyberlabzone.com
C Problem Example
if ((score == 10) || (score == 9))
printf(“An”);
else
if ((score == 8) || (score == 7))
printf(“Bn”);
else
if ((score == 6) || (score == 5))
printf(“Cn”);
else
if ((score == 4) || (score == 3))
printf(“Dn”);
else
printf(“Fn”);
} /* end of program */
Unless { } are used the else matches the first if in the code above.
55. www.cyberlabzone.com
Switch Selection structure
1. Problem Definition
Redo the previous problem by using a switch statement rather
than the nested if-else statement.
Pseudo-code Algorithm
print “enter score”
read score
switch score
score = 9,10 print “A”
score = 7,8 print “B”
score = 5,6 print “C”
score = 3,4 print “D”
otherwise print “F”
56. www.cyberlabzone.com
C Program Example
/* C Program to compute the letter grade for a quiz. */
#include <stdio.h>
void main(void)
{
int score; /* Declare variables. */
/* request user input */
printf(”Please enter a score :”);
scanf("%i", &score); /* read value */
/* Output the grade */
/* continued on the next slide */
57. www.cyberlabzone.com
C Program Example
switch (score) {
case 10:
case 9: printf(“An”);
break;
case 8:
case 7: printf(“Bn”);
break;
case 6:
case 5: printf(“Cn”);
break;
case 4:
case 3: printf(“Dn”);
break;
default: printf(“Fn”);
} /* end of switch */
} /* end of program */
58. www.cyberlabzone.com
Switch Selection Structure
The switch structure can be used when we have
multiple alternatives based on a value of type int or
type char (but not floating point). This structure has
the general form:
switch (controlling expression) {
case label1:
statements1;
case label2:
statements2;
default:
default statements;
}
(controlling expr.
must evaluate to an
integer or a
character value;
each case should
end with a break
stmt.)
...
59. www.cyberlabzone.com
1. Problem Definition
Use a while statement to read a list of integers from a file and
compute the average.
2. Refine, Generalize, Decompose the problem definition
(i.e., identify sub-problems, I/O, etc.)
Input = integers from file “input.dat”
Output=real number representing the arithmetic average =(sum of
values)/(count of number of values)
3. Develop Algorithm
(processing steps to solve problem)
C problem Example
60. www.cyberlabzone.com
Flowchart
while EOF != scanf value
total = total + value;
count = count + 1;
TrueFalse
total = 0;
count = 0;
printf total/(double) count
(double) is a cast
see slide #14
C problem Example
61. www.cyberlabzone.com
/* C Program to compute the average of a list of numbers. */
#include <stdio.h>
void main(void)
{
int value,total = 0,count = 0; /*Why are total and count set to
zero?*/
while (EOF != scanf("%i", &value)) { /* read value */
total = total + value;
count = count + 1;
} /* end of while loop */
/* Output the average. */
printf(”Average of the %i numbers = %f
n“,count,total/(float)count);
}
C problem Example
62. www.cyberlabzone.com
1. Use xemacs to enter the above code in a file problem1.c ,
and make sure to save the file.
2. Use xemacs to create an input file input.dat and enter in integers
into this file. Save and exit this file.
3. Compile the problem1.c code by typing
gcc problem1.c
C problem Example-Execution
63. www.cyberlabzone.com
4. Run the program using Unix redirection <
a.out < input.dat
5. What happens if you type
a.out < input.dat > output.dat
Note: if you do this a second time it will fail because
Unix will not let you over-write an existing file.
6. To append the results to the existing file output.dat
a.out < input.dat >> output.dat
C problem Example-I/O Redirection
64. www.cyberlabzone.com
A second form of a declaration in C :
data-type variable_name = initializer;
/*Why are total and count initialized to zero?*/
Answer: Un-initialized variables have unknown (garbage) values.
int value,total = 0,count = 0;
Assignment statement
65. www.cyberlabzone.com
while(expression)
statement;
• if expression evaluates to true, the statement
is executed and then execution loops up and
re-evaluates expression; otherwise execution
passes to the next statement in the program.
• while statement format
while(value >= 0.0);
/* Error! Don’t put semicolon here */
/* This is an example of a logical error*/
while (EOF != scanf("%i", &value)) { /* read value */
total = total + value;
count = count +1;
} /* end of while loop */
While-loop Statement
66. www.cyberlabzone.com
We can also execute multiple statements
when a given expression is true:
while (expression) {
while-statement1;
while-statement2;
while-statementn;
}
• if expression evaluates to true, all the
statements are executed and then execution
loops up and re-evaluates expression;
otherwise execution passes to the next
statement in the program.
While-General Format
67. www.cyberlabzone.com
{
statement1;
statement2;
.
.
.
statementn;
}
A sequence of statements surrounded by a pair
of curly braces is called a block or
compound statement
1) From outside, the compound statement looks
like a single statement. A compound statement
can go where any single C statement can go.
(e.g. a branch of if-else, body of a for loop, ...)
What is a Compound statement?
68. www.cyberlabzone.com
What is all this fuss about blocks?
A block is any compound statement that may include variable
declaration(s).
1.As a compound statement, from outside, the
block looks like a single C statement. A
block can go where any single C statement
can go.
2.The importance of a block is that, the curly
braces of the block delimit the Scope (i.e.
the region of validity) of the variables
declared in the block.
3. The concept of Scoping lies at the heart of
Structured Programming, as will be
discussed in a future lecture on Modularity.
69. www.cyberlabzone.com
The program makes use of the fact that the scanf function returns
and integer value representing the number of successful
conversions. For example in the code fragment:
Example:
int number,value1,value2,value3;
number = scanf(“%d%d%d”,&value1,&value2,&value3);
the variable number could take the value 0,1,2 or 3.
EOF is a built-in constant in C(usually assigned -1).
If you are checking for End-of-File then use this constant.
EOF != scanf("%i", &value)
Scanf-Revisited
70. www.cyberlabzone.com
To fix the above use the cast operator
where data_type is a valid C data type.
float result;
int total = 10 , count = 4 ;
result = total / (float) count; /* result now has the value 2.5 */
Example,
float result;
int total = 10 , count = 4 ;
result = total / count; /* result has the value 2.0 */
( data_type )
printf(”Average of the %i numbers = %fn“,count, total/(float)count );
Arithmetic Conversions-Cast
71. www.cyberlabzone.com
data_type1 x;
data_type2 result;
result = x;
If x and result have different data types then an automatic
conversion takes place. Data could be lost.
Example,
float x = 3.1416;
int result;
result = x; /* result now has the value 3 */
1) Conversion of assigned values
Arithmetic Conversions
72. www.cyberlabzone.com
+, - , * , /x op y ; where op is
If x and y have different (mixed) data types then C automatically
converts data from the lower rank to the higher rank and then
performs the computation.
Note: % (modulus) is only defined on integers.
The ranking is given by the following table.
long double Higher
double
float
long integer
integer
short integer Lower
2) Conversion of values with mixed data types
in an expression using arithmetic operators
Arithmetic Conversions
73. www.cyberlabzone.com
Example,
float result , x = 3.1416;
int y = 3;
result = x + y; /* result now has the value 6.1416 */
Example,
int x = 2.5;
float result, y;
y = x;
result = 1 / y; /* result now has the value .5 */
Arithmetic Conversions
74. www.cyberlabzone.com
1. Problem Definition
Write a program that reads a file of characters one
character at a time and writes out each non-blank character to
another file.
2. Refine, Generalize, Decompose the problem definition
(i.e., identify sub-problems, I/O, etc.)
Input = characters in a file “input2.dat” Assume this file
is non-empty.
Output=Non-blank characters from input2.dat are
output to the file output2.dat
3. Develop Algorithm
(processing steps to solve problem)
C Problem Example
76. www.cyberlabzone.com
/* C Program to remove the blanks from a text file. */
#include <stdio.h>
void main(void){
char c;
scanf("%c",&c);
do {
if (c != ' ')
printf("%c",c);
} while(EOF != scanf("%c",&c));
}
C Problem Example
77. www.cyberlabzone.com
1. Use xemacs to enter the above code in a file problem2.c ,
and make sure to save the file.
2. Use xemacs to create an input file input2.dat and enter in any
number of lines of text including blanks. Save and exit this file.
3. Compile the problem2.c code by typing
gcc problem2.c
4. Run the program using Unix redirection < and >
a.out < input2.dat > output2.dat
5. View the contents of output2.dat
more output2.dat
C Problem Example-Execution
78. www.cyberlabzone.com
do
statement;
while(expression);
• The statement is executed first. Then if expression
evaluates to true, execution loops up and the statement is
executed again; otherwise execution passes to the next
statement in the program. The general form of the do-while
statement is:
• do/while statement format
do {
while-statement1;
while-statement2;
while-statementn;
} while (expression);
C Problem Example
79. www.cyberlabzone.com
1. Problem Definition
Use a for statement to read a list of integers from a file and
compute the average. The first number in the list gives the count
of the numbers to be read. This first value is not used in the
computation of the average.
2. Refine, Generalize, Decompose the problem definition
(i.e., identify sub-problems, I/O, etc.)
Input = integers from file “input3.dat”
Output=real number representing the arithmetic average (sum of
values)/(count of number of values)
3. Develop Algorithm
Use a counter controlled loop.
(processing steps to solve problem)
C Problem Example
80. www.cyberlabzone.com
Flowchart
for i = 1 ; i <= count; i=i+1
scanf value
total = total + value;
TrueFalse
total = 0;
scanf count
printf total/(double) count
C Problem Example
81. www.cyberlabzone.com
/* C Program to compute the average of a list of numbers. */
#include <stdio.h>
void main(void)
{
int value,total = 0,count;
int i; /* loop counter */
scanf(“%i”,&count);
for(i=1;i<=count;i=i+1) {
scanf(“%i”,&value); /* read value */
total = total + value;
} /* end of for loop */
/* Output the average. */
printf(”Average of the %i numbers = %f n“,count,total/(float)count);
}
C Problem Example
82. www.cyberlabzone.com
1. Use xemacs to enter the above code in a file problem3.c ,
and make sure to save the file.
2. Use xemacs to create an input file input3.dat and enter in integers
into this file .The first integer is the count of integers to be
averaged. Save and exit this file.
3. Compile the problem1.c code by typing
gcc problem3.c
4. Run the program using Unix redirection <
a.out < input3.dat
C Problem Example-Execution
83. www.cyberlabzone.com
for(init. expressions ; expression ; update stmnts. )
statement1;
C allows more than one initialization expression or update statement but
these statements or expressions must be separated by a comma not a
semicolon. Also, if there is more than one init. expression or update
statement then the order of execution is from left to right.
The initialization expressions are executed once (and only once) .
If expression evaluates to true, statement1 is executed and execution loops
up and evaluates all the update stmnts. and then expression is
re-evaluated; otherwise execution passes to the next statement in the
program.
The following order of must be observed …
init. expressions; expression ; update stmnts
for-loop Statement
84. www.cyberlabzone.com
for(init. expressions ; expression ; update stmnts. ){
statement1;
statement2;
.
.
.
statementn;
}
The initialization expressions are executed once (and only once) ,
next:
if expression evaluates to true, the statements
statement1,... ,statementn are executed and execution
loops up and evaluates all the update stmnts. and then
expression is re-evaluated;
otherwise execution passes to the next statement in the program.
for-General Format
85. www.cyberlabzone.com
Write a code fragment to add the integers from 1 to 100.
int i,total;
total = 0;
for(i=1;i<=100;i=i+1)
total = total + i;
The above code could be re-written as:
int i,total;
for(i=1, total = 0; i<=100; total=total+i, i=i+1);
but not as:
int i,total;
for(i=1, total = 0; i<=100; i=i+1, total=total+i);
Why not? The order of the statements is critical!
for-Examples
86. www.cyberlabzone.com
1. Problem Definition
Use a for statement to read a list of integers from a file and
compute the average. Read the integers until the sentinel value of
-999 occurs. Do not use the sentinel value in the computation of
the average.
2. Refine, Generalize, Decompose the problem definition
(i.e., identify sub-problems, I/O, etc.)
Input = integers from file “input4.dat”
Output=real number representing the arithmetic average (sum of
values)/(count of number of values)
3. Develop Algorithm
(processing steps to solve problem)
C Problem Example-Revisited
87. www.cyberlabzone.com
Flowchart
for i = 1 ; ; i=i+1
scanf value
if value == -999
break;
total = total+value;
TrueFalse
total = 0;
printf total/(float) (i-1)
C Problem Example-Revisited
88. www.cyberlabzone.com
/* C Program to compute the average of a list of numbers. */
#include <stdio.h>
void main(void)
{
int value,total = 0,count;
int i; /* loop counter */
for(i=1; ;i=i+1) {
scanf(“%i”,&value); /* read value */
if (value == -999) /* -999 is the sentinel value */
break;
total = total + value;
} /* end of for loop */
/* Output the average. */
count = i-1;
printf(”Average of the %i numbers = %f n“,count,total/(float)count);
}
C Problem Example-Revisited
89. www.cyberlabzone.com
Omitting the logical expression in a for statement means
that the for statement executes as an infinite loop.
for(i=1; ;i=i+1) {
As with the switch statement the break statement causes
the termination of the loop but not the program.
Break Statement
90. www.cyberlabzone.com
A one dimensional array is a list of data values, with
all values having the same data type(the base type),
such as:
• integer
• float
• double
• char
Technically, an array is a uniform data structure.
Individual array elements are referenced using
the array name and a subscript that identifies the
element position in the array.
What is an Array?
Array
91. www.cyberlabzone.com
For a one dimensional array, we specify the array name, its
base data type, and the number of storage locations
required using declarations such as
int a[25];
float x[100], y[100];
which specifies 25 integer locations for a and 100 floating-
point locations for arrays x and y.
Storage for array elements are in contiguous locations in
memory, referenced by subscript(or index) values starting at 0.
Thus for array a above, the storage is
. . .
a[0] a[1] a[24]
RAM
Declaring an Array
92. www.cyberlabzone.com
We can initialize array elements in declaration
statements; e.g.,
int counts[5] = {1, 2, 3, 4, 5};
int evens[] = {2, 4, 6, 8};
The array size could also be specified using a symbolic
constant:
#define ARRAY_SIZE 25
int a[ARRAY_SIZE];
.
.
.
/* evens has 4 elements */
We cannot specify more initial values than there are array
elements, but we can specify fewer initial values, and the
remaining elements will be initialized to 0. e.g.,
int b[10] = {2};
double x[250] = {0};
Declaring and initializing an Array
93. www.cyberlabzone.com
Note: when referencing a particular element of an array use
square brackets, not parenthesis or curly braces.
Given that the array x is declared as:
int x[250];
To initialize a large array to a nonzero value - say 10, we
can use a loop. e.g.,
for (k = 0; k <= 249; k = k+1)
x[k] = 10;
k is a subscript
Arrays-Subscripting
94. www.cyberlabzone.com
A subscript value for an array element can be specified as any
integer expression.
For example, given the following declarations:
double y[4] = {-1.0, 12.0, 3.5, 3.2e-2};
int c = 2;
the following statement would assign the value of 5.5 to y[1]
y[2 * c - 3] = 5.5;
Arrays-Subscripting
95. www.cyberlabzone.com
Given an integer value n, we can use the
following code to compute and store the first n
Fibonacci numbers in an array:
1. Problem Definition
Write a program “fib” that prompts the user for an integer n. The
program prints the first n Fibonacci numbers.
2. Refine, Generalize, Decompose the problem definition
(i.e., identify sub-problems, I/O, etc.)
Input = n - the count of Fibonacci Numbers to be printed
Output= Fib Numbers printed to screen.
3. Develop Algorithm
Use the formula: fib0= 1, fib1 =1 and for k > 1
fibk = fibk-1 + fibk-2
Example-Fibonacci Numbers
96. www.cyberlabzone.com
#include <stdio.h>
/* C program to print the first n Fibonacci Numbers. */
void main(void){
int k,n;
int fib[100] = {1,1}; /* note: n must be <= 100 , why ? */
printf(“How many Fibonacci number do you want listed?”);
scanf(“%i”,&n);
for (k = 2; k < n; k++) /* the ++ is the increment operator */
fib[k] = fib[k-1] + fib[k-2];
/* print the results, four per line */
for (k = 0; k < n;++k){
if (k % 4 == 0)
printf(“n”);
printf("%8i", fib[k]); /* that’s 8 ints */
} /* end of for loop */
printf(“n”);
} /* end of main */
(For large values of parameter n, we would need more space for each
print column. Also, even with data type long , the calculated values may
become too large for the allocated storage space.)
97. www.cyberlabzone.com
:
.
Since incrementing and decrementing (negative increments)
are common programming operations, the C language
provides shortcut Increment / Decrement operators.
++k Increment k by 1 and use incremented value
in expression containing ++k.
k++ Use the current value of k then increment by 1.
--k Decrement k by 1 and use decremented value
in expression containing --k.
k-- Use current value of k then decrement by 1.
++k;
Increment and Decrement Operators
98. www.cyberlabzone.com
++k; /*C statement k = k + 1; */
int x,z;
int y = 1;
int a = 2;
x = y + a++;
/* now x = 3 , y = 1 , a = 3 */
z = x + --a;
/* now a = 2, z = 5, x = 3, y = 1 */
z = --x * ++y;
/* now x = 2, y = 2, z = 4, a = 2 */
x = a++ / --y;
/* now y = 1, x = 2, a = 3, z = 4 */
Note: The increment/decrement operators can be
applied only to single variables. They cannot be
applied to expressions.
Increment and Decrement Operators-Examples
99. www.cyberlabzone.com
Given an integer value n, we can use the following code to
compute and store the first n Fibonacci numbers in an array:
1. Problem Definition
Write a program that inputs a list of numbers into an array. The
program then calculates the average value, and then prints a list
of differences. The differences are computed by taking the original
values in the list minus the average.
2. Refine, Generalize, Decompose the problem definition
(i.e., identify sub-problems, I/O, etc.)
Input = list of reals in a file “input.dat” . We will use Unix
redirection to read values from this file.
Output= The average and the list of differences.
Example-Average and difference List
100. www.cyberlabzone.com
int counter,k;
double datVal[500]; /* 500 element max */
double datAve;
double sum = 0.0;
/* read the file and compute the average */
counter = 0;
while (EOF != scanf("%lf", &datVal[counter])){
sum += datVal[counter]; /* += is an assignment operator */
counter++;
}
/* compute and print the average */
datAve = sum /counter;
printf(“The average is:%lf n", datAve);
/* compute and print the diff list */
for(k=0;k<counter;++k)
printf(“%lfn", datVal[k]-datAve);
Example-Average and difference List
101. www.cyberlabzone.com
- a shortcut method for writing assignment statements of the
form
var1 = var1 op expression;
Using an "assignment operator", we can rewrite the above as
var1 op= expression;
where op can be any one of the arithmetic
binary operators:
+ - * / %
sum += datVal[counter];
Assignment-operators
102. www.cyberlabzone.com
sum += datVal[counter]; or
sum = sum + datVal[counter];
k += 5; or k = k +5;
n -= 4; or n = n -4;
a *= 2.0; or a = a*2.0;
x /= b; or x = x/b;
remainder %= 6; or
remainder = remainder % 6;
newValue += (a-b)/(2*c); or
newValue = newValue + (a-b)/(2*c);
Assignment-operators-Examples
103. www.cyberlabzone.com
Unlike many other languages, there is no data type for
character strings in C. But we can reference a string as
a one dimensional array of characters. That is, each
element of the array is a single character.
Character Arrays
104. www.cyberlabzone.com
char aString[5] = "Zip!";
char atomic[ ] = "hydrogen";
char aString[] = {'Z', 'i', 'p', '!',
'0'};
Declaring a string array with character constants
Declaring character arrays with a string constant
IMPORTANT!!!
In C, you must always terminate a character array with the
NULL character, ‘0’ . Therefore, the array size of your
character array should be one plus the maximum length of
the string you want to store. Example: In the declaration
char atomic[ ] = "hydrogen";
“atomic” is an array of nine elements, the last being ‘0’
Declaring a Character Array
105. www.cyberlabzone.com
char atomic[ ] = "hydrogen";
You may declare and initialize a character arrays
with a string constant as in,
but you cannot assign an array in the same
manner, e.g.
atomic = "hydrogen"; not legal in C!
One of the mysteries of C!
Declaring a Character Array
106. www.cyberlabzone.com
Use the %s conversion specifier to read in a string of
characters. Any blanks will be skipped.
There should not be any blank character input such as in the
string “Hello World”, since a blank signals an end of input for
the string.
Again, don’t forget to declare the array size as one more than
the length of the longest string that you want to read in
order to accommodate the NULL character.
char strArray [10];
printf("Input a string with at most nine characters ”);
printf("with no blanks in the string: n");
scanf("%s", strArray);
/* Notice: No & is used for an array argument! */
printf(“n%s", strArray);
Input and output of Strings
107. www.cyberlabzone.com
You can use the %c conversion specifier to output
the string character by character.
k = 0;
while (strArray[k] != NULL)
printf("%c", strArray[k++]);
NULL is a built-in constant (‘0’). You must have
#include <stdio.h> in your file to be able to use NULL.
Outputing a String
108. www.cyberlabzone.com
• strlen(str) - string length, not counting NULL char.
• strcpy(str1, str2) - copy string2 to string1.
• strcmp(str1, str2) - returns a negative , zero or positive int
depending on whether str1 is lexicographically
less than, equal or greater than str2 respectively.
• strncmp(str1,str2,n) - like strcmp but just the first n characters
of str1 are compared to str2.
#include <string.h>
Arguments str1 and str2 in the following functions can be
character array names, string pointers(discussed in a future
lecture), or string constants.
See Chapter 13.3 for examples. There are many other string
functions (see Appendix G p. 1036 for a complete list).
String.h Library Functions
109. www.cyberlabzone.com
1. Problem Definition
Write a C program that converts a Morse code string into alphabet.
(Morse code is a sequence of dots and dashes). If the input is not a
valid string (see table on next slide) then a message is output to the
user. You will do a variation of this program in a future lab
assignment.
2. Refine, Generalize, Decompose the problem definition
(i.e., identify sub-problems, I/O, etc.)
Input = a single string of characters.
Output= A single letter A-Z.
Example-Morse Code
110. www.cyberlabzone.com
A .- , N -.
B -... O ---
C -.-. P .--.
D -.. Q --.-
E . R .-.
F ..-. S ...
G --. T -
H .... U ..-
I .. V ...-
J .--- W .--
K -.- X -..-
L .-.. Y -.--
M -- Z --..
112. www.cyberlabzone.com
char alphabet[26] = {'A','B','C','D','E','F','G','H','I','J','K',
'L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};
char input[5];
int i;
int flag = 0; /* flag = 0 means match not found ,
flag = 1 means match found */
printf("Please enter a Morse code string:");
scanf("%s",input); /* no & for array */
113. www.cyberlabzone.com
/* loop through the Morse array to find a match */
for(i=0;i<26;++i)
if (strcmp(input,morse[i]) == 0)
{
printf("%cn",alphabet[i]);
flag = 1;
break; /*terminate for loop */
}
if (flag == 0)
printf("Input not a valid Morse character.n");
} /* end of main */
114. www.cyberlabzone.com
The typedef mechanism in C enables a programmer to create
a “custom” data-type.
Examples of the use of typedef are
typedef int blah; /* don’t do this !!!!! */
typedef char string[5];
In the first example we give another name or alias to the
data-type int .
In the second example we create a new data-type named
string.
typedef
115. www.cyberlabzone.com
To declare a variable of data-type blah ,
blah x;
this declaration is equivalent to
int x;
To declare a variable of data-type string ,
string var =“init”; /* declare and initialize */
scanf(“%s”,var); /* we can read in a string of chars */
var = “next”; But we can’t do this!!!
The declaration
string morse[26];
declares morse as an array of 26 elements. Each element
has data-type string.
typedef
116. www.cyberlabzone.com
The declaration and initialization:
string morse[26] =
{".-", "-...", "-.-.", "-..", ".", "..-.",
"--.", "....", "..", ".---", "-.-", ".-..",
"--", "-.", "---", ".--.", "--.-", ".-.", "...",
"-", "..-", "...-", ".--", "-..-", "-.--", "--.. " };
declares morse as an array of 26 elements with
morse[0] = “.-”
morse[1] = “-...” and so on...
typedef
117. www.cyberlabzone.com
- Two dimensional arrays are declared
similarly to one dimensional arrays:
char t[20][10]; (and referred to as a
matrix, or as a "table")
The first subscript gives the row number, and
the second subscript specifies column number.
Two-Dimensional Arrays
118. www.cyberlabzone.com
We can also initialize a two-dimensional array
in a declaration statement; E.g.,
int m[2][3] = {{1, 2, 3}, {4, 5, 6}};
which specifies the elements in each row of the
array (the interior braces around each row of
values could be omitted). The matrix for this
example is
654
321
m
Declaration and Initialization
119. www.cyberlabzone.com
Specification of the number of rows could be
omitted. But other subscript specifications can
not be omitted. So, we could also write the
initialization as
int m[ ][3] = {{1, 2, 3}, {4, 5, 6}};
Declaration and Initialization
120. www.cyberlabzone.com
int a[2][3]= {1,2,3,4,5,6};
specifies 6 integer locations.
Storage for array elements are in contiguous locations in
memory in row major order (unlike column major order in
Fortran), referenced by subscripts(or index) values starting at
0 for both rows and columns.
a[0][0] a[0][1] a[0][2] a[1][0] a[1][1] a[1][2]
RAM
1 2 3 4 5 6
Memory Storage for a Two dimensional Array
121. www.cyberlabzone.com
1. Problem Definition
Assume we have a file “in.dat” (located in the pwd) consisting of 10 rows of
10 integers per row (100 integers total). Write a C program which reads
from the file and stores the numbers in a two dimensional array named
‘mat’, computes the largest of all of these numbers and prints the largest
value to the screen.
2. Refine, Generalize, Decompose the problem definition
(i.e., identify sub-problems, I/O, etc.)
Input = from file “in.dat”
Output= Largest of the 100 integers printed to screen.
3. Develop Algorithm
Use Unix redirection to read file “in.dat”.
Use nested for loop to go through two dimensional array to
find the largest value.
Example-Maximum Value
122. www.cyberlabzone.com
#include <stdio.h>
void main(void){
int row, col, maximum;
/* Declare a 2-D array called ‘mat’ which can hold a 10-by-10 */
/* matrix of integers */
int mat[10][10];
/* Write code here to read from the file ‘in.dat’ */
for(row=0;row<10;++row)
for(col=0;col<10;++col)
scanf(“%d”,&mat[row][col]);
/* Write code to find the largest value in the array ‘mat’ */
maximum = mat[0][0]; /* why ??? */
for(row=0;row<10;++row) /* How does this work??? */
for(col=0;col<10;++col)
if (mat[row][col] > maximum)
maximum = mat[row][col];
/* Print the largest value to the screen */
printf(“ max value in the array = %dn”,maximum);
}
123. www.cyberlabzone.com
Another example of the use of typedef is:
typedef double matrix[size][size];
In this example we create a new data-type named matrix.
We can declare a variable of data-type matrix by
matrix a;
this declaration is equivalent to
double a[size][size];
Typedef Revisited
124. www.cyberlabzone.com
Standard (ANSI) C allows up to 12 dimension.
But more computation is required by the system
to locate elements in multi-subscripted arrays.
Therefore, in problems involving intensive
numerical calculations, we should use arrays
with fewer dimension.
We can also use 3, 4, … dimensional arrays,
e.g.,
threeDArray [i][j][k];
Higher Dimensional Arrays
125. www.cyberlabzone.com
In slides 2-15 and 11-15 we discussed a method for creating
programs. In step three “Develop the Algorithm”, the nature of the
programming problem may suggest that we use top down
programming (as opposed to bottom-up programming , ...)
An analogy for top-down design is the following: Suppose a
general contractor was hired to construct a commercial building. The
contractor would need to know where to build and what are the blue-
prints. Then the contractor would hire various sub-contractors to dig
foundation, install electric, plumbing, frame, roof. That is, the large
job would be broken into smaller jobs, however these jobs must be
performed in some sequence and not at random.
Function-”Top Down Design”
126. www.cyberlabzone.com
In top-down design for programming, we specify the first function to
be invoked (the top function or “general contractor”). In C the top
function is called “main”.
The programmer then refines “main” into its component functions
(sub-contractors), which may in turn be refined into further functions,
and so on.
Function-”Top Down Design”
127. www.cyberlabzone.com
1. Problem Definition
Write a program that inputs a list of numbers into an array. The
program then calculates the average value, and then prints a list
of differences. The differences are computed by taking the original
values in the list minus the average.
2. Refine, Generalize, Decompose the problem definition
(i.e., identify sub-problems, I/O, etc.)
Input = list of reals in a file “input.dat” . We will use Unix
redirection to read values from this file.
Output= The average and the list of differences.
Example-Average and difference List
128. www.cyberlabzone.com
#include <stdio.h>
int read(double datVal[]); /* prototype for read function */
double ave(int counter,double datVal[]);
/* prototype for ave function */
void diff(double datAve, int counter, double datVal[]);
/* prototype for diff function */
void main(void){
int counter,k;
double datVal[500]; /* 500 element max */
double datAve;
counter = read(datVal); /* read file into datVal */
datAve = ave(counter,datVal); /* compute & print average */
printf(“The average is:%f n", datAve);
diff(datAve,counter,datVal); /* compute diff list */
for(k=0;k<counter;++k) /* print the diff list */
printf(“%lfn", datVal[k]);
} /* end of main */
129. www.cyberlabzone.com
/* read function */
int read(double array[]) {
int count = 0;
while (EOF != scanf("%lf", &array[count])){
++count;
}
return count;
} /* end of read function */
/* ave function */
double ave(int count,double array[]){
int i;
double sum = 0.0;
for (i=0;i<count;++i)
sum += array[i];
return sum/count;
} /* end of ave function */
/* diff function */
void diff(double average, int count, double array[]){
int i;
for (i = 0;i<count;++i)
array[i] -= average;
} /* end of diff */
130. www.cyberlabzone.com
1. Use xemacs to enter the above code in a file problem1.c ,
and make sure to save the file.
2. Use xemacs to create an input file input.dat and enter in integers
into this file. Save and exit this file.
3. Compile the problem1.c code by typing
gcc problem1.c
4. Run the program using Unix redirection <
a.out < input.dat
C Problem Example-Execution
131. www.cyberlabzone.com
Example:
If the file input.dat has the values:
1.0 2.0 3.0 4.0 5.0
Then the program would execute as follows:
dclsn70> a.out < input.dat
The average is:3.000000
-2.000000
-1.000000
0.000000
1.000000
2.000000
dclsn70>
C Problem Example-Execution
132. www.cyberlabzone.com
#include <stdio.h> /* include statements */
int read(double datVal[]); /* prototype for read function */
void main(void) /* definiton of the main function */
{
/* C code here */
} /* end of main */
int read(double array[]) /* function definition */
{
/* more C code here */
} /* end of read */
One method to code the function “read”in C :
Functions-Prototypes
Functions
133. www.cyberlabzone.com
In the latest versions of standard C ("ANSI C"),
the function prototype is used to define the data
type to be returned by the function, the number
and data type of function parameters, and the
order of the function parameters. This info is
used by the C compiler to validate calls to the
function.
A general principle in C is that you must declare
or define the variable or function before you use
them.
Functions-Prototypes
134. www.cyberlabzone.com
The actual variable or array name is not needed in the
function prototype.
Examples:
Instead of the following prototypes
int read(double datVal[]);
double ave(int counter,double datVal[]);
void diff(double datAve, int counter, double datVal[]);
we could have used
int read(double []);
double ave(int ,double []);
void diff(double , int , double []);
Functions-Prototypes
135. www.cyberlabzone.com
#include <stdio.h> /* include statements */
/* Since the definition of read occurs before it is */
/* used (called) by main, we don’t need a prototype.*/
int read(double array[]) /* function definition */
{
/* C code for read here */
} /* end of read */
void main(void) /* definiton of the main function */
{
/* C code for main function here */
} /* end of main */
Another method to code the function “read ” in C
without using a prototype :
Functions-Prototypes
136. www.cyberlabzone.com
• The function definition in C is of the form:
return-type function-name(parameter-list)
{
/* function code */
return (value); /* parenthesis optional */
}
• The “value” can be a single variable, constant, or any C expression.
• The data type of “value” should be of type “return-type”, if not
then a conversion of the “value” to the “return-type” is specified
by the C compiler.
• If the “return-type is void then the programmer can omit the return
statement or code: return ; /* return nothing */
Function- definition
137. www.cyberlabzone.com
/* function called */
int x = 1;
float y = 2.0;
float value;
double z = 5.0;
value = sum(x,y,z+4.0);
/* more code here */
/* sum adds an integer a float and a double and returns */
/* a double */
double sum(int a, float b, double c)
{
double result;
result = a + b + c;
return result;
}
Data-types agree!
Since value has type
float and sum returns
a double, a conversion
takes place.
Function Type Checking
138. www.cyberlabzone.com
• A function that does not return a value is declared to
be of type void. e.g.,
void printFunction (int, int);
• If a function takes no parameters, we specify the
parameter list as void. e.g.,
void printPageHeading (void);
It is also possible to specify an "empty" parameter list:
void myFunction ( );
- argument checking is "turned off", so that anything
can be passed to myFunction. Best to avoid this in C.
Function Type Checking
139. www.cyberlabzone.com
• By default , if you omit the data type of the return
value, C assumes that the function returns an int value
(not void). Therefore the following function header:
main(void)
int main(void)
is equivalent to:
Function Type Checking
140. www.cyberlabzone.com
• A function may be called from any function (including itself) in C.
• A call is of the form:
function-name(argument-list)
• To “call” or invoke a function, you must pass the same
number of arguments for which the function has been defined.
The order of the arguments is important!!!
• If the data types in the argument list do not match the data
types in the parameter list, a conversion(or coercion) takes
place.
Function Call
141. www.cyberlabzone.com
.
.
.
int x = 1;
double y = 2.0;
float result;
/* function called */
result = F1(x,x+1,sin(y)); /* argument list */
.
.
.
} /* end main */
/* data types match */
float F1(int var1, int var2, double var3){ /*parameter list
*/
/* function code */
return (value);}
Example-Function Type Checking
142. www.cyberlabzone.com
• Arrays are passed as call-by-reference.
counter = read(datVal);
.
.
.
int read(double array[]) {
int count = 0;
while (EOF != scanf("%lf",
&array[count])){
++count;
}
return count;
} 2.0
1.0
1200
Main Memory after call
unknowndatVal[0]
datVal[1]
datVal[2]
1200
Main Memory before call
datVal[0]
datVal[1]
datVal[2]
.
.
.
.
.
.
.
.
.
.
.
.
The parameter “array” can be
considered as a pseudonym or
alias for “datVal”. There is only
one array in memory.
Passing arguments in a function Call
143. www.cyberlabzone.com
For two dimensional arrays, we could omit
specification of the number of rows in
function prototype and header. But we must
include size declaration for the number of
columns.
(see example on next slide)
Two-Dimensional Arrays Function Parameters
144. www.cyberlabzone.com
#define ROWS 10
#define COLS 5
void doSumpin(int [][COLS]);
int main (void)
{
int a[ROWS][COLS] = {{0}};
doSumpin (a);
}
void doSumpin(int b[][COLS]){ /* array passed by reference */
...
}
/* function prototype */
/* function call */
Examples of passing 2-D arrays
145. www.cyberlabzone.com
We can replace any 2-D array with an equivalent 1-D
array. For instance the following 2-D array
int A[2][3]= {1,2,3,4,5,6};
A[0][0] A[0][1] A[0][2] A[1][0] A[1][1] A[1][2]
RAM
1 2 3 4 5 6
can be replaced with the equivalent 1-D array,
int a[6]= {1,2,3,4,5,6};
however a[0][0] , a[0][1] , … is not defined.
Alternative to 2-D arrays
146. www.cyberlabzone.com
In order to reference A[0][0] , A[0][1] , … with a[ ]
we use the following formula,
int a[]= {1,2,3,4,5,6};
A[row][col] = a[row*3 + col]
A[0][0] A[0][1] A[0][2] A[1][0] A[1][1] A[1][2]
RAM
1 2 3 4 5 6
a[0] a[1] a[2] a[3] a[4] a[5]
Alternative to 2-D arrays
147. www.cyberlabzone.com
1. Problem Definition
Write a function that performs matrix – vector multiplication.
Assume that the matrix is passed as a
1-D array using the formula on the previous slide.
2. Refine, Generalize, Decompose the problem definition
(i.e., identify sub-problems, I/O, etc.)
Input = A matrix and vector of reals .
Output= The vector that results from the matrix - vector
multiplication.
Alternative to 2-D arrays
148. www.cyberlabzone.com
/* The function mvmult works with any size matrix a. */
/* This function assumes that the number of Cols of a is */
/* equal to the number of Rows of invec */
/* a is 1-D version of matrix A[Rows][Cols] */
void mvmult(double a[], int Rows, int Cols, double invec[],
double outvec[]){
int row, col;
/* A[row][col] = a[row*cols + col] */
for(row=0;row<Rows;++row){
outvec[row] = 0.0;
for(col=0;col<Cols;++col)
outvec[row] += a[row*Cols +col] * invec[col];
}
} /* end of mvmult */
149. www.cyberlabzone.com
1. Use xemacs to enter the above code in a file mvmult.c ,
and make sure to save the file.
2. Use xemacs to create a file test.c and write the main function that
calls the mvmult function. Don’t forget the prototype!
3. Compile the code in the two files mvmult.c and test.c by typing,
gcc test.c mvmult.c -o mult
4. Run the program
mult
C Problem Example-Execution
152. www.cyberlabzone.com
• Non-arrays are passed as call-by-value.
datAve = ave(counter,datVal);
.
.
.
double ave(int count,double
array[]){
int i;
double sum = 0.0;
for (i=0;i<count;++i)
sum += array[i];
return sum/count;
}
1196
Main Memory while executing ave
5
counter
1196
Main Memory before call
counter
.
.
.
The value of the parameter “counter” is copied into the
memory location for the variable “count”. Therefore any
change to “count” would have no affect on “counter”.
1192count 5
55
Passing arguments in a function Call
153. www.cyberlabzone.com
1. Problem Definition
Write a function “sinc” that computes the value of
sin(x)/x . If x is zero return 1.0.
2. Refine, Generalize, Decompose the problem definition
(i.e., identify sub-problems, I/O, etc.)
Input = One real number of type double.
Output= sin(x)/x as a double if x is not zero else 1.0.
3. Develop Algorithm
Use an if statement to check for a non-zero value.
But since the user could input 1.0e-600 , this may cause an
overflow when the value 1/x is computed so we will actually not
check for equality with zero but will check if the input value is
close to zero.
Example-Call-by-value
154. www.cyberlabzone.com
#include <stdio.h>
#include <math.h>
double sinc (double); /* function prototype */
void main(void){
double x, y;
printf("Enter a number: ");
scanf("%lf", &x);
y = sinc(x); /* function call */
printf(“n sinc(%f) = %f n”, x, y);
}
double sinc (double x){ /* function header */
if (fabs(x) < 1.0e-15)
return 1.0;
else
return sin(x) / x; } /* notice that sinc calls sin */
Example: function sinc(x)=sin(x)/x
155. www.cyberlabzone.com
Using Xemacs, user-defined functions can be typed into the same
file as “main”.
Functions may be typed into a separate file. For example, suppose
“main” is in the file test.c and the user defined function “sinc” is
entered into the file func.c then to compile both “main” and “sinc”
you would type (at the Unix prompt)
gcc test.c func.c -lm Note the use of the “-lm” option
The -lm option is needed only if you use a math library function in
“main” or “sinc”.
Don’t forget that if you put the function “sinc” into a separate file,
then you must still put the prototype for “sinc” in the same file as
main. The prototype for “sinc” must precede the function main.
Example: Location of user-defined functions
156. www.cyberlabzone.com
We present some methods to debug C programs.
We can categorize errors as
A) compile errors
B) run-time errors
C) Logical errors
Logical errors are the most difficult since they may involve using
the incorrect formula. This has nothing to do with C so we will not
discuss these types of errors any further.
Debugging
157. www.cyberlabzone.com
We present some methods to debug C programs.
A) compile errors
If your program doesn’t compile.
1) Check the line number that gcc returns for the error.
Note: a warning message is not an error. If you only have
warning messages gcc will go ahead and compile your code.
2) Sometimes the line number of the error is not where the
actual error occurred. An error on one line can produce
errors messages for subsequent lines. Therefore it is best in
general to fix the errors occurring on the earliest line numbers
first. Also, if you can’t find an error on the line specified by
gcc then look at the preceding lines.
Compiler Errors
158. www.cyberlabzone.com
A) compile errors(continued)
3) If you can’t find the error specified by gcc then try removing
some code by using the #ifdef feature of C. This is a
preprocessor command that will optionally compile (or not
compile) a group of statements. Or gcc allows you to use the
characters // at the beginning of a line to comment out that line
of code.
Compiler Errors
159. www.cyberlabzone.com
Example: On slide 25 add a semicolon to the which contains the
code:
if (fabs(x) < 1.0e-15);
When you compile you get an error message.
The error message states the problem is before line 15 but the
actual problem occurred on line 13.
dclsn70> gcc test.c -lm
test.c: In function `main':
test.c:4: warning: return type of `main' is not `int'
test.c: In function `sinc':
test.c:15: parse error before `else'
dclsn70>
Compiler Errors
160. www.cyberlabzone.com
Example: Use #ifdef to have the compiler skip
compiling line(s) of code.
From the previous problem add the #ifdef as follows:
double sinc (double x){ /* function header */
if (fabs(x) < 1.0e-15);
#ifdef foo
return 1.0;
#endif
else
return sin(x) / x; } /* notice that sinc calls sin */
Compiler Errors
161. www.cyberlabzone.com
From the above we can see that the code now compiles without
errors.
The reason for this is that the if-else statement is now a valid
statement. If the condition is true do nothing else return sin(x)/x .
Even if you don’t see the extra semicolon, at this point you know
that your if-else statement was the source of your previous compile
error.
dclsn70> gcc test.c -lm
test.c: In function `main':
test.c:4: warning: return type of `main' is not `int'
dclsn70>
Compiler Errors
162. www.cyberlabzone.com
B) run-time errors
If your program compiles without errors but you get incorrect
values or a message like “Segmentation fault”.
1) Use the statement:
fprintf(stderr, “format string”,variable-list);
Run-time Errors
163. www.cyberlabzone.com
On slide 25 remove the “&” symbol to obtain the following line:
scanf("%lf", x);
When you compile and run a.out you get the run-time error
“Segmentation Fault”,
dclsn70> gcc test.c -lm
test.c: In function `main':
test.c:4: warning: return type of `main' is not `int'
dclsn70> a.out
Enter a number: 3.14159
Segmentation fault
dclsn70>
Run-time Errors
164. www.cyberlabzone.com
Example: Use the fprintf statement to debug your code.
void main(void){
double x, y;
printf("Enter a number: ");
fprintf(stderr,“Before scanfn”);
scanf("%lf", &x);
fprintf(stderr,”After scanf x = %lfn”,x);
y = sinc(x); /* function call */
fprintf(stderr,“After sincn”);
printf(“n sinc(%f) = %f n”, x, y);
}
Run-time Errors
165. www.cyberlabzone.com
dclsn70> gcc test.c -lm
test.c: In function `main':
test.c:4: warning: return type of `main' is not `int'
dclsn70> a.out
Before scanf
Enter a number: 3.14159
Segmentation fault
dclsn70>
Since only “Before scanf” prints to the screen (specified by stderr).
This indicates that the problem occurs in the scanf statement.
Run-time Errors
166. www.cyberlabzone.com
1. Problem Definition
Write a function “swap” that has two integer input arguments.
This function should swap the values of the variables.
2. Refine, Generalize, Decompose the problem definition
(i.e., identify sub-problems, I/O, etc.)
Input = two integers
Output= no value is returned to the calling function, but the values
of the called variables should be swapped.
3. Develop Algorithm
temp = a;
a = b;
b = temp;
Example-call-by-value
167. www.cyberlabzone.com
/* C Function to swap values. */
#include <stdio.h>
void swap(int, int); /* prototype for swap */
void main(void){ /* function header */
int x = 1;
int y = 2;
swap(x,y);
printf(“x = %d , y = %d n”,x,y); /* prints x = 1 , y = 2 */
}
void swap(int a , int b){
int temp = a;
a = b;
b = temp;
return;
}
Example-bad Swap!!!
168. www.cyberlabzone.com
x
1000
Main Memory before call
1
The swap function will successfully swap the values of the variables a and
b.
But, since non-arrays are passed by value the swap of the values for a and
b will not have any affect on the variables x and y.
It is important to note that even if we had used the variable names x and y
rather than a and b the swap function would still not work. See the next
slide...
y 2
Main Memory while executing swap,
but before the return statement
x
1000
1
y 2
a 2
b 1
3000
Why swap doesn’t work.
169. www.cyberlabzone.com
/* Modified function to swap values. */
#include <stdio.h>
void swap(int, int);
void main(void){
int x = 1;
int y = 2;
swap(x,y);
printf(“x = %d , y = %d n”,x,y); /* prints x = 1 , y = 2 */
}
void swap(int x , int y){ /* we now use x and y */
int temp = x;
x = y;
y = temp;
return;
}
Example-bad Swap!!!
170. www.cyberlabzone.com
x
1000
Main Memory before call
1
The C compiler will keep track of the variables x and y declared in main and
the variables x and y declared in swap. The x in main is a different variable
than the x in swap. Similarly for the y variable.
The reason that the x variable in main is different than the x variable in
swap is that two declarations of x occur in different blocks. That is the
scope of the x in main is different than the scope of x in swap.
One solution to the problem is to use pointer variables. We will discuss
pointer variables in a future lecture.
y 2
Main Memory while executing swap,
but before the return statement
x
1000
1
y 2
x 2
y 1
3000
Why the modified swap doesn’t work.
171. www.cyberlabzone.com
An identifier is a name that is composed of a sequence of letters,
digits, and the ‘_’ underscore character.
Variable names are identifiers and so are function names and
symbolic constant names.
The scope of an identifier is the portion of the program in which
the identifier is visible or accessible.
Both variables and functions have two attributes: type and
storage class. The scope of a variable or function is related to its
storage class.
Scope of Identifiers
172. www.cyberlabzone.com
•Local Variables - are declared within a block and cannot be referenced
by outside the block; i.e., each function is assigned its own "local"
storage areas.
•Global Variables - declared outside any block and are known to all
blocks in the same file . By default, global variables are "static”
storage class.
In the examples on the following slides, drawing a picture of memory is
helpful in understanding how scoping works.
Scope of Variable Names
173. www.cyberlabzone.com
int globalVar = 1; /* global variable */
int myFunction(int); /* function prototypes */
void main(void){ /* local variable: result, in main */
int result;
result = myFunction(globalVar); /* call myFunction */
printf(“%d”,result); /* prints “2” */
printf(“%d”,globalVar); /* prints “2” */
printf(“%d”,x); /* compile error! x not known in main */
}
int myFunction(int x){ /* Local variable x */
++x;
printf(“%d”,x); /* prints value “2” */
printf(“%d”,globalVar); /*prints value“1” */
++globalVar;
return x;
}
Example1:Scope of Variables
Program Design Example
174. www.cyberlabzone.com
globalVar
1000
Main Memory before call to Myfunction
1
result
???
Main Memory while executing MyFunction, but before ++globalVar;
1000
1
x 2
3000
???
globalVar
result
Example1:Scope of Variables
176. www.cyberlabzone.com
int globalVar = 1; /* global variable */
int myFunction(int); /* function prototypes */
void main(void){ /* local variable: result, in main */
int result;
result = myFunction(globalVar); /* call myFunction */
printf(“%d”,result); /* prints “2” */
}
int myFunction(int x){/* Local variables: x, globalVar */
int globalVar; /* new “local” variable */
printf(“%dn”,globalVar);/* prints ??? */
return x + 1;
}
Example2:Scope of Variables
177. www.cyberlabzone.com
int myFunction(int); /* function prototypes */
void main(void){ /* local variables: x,result in main */
int result, x = 2;
result = myFunction(x); /* call myFunction */
printf(“%d”,result); /* prints “3” */
printf(“%d”,x); /* prints “2” WHY??? */
}
int myFunction(int x){/* Local variable: x */
x = x + 1;
printf(“%dn”,x);/* prints “3” */
return x;
}
Example3:Scope of Variables
178. www.cyberlabzone.com
/* C Function to swap values.This doesn’t work!!!! */
#include <stdio.h>
int x; /* x is a global variable */
int y; /* y is a global variable */
void swap(int, int); /* prototype for swap */
void main(void){
x = 1; /* note that x and y are not declared here!!! */
y = 2;
swap(x,y);
printf(“x = %d , y = %d n”,x,y); /* prints x = 1 , y = 2 */
}
void swap(int x , int y){
int temp = x;
x = y;
y = temp;
return;
}
Example4:Scope of Variables
179. www.cyberlabzone.com
A function can be called by any other function, provided that
either the function definition or its prototype is in the same
file as the calling function and precedes the function call.
If no prototype is specified for a function, its header serves as
the function prototype.
Note: Functions cannot be defined within each other
Scope of Function Names
180. www.cyberlabzone.com
- Determines the storage duration and scope of identifiers,
and also linkage between files.
auto - creates storage for variables when the block that
declares them is entered, and deletes the storage when the
block is exited. Local variables have "auto" storage by
default.
e.g.,typing auto float a, b, c; is equivalent to typing float a, b, c;
Storage Classes-auto
181. www.cyberlabzone.com
static - creates and initializes storage for variables when the program
begins execution. Storage continues to exist until execution terminates. If
an initial value is not explicitly stated, a static variable is initialized to 0. We
can retain values of local variables by declaring them to be static.
In the following example, the static variable sum is initialized to 1.
static int sum = 1;
The initialization takes place only once. If the above declaration appears in
a user defined function , the first time the function is called, the variable
sum is initialized to 1. The next time the function (containing the above
declaration) is executed sum is not reset to 1.
Storage Classes-static
182. www.cyberlabzone.com
extern - used to reference identifiers in another file. Function names
are extern by default.
e.g., extern int foreignVar;
Storage Classes-extern
183. www.cyberlabzone.com
1. Problem Definition
Write a function “sum”that keeps a running total of the sum of
every value passed to “sum”. To test this function, modify the
previous program of slide 15 -3 that compute the average of
values in a file.
2. Refine, Generalize, Decompose the problem definition
(i.e., identify sub-problems, I/O, etc.)
Input = integers from file “input.dat”
Output=real number representing the arithmetic average (sum of
values)/(count of number of values)
3. Develop Algorithm
(processing steps to solve problem)
Example-static variable
185. www.cyberlabzone.com
/* C Program to compute the average of a list of numbers. */
#include <stdio.h>
int sum(int); /* function protoype */
void main(void)
{
int value,total,count = 0;
while (EOF != scanf("%i", &value)) { /* read value */
total = sum(value);
++count;
} /* end of while loop */
printf(”Average of the %i numbers = %f n“,count,total/(double)count);
}
int sum(int val){ /* function header */
static int total_val = 0; /* static variable, */
total_val += val;
return total_val;
}
Example-static variable
186. www.cyberlabzone.com
Pointer variables are variables that store memory addresses.
Pointers variables are useful in passing storage addresses in
function calls (call-by-reference) and for applications involving
dynamic data structures (e.g., linked lists)
Example: int *intPtr;
float *floatPtr;
declares intPtr to be a pointer variable to an object of type
integer. and floatPtr to be a pointer variable to an object of
type float.
Pointers
187. www.cyberlabzone.com
We can write the pointer variable declaration
as int* intPtr;
or as int * intPtr;
Note that when we declare more than two pointer
variables in one line each pointer name requires an
asterisk:
int *ptr1, *ptr2;
otherwise we are just declaring a regular variable ,
not a pointer variable.
Pointer Declaration-syntax
188. www.cyberlabzone.com
There are two C operators that are necessary when using
pointer variables.
& - the address operator returns the address of a variable
x
1000
3
ptrX 1000
ptrX holds the address of x.
We say ptrX “points” to x.
We will apply the & operator only to variables, e.g. &77 or &(x+1)
are not valid.
The declaration of ptrX initializes the variable ptrX = &x;
Example:
int x = 3;
int * ptrX = &x;
1004
& Operator
189. www.cyberlabzone.com
Example:
int x;
int * pt;
pt = &x; /* another way to assign an address to a pointer variable */
Suppose the address of the variable x is 9640
Then, the effect of pt = &x; will be:
x pt
Address
9640 9640
& Operator
190. www.cyberlabzone.com
int x;
int * pt;
pt = &x;
To assign the value “3” to the variable x in C:
x = 3;
We can use the “ * ” operator to indirectly reference x.
We can assign “3” to x by:
*pt = 3;
Here we use the fact that “pt” points to integer values.
x pt
Address
9640 96403
* - means "a pointer to" and is called an indirection operator or
dereferencing operator, since a pointer "indirectly" references a
value in a storage location. Example:
*Operator
191. www.cyberlabzone.com
double *ptr;
ptr = NULL;
Assigning a NULL value (zero) to a pointer
A null pointer points to nothing. We often depict it as
ptr
/*called a null pointer*/
Null Pointer
192. www.cyberlabzone.com
1. Problem Definition
Write a function “swap” that has two input integer arguments.
This function should swap the values of the variables.
2. Refine, Generalize, Decompose the problem definition
(i.e., identify sub-problems, I/O, etc.)
Input = two integers
Output= no value is returned to the calling function, but the values
of the called variables should be swapped.
3. Develop Algorithm
Pass the addresses of the variables and not their values. In the
swap function the parameters that hold the addresses are
pointers. Use the indirection operator to swap the values.
Example-call-by-Reference
193. www.cyberlabzone.com
/* C Function to swap values. */
#include <stdio.h>
void swap(int * , int *);
void main(void){ /* function header */
int x = 1;
int y = 2;
swap(&x,&y); /* pass the addresses of x and y */
printf(“x = %d , y = %d n”,x,y); /* prints x = 2 , y = 1 */
}
void swap(int *ptrX , int *ptrY){ /* pointer variables */
int temp = *ptrX;
*ptrX = *ptrY ;
*ptrY = temp;
return;
}
Example-good Swap
194. www.cyberlabzone.com
x
1000
Main Memory before call to swap
1
y
2
Main Memory while executing swap, after temp = *ptrX;
but before *ptrX = *ptrY ;
10001
ptrX 1000 3000
2
x
y 1004
1004
3008
30041004ptrY
temp 1
Example-good Swap
195. www.cyberlabzone.com
x
y
Main Memory while executing swap, after *ptrX = *ptrY ;
but before *ptrY = temp;
10002
ptrX 1000 3000
2 1004
3008
30041004ptrY
temp 1
Example-good Swap
196. www.cyberlabzone.com
x
y
Main Memory while executing swap, after *ptrY = temp;
but before return;
10002
ptrX 1000 3000
1 1004
3008
30041004ptrY
temp 1
Example-good Swap
197. www.cyberlabzone.com
The array name in C is assigned the address of the
first element of the array.
The following code will assign the address of
xArray[0] to xArrayPtr :
float xArray[50];
float * xArrayPtr;
xArrayPtr = xArray;
The assignment statement above is equivalent to:
xArrayPtr = &xArray[0];
Array Names are Constant Pointers
198. www.cyberlabzone.com
A string literal (e.g. “A – your course graden”) is actually
represented in C by a pointer to an address in memory that holds the
first byte of the array of characters.
Therefore the following declaration of the pointer variable “string” is
valid:
char * string = “A – your course graden”;
and to print the value of “string” , use the “%s” conversion specifier,
printf(“%s”,string);
Although a pointer can be used as an array name, we cannot modify
the values of “string” by using the square brackets of array notation.
string[0] = ‘B’; /* error !!! */
The error is due to the fact that the literal “A – your course graden”
is stored in a location in memory that cannot be accessed by
pointers.
String Literal is pointer to an array
199. www.cyberlabzone.com
One use of char * pointers is ragged arrays.
In slide 15-24 we used the following code fragment in the “Morse
Code” example to declare and initialize the array “morse” as :
typedef char string[5];
string morse[26] = {".-", "-...", "-.-.", "-..", ".", "..-.", "--.",
"....", "..", ".---", "-.-", ".-..","--", "-.",
"---", ".--.", "--.-", ".-.", "...", "-", "..-",
"...-", ".--", "-..-", "-.--", "--.." };
An alternative would be the use of a ragged “morse” array declared
as:
typedef char * string;
string morse[26] = {".-", "-...", "-.-.", "-..", ".", "..-.", "--.",
"....", "..", ".---", "-.-", ".-..","--", "-.",
"---", ".--.", "--.-", ".-.", "...", "-", "..-",
"...-", ".--", "-..-", "-.--", "--.." };
String Literal is Pointer to an Array
200. www.cyberlabzone.com
The later declaration of the array “morse” is called ragged since
each element of the array , morse[0], morse[1], … takes up
exactly the number of bytes necessary in memory to hold the
initialized strings whereas in the previous declaration of “morse”
each element of the array takes exactly five character values in
memory no matter what length of the initializing string.
As discussed on slide 15, we cannot change the values of the
ragged “morse” array. But in the “Morse Code” problem we know
that the morse strings should never be changed.
Ragged Arrays
201. www.cyberlabzone.com
To sort means to put in place or rank according to kind, class or nature.
For example, consider a herd of cows. We can sort the cows by weight,
age, amount of milk produced, etc. . The sort can be in ascending or
descending order.
Note that we could not include a lizard in among the sort if we were
sorting with respect to amount of milk produced. That is, the items we
want to sort must have the same nature.
In C we will use arrays to do our sorting. Since the data-type(kind, class
or nature) for each element of the array must be the same we are able to
compare any two elements in the array (no lizards in the array of milk
producing cows).
Why sort?
Sorting
202. www.cyberlabzone.com
One method of sorting is called “selection sort”.
The algorithm: find the smallest element in the list and swap the first item in
the list with the smallest value.
For example, suppose you are given the values(below):
5 3 7 2 4 ( 2 is the smallest value )
step 1
2 3 7 5 4 ( swap 2 with 5, now 3 is the smallest element)
step 2
2 3 7 5 4 ( 3 is in place don’t swap, now 4 is the smallest element)
step 3
2 3 4 5 7 ( swap 4 with 7, now 5 is the smallest element)
step 4
2 3 4 5 7 ( 5 is in place don’t swap, 7 is in place )
203. www.cyberlabzone.com
Another method of sorting is called “insertion sort”.
You use insertion sort when you sort a hand of cards.
For example, suppose you are given the five cards (below):
5 3 7 2 4 (cards in Right hand)
empty (cards in Left hand)
step 1
3 7 2 4 (Right hand)
5 (Left hand)
step 2
7 2 4 ( R )
3 5 ( L )
step 3
2 4 ( R )
3 5 7 ( L )
step 4
4 ( R) )
2 3 5 7 ( L )
step 5
empty ( R )
2 3 4 5 7 ( L ) ( the cards are now sorted )
204. www.cyberlabzone.com
1. Problem Definition
Write a program that sorts the values in an array in ascending
order. Use the built-in function ‘qsort’ to do the work of sorting.
2. Refine, Generalize, Decompose the problem definition
(i.e., identify sub-problems, I/O, etc.)
Input = Array of integers.
Output= Sorted array of integers (ascending order) is printed.
Qsort-Sorting an array
205. www.cyberlabzone.com
#include <stdio.h>
#include <stdlib.h>
int compare(int *ptr1, int *ptr2) {
if ( *ptr1 > *ptr2)
return 1;
else if ( *ptr1 < *ptr2)
return -1;
else
return 0;
}
void main(void) {
int numbers[100];
int k,i=0;
printf(“Enter an array of no more than 100 integers.n”);
while (EOF != scanf(“%d”,&numbers[i]))
++i;
qsort(numbers, i, sizeof(numbers[0]), compare);
for (k=0; k<i; k++)
printf("%d ", numbers[k]);
printf(“n”);
}
207. www.cyberlabzone.com
arrayname - is the name of an existing array. This array
can have any data-type. It can even be an array of
pointers. We will refer to the array’s type as datatype .
elts is the number of elements of array.
qsort(arrayname,elts,size_of_elts,compare_function)
The qsort function is a built-in C function that sorts values
in an array. The algorithm behind qsort is called “Quick
Sort” . In CS101 we are interested only in how to call this
function.
The general format of the qsort function is:
Sorting Example-qsort
208. www.cyberlabzone.com
size_of_elts is the size in bytes of each element in the
array. Use the built-in operator sizeof that returns an
integer value representing the number of bytes a variable
or data-type takes up in RAM.
Example:
sizeof(integer) returns the value 4 on the Lab machines.
sizeof(numbers[0]) returns the number of bytes the variable
numbers[0] takes up in RAM, which is 4 since numbers is
an integer array.
compare_function is the name of the user defined function
that actually does the comparison.
qsort(arrayname,elts,size_of_elts,compare_function)
Sorting Example-qsort
209. www.cyberlabzone.com
The general format of the header for the user defined compare
function is:
int compare_function( datatype * ptr1,datatype * ptr2)
qsort will call the compare_function and pass two pointers ptr1
and ptr2 . Both ptr1 and ptr2 “point” to values in the array
arrayname (see previous slide).
The user must code the function compare_function so that it
returns an integer value back to qsort (the function that called
compare_function) . qsort will use this integer to determine
whether or not to swap the values in the array.
To sort in ascending order the return value is:
0 if the elements *ptr1 and *ptr2 of the array are equal
positive if *ptr1 > *ptr2 (i.e. swap the array values)
negative if *ptr1 < *ptr2 (i.e. don’t swap the array values)
Sorting Example- compare_function
210. www.cyberlabzone.com
Writing the code for compare_function depends on the data-type
datatype and whether the data is sorted in ascending order,
descending order, ... or by some other rule.
Therefore it’s not possible to write one version of
compare_function that does all.
Sorting Example- compare_function
211. www.cyberlabzone.com
The datatype in the sorting example is int . Therefore the
header for the compare_function has the form:
int compare( int * ptr1,int * ptr2)
where ptr1 and ptr2 are pointers to values in the array
numbers . As an example of how qsort works with compare see
the pictures of memory in the following slides.
Sorting Example
212. www.cyberlabzone.com
ptr1 ptr2 numbers[0] numbers[1] numbers[4]
3 4
Address 2000 2004 …
20042000 2 1 5
. . .
Suppose qsort called the compare function and *ptr1 is “3” and
*ptr2 is “4”. The picture above shows this situation. In this
example, we want to tell qsort to sort 3 before 4(don’t swap the
values). To do this, we use *ptr1 and *ptr2 . Since *ptr1 < *ptr2
( 3 < 4) we return a -1 value to qsort. That’s why we have the
code(slide 20):
else if ( *ptr1 < *ptr2)
{
return -1;
Sorting Example
213. www.cyberlabzone.com
ptr1 ptr2 numbers[1] numbers[2] numbers[4]
3 4
Address 2000 2004 2008…
20082004 2 1 5
. . .
Now suppose qsort called the compare function and *ptr1 is “4” and
*ptr2 is “2”. The picture above shows this situation. In this
example, we want to tell qsort to sort 2 before 4( swap the values).
To do this, we use *ptr1 and *ptr2 . Since *ptr1 > *ptr2 ( 4 > 2)
we return +1 value to qsort. That’s why we have the code(slide
20):
if ( *ptr1 > *ptr2)
{
return 1;
}
Sorting Example
214. www.cyberlabzone.com
The previous code works correctly but will generate a warning
message. We can avoid the error messages if we obey the
rules that qsort expects the compare_function to observe.
The code on the next slide will sort the numbers as before but
gcc will not display any warning messages.
In the compare function (on the next slide), note the use of the
void pointer data-type and the use of the cast operators on the
pointer variables.
const int x = 1;
x = 2; /* illegal */
Compiler Warning Messages
215. www.cyberlabzone.com
#include <stdio.h>
#include <stdlib.h>
int compare(const void *ptr1, const void *ptr2) {
if ( *(int *)ptr1 > *(int *)ptr2)
return 1;
else if ( *(int *)ptr1 < *(int *)ptr2)
return -1;
else
return 0;
}
void main(void) {
int numbers[100];
int k,i=0;
printf(“Enter an array of no more than 100 integers.n”);
while (EOF != scanf(“%d”,&numbers[i]))
++i;
qsort(numbers, i, sizeof(numbers[0]), compare);
for (k=0; k<i; k++)
printf("%d ", numbers[k]);
printf(“n”);
}
216. www.cyberlabzone.com
#include <stdio.h>
void main(void){
int z = 3;
float w = 4.0;
void * ptr;
ptr = &z;
/* add one to z */
*(int *)ptr = *(int *)ptr + 1; /* cast ptr */
ptr = &w;
/* add 1.0 to w */
*(float *)ptr = *(float *)ptr + 1.0; /* cast ptr */
printf("z = %i n",z); /* prints 4 */
printf("w = %f n",w); /* prints 5.000 */
}
217. www.cyberlabzone.com
1. Problem Definition
Write a program that creates a new data type named “vector”. A “vector”
represents a 2 dimensional vector v =<x,y> in the plane. The values of v are of
type double. Along with this new data-type, create functions add, sub, and dot
which will add , subtract and take the vector dot product of two vectors.
2. Refine, Generalize, Decompose the problem definition
(i.e., identify sub-problems, I/O, etc.)
We first define a new data type “vector”. Then in main we will declare v1,v2,v3 of
data type “vector”. We will assign values to these vectors and then perform
addition, subtraction and the dot product.
Input = None
Output= The values of v1,v2 will be printed along with the results from add, sub
and dot.
Example-Defining a 2D “vector data type”
218. www.cyberlabzone.com
#include <stdio.h>
#include <stdlib.h>
typedef struct { /* user defined data-type called vector */
double x; /* this is a definition*/
/* no variables are declared */
double y; /* location is outside any block */
} vector;
vector add(vector vec1, vector vec2) ; /* prototype */
vector sub(vector vec1, vector vec2) ; /* prototype */
double dot(vector vec1, vector vec2) ; /* prototype */
/* see explanation of the above in subsequent slides */
void main(void){
vector v1,v2,v3 ={1.0,2.0}; /* three variables of type vector*/
/* v3 initialized to {1.0,2.0} */
v1.x = 2.5; /* use the . to access individual fields */
v1.y = -1.5;
v2 = v3; /* can assign all the values with one statement */
/* continued on next slide */
219. www.cyberlabzone.com
printf(“v1 = [%f,%f]n”,v1.x,v1.y);
printf(“v2 = [%f,%f]n”,v2.x,v2.y);
v3 = add(v1,v2);
printf(“add(v1,v2) = [%f,%f]n”,v3.x,v3.y);
v3 = sub(v1,v2);
printf(“sub(v1,v2) = [%f,%f]n”,v3.x,v3.y);
printf(“dot(v1,v2) = %fn”,dot(v1,v2));
} /* end of main */
vector add(vector vec1, vector vec2){
vector v4 = {vec1.x + vec2.x, vec1.y + vec2.y};
return v4;
} /* end of add */
vector sub(vector vec1, vector vec2){
vector v4 = {vec1.x - vec2.x, vec1.y - vec2.y};
return v4;
} /* end of sub */
double dot(vector vec1, vector vec2){
return (vec1.x * vec2.x) + (vec1.y * vec2.y);
} /* end of dot */
221. www.cyberlabzone.com
To set up a structure in C, we need to
(1) Define a structure type. There are
several ways to do this in C. In general,
we will use the typedef mechanism to
do this.
(2) Declare variables to be of that type.
Note: The built-in data types (e.g. int, float, char,…)
can be used to declare variables in the C language.
These data types don’t have to be defined by the
user.
Structures provide the user with the means to define
custom designed data types.
Structures & Union -How it Works
Structures & Union
222. www.cyberlabzone.com
Structures & Union -How it Works
Union is same as the structure. As the structure contains
members of different data types. In the structure each member
has its own memory location. Whereas members of Unions has
same memory location. we can assign values to only one
member at a time, so assigning value to another member that
time has no meaning. When a union is declared, Compiler
automatically allocates a memory locations to hold the largest
largest data type of members in the Union. Thus the Union is
used for saving memory. The concept of union is useful when it
is not necessary to assign the values to all the members of the
union at a time. Union can be declared as
Union union_name {
member1
member2
………….
…………
} variable_name
223. www.cyberlabzone.com
You can use the typedef mechanism in C to
create an alias for a structure.
The code above names “vector” as a synonym for,
typedef struct {
double x;
double y;
} vector;
struct {
double x;
double y;
};
Structures & Union -How it Works
224. www.cyberlabzone.com
Structure definitions do not reserve storage,
they are used to define a new data type.
For example, the code above doesn’t allocate any
storage. It doesn’t reserve memory for the variables
x or y --- the fields or members of the structure.
Also, no variable of type vector is declared yet.
typedef struct {
double x;
double y;
} vector;
Structures & Union -How it Works
225. www.cyberlabzone.com
Once you have defined a new data type, or a synonym
for this type, you can declare variables of this data
type as in,
The variables v1, v2, and v3 are declared to be of
data type “vector” where “vector” is a synonym for
the structure, struct {
double x;
double y;
};
vector v1,v2,v3 ={1.0,2.0};
Structure variables, like v3 above, are initialized in the
same way you initialize an array.
Structures & Union -How it Works
226. www.cyberlabzone.com
struct Vector_2D v1,v2,v3 ={1.0,2.0};
A second, alternative method in using structures in C
is to code the following immediately after the
preprocessor directives as in slide 4,
struct Vector_2D{
double x;
double y;
};
The name Vector_2D is called a “tag name”.
And in your functions, declare variables by
Structures & Union -How it Works
227. www.cyberlabzone.com
A third, alternative method in using structures in C is
to combine the struct and declaration of the variable
in one statement.
struct Vector_2D{
double x;
double y;
} v1,v2,v3 ={1.0,2.0};
Structures & Union -How it Works
228. www.cyberlabzone.com
We have seen primitive built-in single variable data
types such as int, float, char.
These data types can also be applied uniformly to an
array. All elements of the array have the identical
data type.
Structures provide the mechanism in C for grouping
values of different data types.
Example:
typedef struct {
int employeeID;
float salary;
int departmentID;
char name[30]; /* same as char * name;??? */
} Employee;
Structure can have members of different data-type
229. www.cyberlabzone.com
Accessing(storing and fetching) values from/to
fields in the structure is accomplished with the
"dot operator" (.), also called the "structure
member operator ".
Example: (From slide 4)
v1.x = 2.5; /* use the . to access individual fields */
v1.y = -1.5;
Example: (From the previous slide)
Employee emp1; /* declare a variable of type Employee */
emp1.employeeID = 1004; /* initialize the variable */
emp1.salary = 45123.50;
Structure-Accessing Fields
230. www.cyberlabzone.com
scanf(“%f”,&emp1.salary); /* you can also use scanf */
emp1.departmentID = 37;
strcpy(emp1.name,“John”);/* strcpy function */
scanf(“%s”,emp1.name); /* this is ok, no & needed */
emp1.name[0] = ‘J’; /* this also works */
emp1.name[1] = ‘o’;
emp1.name[2] = ‘h’;
emp1.name[3] = ‘n’;
emp1.name[4] = ‘0’;
Structure-Accessing Fields
231. www.cyberlabzone.com
v3 = add(v1,v2);
vector add(vector vec1, vector vec2){
Function calls with an argument having a structure
data-type are implement as call-by-value. In this
regard structures differ from arrays in that arrays are
passed as call-by-reference.
For example, in slide 5, function add is called
with arguments v1 and v2 of data-type vector.
The header for the function add has two parameters,
vec1 and vec2.
The variables vec1 and vec2 are “local” in scope to
the function add. In call-by-value the values of v1 and
v2 are copied into vec1 and vec2 respectively.
Structure-passed as cal-by-value
232. www.cyberlabzone.com
v3 = add(v1,v2);
Functions can return values of structure data-type.
For example, in slide 5, function add is called
The header for the function add indicates it returns a
value of data-type vector (a structure).
vector add(vector vec1, vector vec2){
vector v4 = {vec1.x + vec2.x, vec1.y + vec2.y};
return v4;
}
Functions can return values of structure data-type
233. www.cyberlabzone.com
1. Problem Definition
Write a program that reads in data for the elements in the periodic system, (e.g.
Hydrogen, Helium,...) the name as a string , symbol as a string, atomic number as
an int and atomic weight as a double. After the elements have been entered they
are sorted using qsort in ascending alphabetical order and then printed back to
the terminal.
2. Refine, Generalize, Decompose the problem definition
(i.e., identify sub-problems, I/O, etc.)
We have four values per atomic element:
name,symbol,atomicNum and atomicWt
Rather than using five separate arrays of 102 elements we will
use one array AtomicElement of 102 elements. The data-type of
AtomicElement is a user-defined structure named Element.
Input = Input data from keyboard as above.
Output= Sort the elements by atomic name, using qsort.
Structure-Accessing Fields
Example-Sort an array of structures
234. www.cyberlabzone.com
#include <stdio.h>
#include <stdlib.h>
typedef struct { /* user defined data-type called Element */
char name[15]; /* this is a definition, no variables are declared */
char symbol[3];/* location of this definition is outside any block */
int atomicNum;
double atomicWt;
} Element;
int cmpnames(Element * ptr1, Element * ptr2) ; /* prototype */
/* see explanation of the above in subsequent slides */
void main(void){
int num, i;
Element AtomicElement[102]; /* AtomicElement is an array */
printf(“How many elements are you going to enter?”);
scanf(“%d”,&num);
for(i=0;i<num;++i){
scanf(“%s”,AtomicElement[i].name);
scanf(“%s”,AtomicElement[i].symbol);
scanf(“%d”,&AtomicElement[i].atomicNum);
scanf(“%lf”,&AtomicElement[i].atomicWt);
}
235. www.cyberlabzone.com
/* sort the arrays by name */
qsort(AtomicElement, num, sizeof(AtomicElement[0]), cmpnames);
/* print the sorted array */
printf(“n”);
for (i=0;i<num;++i){
printf(“%s ”,AtomicElement[i].name);
printf(“%s ”,AtomicElement[i].symbol);
printf(“%d ”,AtomicElement[i].atomicNum);
printf(“%.5lf ”,AtomicElement[i].atomicWt);
printf(“n”); /* print one element per line */
} /* end of for */
} /* end of main */
int cmpnames(Element * ptr1, Element * ptr2) {
return strcmp(ptr1->name, ptr2->name); /* why arrow and not dot??? */
} /* end of cmpnames */
236. www.cyberlabzone.com
> a.out
How many elements are you going to enter?4
Hydrogen H 1 1.00794
Beryllium Be 4 9.01218
Gold Au 79 196.96655
Carbon C 6 12.0107
Beryllium Be 4 9.01218
Carbon C 6 12.01070
Gold Au 79 196.96655
Hydrogen H 1 1.00794
input
output
Example-Execution
237. www.cyberlabzone.com
strcmp(ptr1->name, ptr2->name)
If the string ptr1->name < ptr2->name (alphabetically)
then strcmp(ptr1->name, ptr2->name) has a negative value
else if ptr1->name > ptr2->name
then strcmp(ptr1->name, ptr2->name) has a positive value
else if ptr1->name == ptr2->name
then strcmp(ptr1->name, ptr2->name) has the value 0.
These are the correct values we want to return to qsort and
we do this by
From Lecture 15 slide 21:
strcmp(str1, str2) - returns a negative , zero or positive int
depending on whether str1 is alphabetically
less than, equal or greater than str2 respectively.
qsort calls our function cmpnames and passes two addresses
which are assigned to the pointer variables, ptr1 and ptr2.
return strcmp(ptr1->name, ptr2->name);
Strcmp
239. www.cyberlabzone.com
Address 2030
prt1 ptr2 AtomicElement[0]
“Hydrogen”
Address 2000
20302000
“H” 1
9.01218“Beryllium” “Be” 4
1.00794
AtomicElement[1]
After qsort calls ‘cmpnames’
Since ‘cmpnames’ function returns a positive value to the
function ‘qsort’. The function ‘qsort’ does the work of
swapping the 30 bytes of AtomicElement[0] with
the 30 bytes of AtomicElement[1].
Sorting Example
240. www.cyberlabzone.com
We can declare an array of the struct data
type Autopart.
AutoPart structArray[50];
declares structArray as an array which contains
50 cells (in memory) of type AutoPart.
typedef struct {
int id;
char name[30];
} AutoPart;
Given the data-type definition:
Arrays of Structure data-type
241. www.cyberlabzone.com
We can access the field in the structure with pointers
and arrow operator “ -> ” (also called the indirect
component selection operator ). The general format of
the use of the arrow operator is:
(see example on next slide)
pointer_to_structure -> member_name
Pointer to variables of structure data-type
242. www.cyberlabzone.com
typedef struct {
int employeeID;
float salary;
int departmentID;
char name[30];
} Employee;
Employee emp1;
Employee *empPtr; /* pointer to data-type Employee */
emp1.employeeID = 1004;
emp1.salary = 45123.50;
emp1.departmentID = 37;
empPtr = &emp1; /* empPtr now points to emp1 */
printf(“emplayeeID is %d in department %d n”,
empPtr->employeeID, empPtr->departmentID);
Pointer to variables of structure data-type
243. www.cyberlabzone.com
Rather than use the arrow operator we could use “ * ” the
dereferencing operator.
From the last example:
printf(“emplayeeID is %d in department %d n”,
(*empPtr).employeeID, (*empPtr).departmentID);
However, do not write:
printf(“emplayeeID is %d in department %d n”,
*empPtr.employeeID, *empPtr.departmentID);
because in C this means (see operator precedence rules)
printf(“emplayeeID is %d in department %d n”,
*(empPtr.employeeID), *(empPtr.departmentID));
and these expressions are not equivalent. Why?
Therefore, it may be “safer” to use the arrow operator, so
that we don’t make the mistake shown above.
Why use the arrow “”?
244. www.cyberlabzone.com
So far, we have seen that one way to manipulate
files in a program is to redirect the standard input
and output.
E.g. in UNIX command line
a.out < input.dat > output.dat
We redirect standard input as the file, input.dat (not a
keyboard) And standard output as the file, output.dat(not
screen) This method works for one input file and one
output file.
In this lecture we will consider an alternative,
using FILE pointers.
File Input/Output (I/O)
File Operation in C
245. www.cyberlabzone.com
1. Problem Definition
Write a program that computes the average of a list of integers.
The program should prompt the user for the name of both the
input and output files and then read the values from the input file
and print the average value in the output file.
2. Refine, Generalize, Decompose the problem definition
(i.e., identify sub-problems, I/O, etc.)
Input = String naming the file of integers to be read and a string
naming the output file. Also, the integers in the file.
Output = The average value is written to the output file.
Example-Compute the Average value of a File of Integers
246. www.cyberlabzone.com
/* C Program to compute the average of a list of numbers. */
#include <stdio.h>
void main(void) {
int value,total = 0,count = 0;
/* fileptrIn and fileptrOut are variables of type “FILE *” */
FILE * fileptrIn, * fileptrOut;
char filenameIn[100],filenameOut[100];
printf(“Please enter an input filename (use path if needed):”);
scanf(“%s”,filenameIn);
printf(“Please enter an output filename (use path if
needed):”);
scanf(“%s”,filenameOut);
/* open files to read “r” and write “w” */
fileptrIn = fopen(filenameIn,”r”);
fileptrOut = fopen(filenameOut,”w”);
/* check to see if program found file */
if ((fileptrIn == NULL) || (fileptrOut == NULL))
{ printf(“file not opened, program terminated.n”);
return;
}
Example-Computing the Average value
247. www.cyberlabzone.com
/* fscanf */
while( EOF != fscanf(fileptrIn,"%i", &value)){
total += value;
++count;
} /* end of while loop */
/* Write the average value to the file. fprintf */
fprintf(fileptrOut,”Ave of %i numbers = %f n“
,count,total/(double)count);
fclose(fileptrIn);
fclose(fileptrOut);
}
248. www.cyberlabzone.com
/* fscanf */
while( EOF != fscanf(fileptrIn,"%i", &value)){
total += value;
++count;
} /* end of while loop */
/* Write the average value to the file. fprintf */
fprintf(fileptrOut,”Ave of %i numbers = %f n“
,count,total/(double)count);
fclose(fileptrIn);
fclose(fileptrOut);
}
Example-Compute the Average value of a File of Integers
249. www.cyberlabzone.com
After the above program is compiled execution from the
Unix prompt:
> more input.dat
1
2
3
4
5
> ./a.out
Please enter an input filename (use path if needed):input.dat
Please enter an output filename (use path if needed):output.dat
> more output.dat
Ave of 5 numbers = 3.000000
>
Execution-How it Works
250. www.cyberlabzone.com
FILE (all caps) is a structure defined in <stdio.h>.
In CS101 we will only use this data type in the
declaration of pointer variables.
Examples:
FILE *ptrFileIn;
FILE *ptrFileOut;
declares ptrFileIn and ptrFileOut as pointer
variables. They both “point” to values of data-type
FILE. We must have #include <stdio.h> in our
source file to use FILE pointers.
File-data-type
251. www.cyberlabzone.com
fprintf function is in <stdio.h>. It is the
same as the printf function except that the
first argument for fprintf is a file pointer:
fprintf(ptrFileOut, ctrlString, expression(s));
where ctrlString contains the format
specifiers, and expression(s) can contain
one or more variable names and constants.
Examples:
fprintf(ptrFileOut, "%d ", intVlaue);
fprintf(ptrFileOut, "%f ", a + 5.0 * b);
fprintf
252. www.cyberlabzone.com
fscanf function is also in <stdio.h>. It is the
same as the scanf function except that the
first argument for fscanf is a file pointer; i.e.,
fscanf(ptrFileIn, ctrlString,address(es));
Examples -
fscanf(ptrFileIn, "%lf", &dataValue);
fscanf(ptrFileIn, "%c%s%d", &ch, str, &num);
- returns an int value equal to number of items
successfully read from file (e.g., 0, 1, 2, 3 in last
example), or returns the value of EOF if end of file is
encountered before any values are read in. Thus,
fscanf can be used as an input check just like scanf.
fscanf
253. www.cyberlabzone.com
To use fscanf and fprintf you must first open a file, we
use the library function fopen (defined in <stdio.h>.)
For example, to open the file input.dat for reading, we
write
FILE *fileIn;
fileIn = fopen(“infile.dat”, “r”);
The first argument “infile.dat” is a string that names the
file to be read. The second argument the mode, “ r ”,
stands for “reading” mode only. If the file cannot be
opened, fopen returns NULL. (e.g. file doesn’t exit)
fopen returns a pointer to the file(in this case infile.dat).
The file pointer is the handle to the file, once the file is
opened with fopen a programmer can manipulate the file
with this pointer.
fopen
254. www.cyberlabzone.com
FILE *fileOut;
fileOut = fopen(“output.dat”, “w”);
The first argument “output.dat” is a string that names the
file to be read. The second argument the mode, “ w ”,
stands for “write” mode only.
fopen returns a pointer to the file(in this case (output.dat).
Example:
If an already existing file is opened with mode “w” the
old contents are discarded.
fopen
255. www.cyberlabzone.com
FILE *fileOut;
fileOut = fopen(“out.dat”, “a”);
The first argument “out.dat” is a string that names the
file the you to which you want to write .
The writing takes place at the end of the original file.
If the file out.dat already exists it will not be destroyed as
in the case for “w” mode.
fopen returns a pointer to the file(in this case (out.dat).
Example:
fopen
256. www.cyberlabzone.com
When we open a file such as infile.dat we
need to specify in advance whether we want to
read from the file, write to the file, append to
the file. A file can be opened in one mode,
closed and then reopened in another mode.
Mode If the file exists If the file
doesn’t exist
“r” Opens the file for reading Error
“w” Opens a new file for writing Create a new
file
“a” Opens a file for appending
(writing at the end of the file)
Create a new
file
Fopen-mode
257. www.cyberlabzone.com
To close a file that is opened, you must use
fclose. The function expects one argument,
a pointer to FILE. The function fclose
returns zero if it successfully closes the file
and EOF otherwise.(e.g file doesn’t exist)
FILE *fileIn;
fileIn = fopen(“infile.dat”, “r”)
…
fclose(fileIn);
When a program terminates, all open files are
automatically closed.
fclose
258. www.cyberlabzone.com
1. Problem Definition Write a program that reads a list of real
numbers into an array from the keyboard (or a file using Unix
redirection). The array can be of arbitrary length but the user
must first specify the length of the array. The program then
calculates the average value, and then prints a list of
differences. The differences are computed by taking the original
values in the list minus the average.
2. Refine, Generalize, Decompose the problem definition (i.e.,
identify sub-problems, I/O, etc.)
Input = Since the length of the array is specified at run-time we must
use Dynamic Memory Allocation. This is accomplished in C by
the use of the built-in function calloc (or malloc). Use data-type
double to hold the values.
Output= The average and the list of differences.
Example-DMA example
259. www.cyberlabzone.com
#include <stdio.h>
#include <stdlib.h>
void main(void){
int k,num;
double * datValptr; /* pointer used in DMA */
double datAve;
double sum = 0.0;
/* prompt the user for the number of array elements */
printf(“Please enter the number of array elements:”);
scanf(“%d”,&num);
/* use calloc to allocate a block of memory */
datValptr = calloc(num,sizeof(double));
/* verify that calloc was successful */
if (datValptr = = NULL){
printf(“Memory not allocated!n”);
return;
}
(continued on next slide)
260. www.cyberlabzone.com
/* read the values and compute the average */
k = 0;
for(k=0;k<num;++k){
scanf("%lf", &datValptr[k]);/* use pointer as array name */
sum += datValptr[k];
}
/* compute the average */
datAve = sum /num;
printf(“The average is:%f n", datAve);
/* compute and print the diff list */
for(k=0;k<num;++k){
printf(“%fn", datValptr[k]-datAve);
} /* end of for*/
/* free up any memory that was dynamically allocated */
free(datValptr);
} /* end of main */
262. www.cyberlabzone.com
In C, we can dynamically allocate storage with either of
the following two functions (both are in <stdlib.h>).
• malloc(numberOfBytes)
• calloc(numberOfItems, itemSize)
Both functions return a pointer to the address of the block
of storage that has been allocated. If no memory is
available, a NULL value will be returned.
Function calloc returns a contiguous block of
locations that are initialized to 0 and that can be
referenced as array locations, using pointer operations.
Calloc and malloc
263. www.cyberlabzone.com
In both cases above (calloc or malloc) return memory
locations to the system ("memory manager") with:
free (ptr);
Example: Declare ptr as a pointer variable to data-
type double and use dynamic memory allocation
(calloc or malloc) to allocate 100 elements of data-
type double.
double * ptr;
ptr = calloc(100,sizeof(double));
or
ptr = malloc(100*sizeof(double));
free
264. www.cyberlabzone.com
Lecture 19 slide 8 mentioned that array names
are constant pointers. Conversely, pointer variables
can be used as array names.
Example:
int x[5] ={2,4,6,8,10};
int * ptr;
ptr = x; /* or ptr = &x[0] , that is ptr points to x-array*/
ptr[0] = 3; /* is the same as x[0] = 3 */
printf(“%d”,ptr[1]); /* prints 4 */
Pointer Variables can be Used as Array Names
265. www.cyberlabzone.com
1. Problem Definition
Read a file “input.dat” that has employee data(“records”). Read
the records into an array (using dynamic memory allocation) of
data-type Employee (defined below) and then sort the employee
data alphabetically by name. Write the sorted data to the file
“output.dat”.
2. Refine, Generalize, Decompose the problem definition
(i.e., identify sub-problems, I/O, etc.)
Input = Use the structure
typedef struct {
int employeeID;
float salary;
int departmentID;
char fname[30];
char lname[30];
} Employee;
Output= The employee records in alphabetic order.
Example-Sorting Employee Records
266. www.cyberlabzone.com
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int employeeID;
float salary;
int departmentID;
char fname[30];
char lname[30];
} Employee;
int cmpnames(Employee *ptr1,Employee *ptr2) /* prototype */
void main(void){
FILE * fileptrIn;
FILE * fileptrOut;
int i, num;
char filenameIn[100];
char filenameOut[100];
Employee * ptr; /* ptr is a pointer variable */
Employee temp;
(continued on next slide)
267. www.cyberlabzone.com
/* prompt user and get the name of employee input */
/* and output file */
printf("Enter the file name that contains the records. n");
scanf("%s",filenameIn);
printf("Enter the output file name. n");
scanf("%s",filenameOut);
/* open file for reading */
fileptrIn = fopen(filenameIn,”r”);
/*open file for writing */
fileptrOut = fopen(filenameOut,”w”);
/* verify that files were successfully opened */
if (fileptrIn == NULL){
printf(“Input file not found.n”);
return; /* terminate program */
}
if (fileptrOut == NULL){
printf(“Output file not opened.n”);
return; /* terminate program */
}
(continued on next slide)
268. www.cyberlabzone.com
/* find the number of Employee records by reading the */
/* input file. Then reset the file to read from the */
/* beginning of the file again. */
num = 0;
while (
(EOF !=fscanf(fileptrIn,"%d",&temp.employeeID))&&
(EOF !=fscanf(fileptrIn,"%f",&temp.salary))&&
(EOF !=fscanf(fileptrIn,"%d",&temp.departmentID))&&
(EOF !=fscanf(fileptrIn,"%s",temp.fname))&&
(EOF !=fscanf(fileptrIn,”%s”,temp.lname)))
++num;
rewind(fileptrIn);
/* calloc is a built-in C function that performs DMA*/
ptr = calloc(num,sizeof(Employee));
(continued on next slide)
269. www.cyberlabzone.com
/* read the records into the area in memory pointed to */
/* by ptr. See the previous statement ptr = calloc(… */
/* Use ptr as the “name” of an array */
for(i = 0;i<num;++i){
fscanf(fileptrIn,"%d",&ptr[i].employeeID);
fscanf(fileptrIn,"%f",&ptr[i].salary);
fscanf(fileptrIn,"%d",&ptr[i].departmentID);
fscanf(fileptrIn,"%s",ptr[i].fname);
fscanf(fileptrIn,"%s",ptr[i].lname);
}
/* use qsort to sort the records by employee name */
qsort(ptr,num,sizeof(Employee),cmpnames);
/* write the records to the output file */
/* note the space after the conversion specifiers */
for(i = 0;i<num;++i){
fprintf(fileptrOut,"%d ",ptr[i].employeeID);
fprintf(fileptrOut,"%.2f ",ptr[i].salary);
fprintf(fileptrOut,"%d ",ptr[i].departmentID);
fprintf(fileptrOut,"%s ",ptr[i].fname);
fprintf(fileptrOut,"%sn",ptr[i].lname);
}
(continued on next slide)
270. www.cyberlabzone.com
/* free up dynamic memory */
free(ptr);
/* close all files before you terminate the program */
fclose(fileptrIn);
fclose(fileptrOut);
} /* end of main */
/* cmpnames is called by qsort */
int cmpnames(Employee *ptr1,Employee *ptr2){
return strcmp(ptr1->lname, ptr2->lname);
}
How would you modify the cmpnames function above to sort
the array by if the last names were the same?
How would you modify the compare function to sort by
employeeID, or by departmentID, or by salary ?
271. www.cyberlabzone.com
Given that the input file “input.dat” has the following
data:
12345 34500.00 24 Brad Pitt
12346 28888.00 23 Jennifer Aniston
12347 47595.00 24 Britney Spears
12348 55675.00 23 Jim Carey
The program described in the previous slides
produces the output shown on the next slide.
Example-Execution
272. www.cyberlabzone.com
dclsn75> ./a.out
Enter the file name that contains the records.
input.dat
Enter the file name that contains the records.
output.dat
dclsn75> more output.dat
12346 28888.00 23 Jennifer Aniston
12348 55675.00 23 Jim Carey
12345 34500.00 24 Brad Pitt
12347 47595.00 24 Britney Spears
dclsn75>
Example-Execution
273. www.cyberlabzone.com
fclose(fileptrIn);
fileptrIn = fopen(filenameIn,”r”);
In slide 13 we used the built-in C function rewind. To
illustrate the meaning of rewind, consider the
following example: If the data was written on a
magnetic tape, then the rewind command causes
the tape to be rewound back to the beginning of the
tape. So the next read command would begin
reading from the beginning of the file.
In the program in slides 10-15 we could replace
the code:
rewind(fileptrIn);
by the following code:
Rewind
274. www.cyberlabzone.com
C has the special feature of preprocessor directive which makes it
different from other languages (which hasn’t this type of facility). C
preprocessor provides the facility to programmers to make program
more efficient (for Understanding and modification of program). The
preprocessor processes the C source code before it passes to the
compiler preprocessor directives are executed before the C source code
passes through the compiler. The preprocessor directives usually
written at the beginning of the C program. These directives are
preceded with the # symbol and there is no semicolon at the end. This is
not necessary to write the preprocessor directives at the beginning of
the program, These can be written anywhere in the program but they
are generally written before main function or other functions. The
preprocessor directives are as given below:-
# define, #ifdef, #ifndef, #else, #elif,#if
#error, #endif, #undef, #line, #pragma
Stringizing operator #
Token pasting operator ##
The C Preprocessor
275. www.cyberlabzone.com
Recursive functions are defined in terms of
themselves; i.e., a function is recursive if it
contains calls back to itself or to another function
that calls the original function. Recursive
programming usually requires more memory and
runs more slowly than non-recursive programs.
This is due to the cost of implementing the “stack”.
However, recursion is often a natural way to
define a problem.
Recursive Functions
276. www.cyberlabzone.com
1. Problem Definition
Write a factorial function. 0! = 1 and n! = n*(n-1)!.
Use “recursion” to implement the factorial function.
2. Refine, Generalize, Decompose the problem definition
(i.e., identify sub-problems, I/O, etc.)
Input = Non-negative integers as input.
Output= return the factorial of the input value.
Note: that 69! = 1.711224524... x 1098
so our function will only work for small integer
values. It would be better to return a
value of data-type double (Why?)
Example-Factorial function
277. www.cyberlabzone.com
double fact(int n)
{
if (n = =0 || n = =1)
return 1.0;
else
return (n * fact(n - 1)); /* recursive call */
}
In main we can call the factorial function by the following
command:
printf(“%lf”, fact(6));
or by (if x is of data-type int and y is of data-type double) :
x = 5;
y = fact(x);
Example-(Recursive) Factorial function
278. www.cyberlabzone.com
double fact(int n)
{
if (n = =0 || n = =1)
return 1.0;
else
return (n * fact(n - 1)); /* recursive call */
}
When we call the factorial function with fact(2) we “stop” executing the
factorial function at the line:
return ( 2 * fact(1)); (n = 2) (values are substituted for the variables).
We cannot return a value because we must first compute fact(1), so this
statement is put on hold or “pushed on the stack” until fact(1) is computed. A
second call to factorial function is made, i.e. fact(1) and we execute,
(continued on the next slide)
Example-How it Works
279. www.cyberlabzone.com
and since n = = 1 is true then the following executes:
return 1.0; (n = 1)
But to where does the value 1.0 return ? From where fact was last called ,
the fact function(see previous slide). So when this call to fact terminates
(at return 1.0;) the statement
return ( 2 * fact(1)); (n = 2)
is “popped” from the stack and fact(1) gets the value 1.0, that is, we can
now execute this statement which (effectively) says
return ( 2 * 1.0);
double fact(int n) (n = 1)
{
if (n = =0 || n = =1)
return 1.0;
else
return (n * fact(n - 1)); /* recursive call */
}
Example-How it Works
280. www.cyberlabzone.com
Note the contents of the “stack” when we execute a call fact(3) from main.:
(push) return ( 3 * fact(2)); (n = 3)
(push) return ( 2 * fact(1)); (n = 2)
return 1.0; (n = 1)
(pop) return ( 2 * 1.0); (n = 2)
(pop) return ( 3 * 2.0); (n = 3)
return ( 3 * fact(2)); (n = 3)
return ( 2 * fact(1)); (n = 2)
return ( 3 * fact(2)); (n = 3)
(STACK)
The “stack” contains “stack frames” see FER 21.2.1.
Example-fact(3)
281. www.cyberlabzone.com
1. Problem Definition
Write a solve_maze function. Read the maze from a file, “maze.txt”
and display one path that traverses the maze. Use “recursion” to
implement the maze function.
2. Refine, Generalize, Decompose the problem definition
(i.e., identify sub-problems, I/O, etc.)
Input = The file “maze.txt” contains the following
**********
* *
**** * *O*
* * ***
* * *X*
* ** *** *
* * *
* *** ** *
* * *
**********
Your program will have to find its way through a
10x10 maze where the symbols “ * ” , “O” and “X”
denote:
“ * ” are solid walls through which you cannot travel
"O" denotes the starting position,
"X" is the exit for which you are looking for
Example-Traversing a Maze
283. www.cyberlabzone.com
2. Refine, Generalize, Decompose the problem definition
Input (continued): Read the maze into the 2D array,
**********
* *
**** * *O*
* * ***
* * *X*
* ** *** *
* * *
* *** ** *
* * *
**********
char maze[NUMROWS][NUMCOLS];
where NUMROWS and NUMCOLS are
constants with value 10. The upper left-hand
corner of the maze has the value maze[0][0] .
If we want to test whether the cell in the
fourth row and fourth column contains
a wall then it's enough to use an
if statement like this:
if (maze[3][3] == ‘ * ')
Example-Traversing a Maze
284. www.cyberlabzone.com
2. Refine, Generalize, Decompose the problem definition
Output : Display a solution as follows:
**********
* OOOOO*
****O* *O*
* *O* ***
* *O* *X*
* **O***O*
* OO *O*
* ***O**O*
* * OOOO*
**********
Example-Traversing a Maze
285. www.cyberlabzone.com
3. Develop Algorithm
(processing steps to solve problem)
Step 1 Read in the “maze” and find the starting Row and Column (the
position of the “O”).
Use variables “curRow” and “curCol” to keep track of the current position
as we traverse through the maze (the 2D matrix “maze”).
Step 2 Display the maze.
Step 3 Check to see if current position is an “X” then we are done.
Otherwise first try to go up and if not then down and if not then left and
if not then right and if you can go up/down/left/right then go back to
Step 2. Otherwise, go back to the previous position [curRow,curCol] and
try another direction.
Example-Traversing a Maze
290. www.cyberlabzone.com
/* Display the maze passed as a parameter to standard output. */
void display_maze (char maze[ ][NUMCOLS])
{
int i, row, col;
for (row = 0; row < NUMROWS; row++)
{
for (col = 0; col < NUMCOLS; col++)
{
printf ("%c", maze[row][col]);
}
printf ("n");
}
usleep (600000);
printf ("n");
}
291. www.cyberlabzone.com
int read_maze (char maze[ ][NUMCOLS], int *sRow, int *sCol){
FILE *fpMaze;
int row, col;
char endofline; /* end of line character */
/* Open maze text file, make sure it opens OK. */
if ((fpMaze = fopen ("maze.txt", "r")) == NULL)
return 0;
for (row = 0; row < NUMROWS; row++){ /* Loop through the rows. */
for(col=0;col<NUMCOLS;++col){/* Loop through columns */
fscanf(fpMaze,"%c",&maze[row][col]);
if (maze[row][col] == 'O') { /*Check if this is the starting
position.*/
*sRow = row;
*sCol = col;
}
} /* end of for(col=... loop */
fscanf(fpMaze,"%c",&endofline);
} /* end of for(row=... loop */
fclose(fpMaze);
return 1;
}
292. www.cyberlabzone.com
According to legend, in the great temple of Benares, beneath
the dome which marks the center of the world, rests a brass
plate on which are fixed three diamond needles. On one of
these needles at creation, there were placed 64 discs of pure
gold, the largest disc resting on the brass plate and the others
getting smaller up to the top one. This is the TOWERS OF
HANOI. Day and night, the people on duty move the discs from
one needle to another, according to the two following laws:
Law 1: Only one disc at a time may be moved.
Law 2: A larger disc may never rest on a smaller disc.
The workers labor in the belief that once the tower has been
transferred to another needle there will be heaven on earth, so
they want to complete the task in the least number of moves.
Towers of Hanoi
293. www.cyberlabzone.com
Actually, the Tower of Hanoi puzzle was invented in 1883 by
the French mathematician Edouard Lucas (1842-1891), who
made up the legend to accompany it.
Towers of Hanoi
294. www.cyberlabzone.com
An elegant and efficient way to solve this problem is
to think recursively.
Suppose that you, somehow or other, have found the
most efficient way possible to transfer a tower of n-1
disks one by one from one pole to another obeying
the restriction that you never place a larger disk on
top of a smaller one. Then, what is the most efficient
way to move a tower of n disks from one pole to
another?
Towers of Hanoi
295. www.cyberlabzone.com
Assume we know how to move n-1 disks from one peg to
another.Then can we move n disks from peg 1 to peg 3 ?
1. Move n-1 disks from peg 1 to peg 2, peg 3 is just a
temporary holding area
2. Move the last disk(the largest) from peg 1 to peg 3
3. Move the n-1 disks from peg 2 to peg 3, peg 1 is just a
temporary holding area.
1 2 3
n disks
Pseudo-code
297. www.cyberlabzone.com
/* function prototype*/
void hanoi( int origin, int dest, int spare, int how_many);
void main(void){
int how_many;
printf(“ntHow many disks initially on peg1?”);
scanf(“%d”, &how_many);
hanoi(1, 3, 2, how_many);
}
Example-Towers of Hanoi
298. www.cyberlabzone.com
void hanoi( int origin, int dest, int spare, int how_many){
int new_origin, new_dest, new_spare;
if(how_many == 1){
printf(“nntMove top disk from peg %d to peg %d.”, origin, dest);
return;
}
new_origin = origin;
new_dest = spare;
new_spare = dest;
hanoi(new_origin, new_dest, new_spare, how_many - 1);
printf(“nnt Move top disk from peg %d, to peg %d.”, origin, dest);
new_origin = spare;
new_dest = dest;
new_spare = origin;
hanoi(new_origin, new_dest, new_spare, how_many - 1) ;
}
Example-Towers of Hanoi
299. www.cyberlabzone.com
Going back to the legend, suppose the priests work
rapidly and move one disk every second. As shown earlier,
the minimum sequence of moves must be :
The minimum
number of moves
needed to transfer
a tower of n disks
from peg1 to peg3
The minimum
number of moves
needed to transfer
n-1 disks from
peg1 to peg2
The minimum
number of moves
needed to transfer
the n th disk from
peg1 to peg3
The minimum
number of moves
needed to transfer
n-1 disks from peg2
to peg3 on top of
the n th disk
Therefore, the recurrence relation is moves(n) = 2*moves(n-1) + 1 and
initial case is moves(1) = 1 second.
For example, moves(2) = 2*moves(1) + 1 = 3,
moves(3) = 2*moves(2) + 1 = 7,
moves(4) = 2*moves(3) + 1 = 15.
Then, the time to move all 64 disks from one peg to the other, and end
the universe would be moves(64) seconds or 584.5 billion years!!
= + +
Computational Complexity