The document discusses functions in C programming. It provides examples of functions that return values, functions that accept arguments, and functions that call other functions. It also discusses concepts like scope of variables, passing arguments by value, and returning values from functions. Functions are defined as blocks of code that perform a specific task and can be reused. The examples demonstrate how to write functions and call them from other parts of the code.
The document discusses automatic versus static variables in C programming. It provides examples of functions with automatic and static variables. Automatic variables are reinitialized each time the function is called, while static variables retain their value between calls. The document also discusses recursion, providing examples of recursive functions to calculate factorials and generate the Fibonacci series. Recursion involves functions calling themselves until a base case is reached.
The document provides instructions for solving a system of linear equations using Gaussian elimination and the Regula Falsi method. It includes sample code to implement (1) Gaussian elimination to solve the system of equations x+2y=10, 2x+y+z=9, 5x+3y+2z=23 and (2) the Regula Falsi method to find a root of the equation x^2 - 8x + 15 = 0.
I am telling about basic c such as variable,constant,operators,decison making,loops,switch,break and continue,function,call by value ,call by reference and recursion.In this pdf i give some practice problems too.
This document contains some programs of C using Data structures, like Stack, LinkedList, queue, Fibonacci series, addition and multiplication of two matrices,etc.
A pointer is a variable that stores the address of another variable. Pointers allow variables to reference memory locations and access the values stored there. An array is a collection of variables of the same type stored contiguously in memory. Strings in C are arrays of characters terminated by a null character. Pointers can also be used to point to strings by storing the base address of the character array. Multidimensional arrays and manipulating strings are also discussed.
The document describes exercises on structures and strings in C programming. It defines a structure called _PLAYER to store details of players like name, date of birth, height and weight. It then shows how to define the structure, read and print records of multiple players from an array of _PLAYER structures. Functions are defined to find the tallest player, print names in descending order of height, check character cases, convert case of characters in a string, and compute operations on structures like distance between points.
The document discusses automatic versus static variables in C programming. It provides examples of functions with automatic and static variables. Automatic variables are reinitialized each time the function is called, while static variables retain their value between calls. The document also discusses recursion, providing examples of recursive functions to calculate factorials and generate the Fibonacci series. Recursion involves functions calling themselves until a base case is reached.
The document provides instructions for solving a system of linear equations using Gaussian elimination and the Regula Falsi method. It includes sample code to implement (1) Gaussian elimination to solve the system of equations x+2y=10, 2x+y+z=9, 5x+3y+2z=23 and (2) the Regula Falsi method to find a root of the equation x^2 - 8x + 15 = 0.
I am telling about basic c such as variable,constant,operators,decison making,loops,switch,break and continue,function,call by value ,call by reference and recursion.In this pdf i give some practice problems too.
This document contains some programs of C using Data structures, like Stack, LinkedList, queue, Fibonacci series, addition and multiplication of two matrices,etc.
A pointer is a variable that stores the address of another variable. Pointers allow variables to reference memory locations and access the values stored there. An array is a collection of variables of the same type stored contiguously in memory. Strings in C are arrays of characters terminated by a null character. Pointers can also be used to point to strings by storing the base address of the character array. Multidimensional arrays and manipulating strings are also discussed.
The document describes exercises on structures and strings in C programming. It defines a structure called _PLAYER to store details of players like name, date of birth, height and weight. It then shows how to define the structure, read and print records of multiple players from an array of _PLAYER structures. Functions are defined to find the tallest player, print names in descending order of height, check character cases, convert case of characters in a string, and compute operations on structures like distance between points.
C programming uses basic elements like expressions, statements, blocks and functions. Expressions combine constants, variables and operators, while statements end with semicolons. A block of statements is treated as a single statement. Standard library functions include printf(), exit() and scanf(). Control structures like if-else, switch, for, while and do-while statements are used for decision making and looping.
The document contains code snippets for several C programs including:
1) A program to add complex numbers by defining a structure for complex numbers and taking user input for real and imaginary parts of two numbers and printing their sum.
2) A binary search algorithm implementation to search a sorted array for a key and return its index.
3) A bubble sort algorithm implementation to sort an array of long integers in ascending order by swapping adjacent elements.
The document contains C code for multiple programs that perform various calculations and operations on arrays and numbers. The programs include:
1. Evaluating mathematical expressions by taking input values, performing calculations defined by the expressions, and outputting results.
2. Performing logical operations and comparisons on input values to determine output values based on if/else or switch statements.
3. Calculating factorials, digit sums, reversing numbers, checking for palindromes, and other numeric operations using loops.
4. Generating patterns and diagrams by iterating with for loops.
5. Performing array operations like reversing elements, calculating sums, and swapping arrays.
The document contains 11 questions related to string manipulation and function problems in C programming. For each question, it provides the full source code of a C program that implements the given task. The questions cover topics such as reading and manipulating strings, calculating lengths, reversing strings, copying strings, comparing strings, counting characters, and defining and calling functions to perform operations on integers like addition, multiplication, factorial, prime checking etc.
The document describes a C program that implements selection sort using pointers and functions. It takes input of array size and elements, calls the selection sort function sel() on the array, and prints the sorted output. The sel() function takes the array, start and end indexes, finds the minimum element in the range and swaps it with the start element, then calls itself recursively to sort the rest.
1. The document contains 10 code snippets implementing various data structures and algorithms in C/C++ like linear search, binary search, merge sort, quick sort, selection sort, bubble sort, stack implementation using array, Fibonacci series using recursion, queue implementation using array, and binary search tree operations like insertion, deletion, display and traversal.
2. The codes include functions for searching an element, sorting arrays, implementing stacks and queues as well as common operations on binary search trees.
3. Main functions are included to accept user input, call the relevant functions and output the results of operations like searching, sorting or tree traversals.
This document contains C code examples for various programming concepts like functions, loops, arrays, structures, pointers etc. There are a total of 40 code snippets showing how to use different features in C like printing output, taking input, if-else conditions, switch case, loops (while, for, do-while), functions (call by value, call by reference), arrays (single, multi-dimensional), structures, pointers etc. Each code snippet is commented and labeled to explain the concept demonstrated in that section.
The document discusses different types of selection and looping structures in C programming such as if-else statements, switch statements, while loops, for loops, and nested loops. It provides syntax examples and sample code to demonstrate if-else ladders, nested if statements, while, do-while and for loops. Examples include calculating grades based on marks, finding roots of quadratic equations, Fibonacci series, swapping values and reversing numbers.
An array is a collection of data items stored at contiguous memory locations. Arrays can have one or more dimensions. A one-dimensional array is declared with the data type, array name, and size. Elements are accessed using indexes within brackets. Two-dimensional arrays are declared with the data type, array name with two sets of brackets and sizes. Elements are accessed using row and column indexes. Arrays can be passed to functions by passing a pointer to the first element or by passing the entire array. Array elements can be accessed and modified within functions.
SPL 6.1 | Advanced problems on Operators and Math.h function in CMohammad Imam Hossain
The document provides code samples for solving various problems involving mathematical operations and conversions in C programming language. It includes code to take input, perform calculations using functions like pow(), tan(), exp() etc. and display output. Problems covered are calculating expressions, swapping values, temperature conversion, volume of cylinder, area of triangle, time conversion etc. Detailed code is given with comments to explain each step like variable declaration, input, processing and output.
The document contains C code examples demonstrating various array operations including:
1) Defining and initializing a single dimensional array, printing its elements, and sorting the array using selection sort.
2) Implementing linear and binary search algorithms to search for elements in an array.
3) Defining and initializing a double dimensional (2D) array and printing its elements.
The document contains C code snippets for various programming problems including calculating the area of shapes, finding roots of quadratic equations, sorting arrays, matrix multiplication, and more. The last problem is a program to list the names of students who scored over 60% total marks across three subjects, using a structure variable to store student data.
The document discusses C programming with arrays. It includes 8 programs demonstrating different array operations and concepts like initializing arrays, accessing array elements, passing arrays to functions, 2D arrays, and using pointers with arrays. It also includes diagrams explaining memory representation of arrays and pointer notation. The programs are accompanied by output screenshots and brief descriptions. Overall it provides examples of basic to some advanced array concepts in C programming.
C provides various built-in operators to manipulate data and variables. These operators can be classified as arithmetic, relational, logical, bitwise, assignment, conditional, and special operators. Arithmetic operators perform basic math operations like addition and subtraction. Relational operators compare values. Logical operators combine conditional statements. Bitwise operators perform manipulations at the bit level. Assignment operators assign values. Conditional operators provide an if-else statement in a single line. Precedence and associativity determine the order of evaluation for expressions containing multiple operators.
Work common problems out via a functional approach. Think in terms of functions, be lazy, use pipelines and handle concurrency with immutable data borrowing concepts from Haskell/Scala/Erlang. All of this in Python.
The document provides examples of basic C programs that demonstrate fundamental programming concepts like printing values, arithmetic operations, arrays, functions, conditionals, loops, and matrices. The programs cover topics such as printing and reading integers, adding/multiplying numbers, swapping values, checking vowels/consonants, Armstrong numbers, palindromes, summing matrices, and finding the transpose of a matrix.
Functions allow programmers to organize code into reusable blocks. There are two types of functions: pre-defined/library functions which are provided for use and user-defined functions which are created by the programmer. User-defined functions help reduce code length and make debugging easier. Functions can receive input parameters, return values, or do both. Arrays allow storing and accessing related data through indexes. One-dimensional arrays store data in a single list while multi-dimensional arrays can represent tables of data through multiple indexes.
The document contains code snippets demonstrating the use of blocks and Grand Central Dispatch (GCD) in C. It shows examples of creating and using blocks, dispatch queues, dispatch groups, semaphores, and other GCD features for concurrency and parallelism.
This document describes a C program that implements a double linked list. It includes functions to insert, delete, search, and display nodes in the list. The insert function allocates a new node, gets the insertion position and data from the user, and adds the new node to the list by updating the next and prev pointers of neighboring nodes. It checks for special cases like insertion at the head or end of the list. The other functions are not described in detail.
The document discusses implementation of linked lists in C programming language. It includes functions to create, insert, delete and display nodes in a linked list. The functions demonstrated are to insert nodes at the beginning, end or after a particular node. It also includes functions to delete nodes from the beginning, end or anywhere in the list. The main function uses a switch case to call these functions and operate on a linked list based on user input.
The document discusses functions in C programming. It provides examples of defining functions with parameters and return types, calling functions by passing arguments, using header files to declare functions, and recursion. It shows functions being defined and called to perform tasks like calculating factorials, displaying prices based on hotel rates and nights, and converting numbers to binary. Functions allow breaking programs into smaller, reusable components.
This document provides information about computing fundamentals and C programming concepts such as data types, variables, operators, and decision making structures. It includes code examples demonstrating the use of scanf to read input, basic arithmetic operators, if statements, and more. The document is authored by Dr. Muhammad Yousaf Hamza and covers fundamental C programming topics for beginners.
C programming uses basic elements like expressions, statements, blocks and functions. Expressions combine constants, variables and operators, while statements end with semicolons. A block of statements is treated as a single statement. Standard library functions include printf(), exit() and scanf(). Control structures like if-else, switch, for, while and do-while statements are used for decision making and looping.
The document contains code snippets for several C programs including:
1) A program to add complex numbers by defining a structure for complex numbers and taking user input for real and imaginary parts of two numbers and printing their sum.
2) A binary search algorithm implementation to search a sorted array for a key and return its index.
3) A bubble sort algorithm implementation to sort an array of long integers in ascending order by swapping adjacent elements.
The document contains C code for multiple programs that perform various calculations and operations on arrays and numbers. The programs include:
1. Evaluating mathematical expressions by taking input values, performing calculations defined by the expressions, and outputting results.
2. Performing logical operations and comparisons on input values to determine output values based on if/else or switch statements.
3. Calculating factorials, digit sums, reversing numbers, checking for palindromes, and other numeric operations using loops.
4. Generating patterns and diagrams by iterating with for loops.
5. Performing array operations like reversing elements, calculating sums, and swapping arrays.
The document contains 11 questions related to string manipulation and function problems in C programming. For each question, it provides the full source code of a C program that implements the given task. The questions cover topics such as reading and manipulating strings, calculating lengths, reversing strings, copying strings, comparing strings, counting characters, and defining and calling functions to perform operations on integers like addition, multiplication, factorial, prime checking etc.
The document describes a C program that implements selection sort using pointers and functions. It takes input of array size and elements, calls the selection sort function sel() on the array, and prints the sorted output. The sel() function takes the array, start and end indexes, finds the minimum element in the range and swaps it with the start element, then calls itself recursively to sort the rest.
1. The document contains 10 code snippets implementing various data structures and algorithms in C/C++ like linear search, binary search, merge sort, quick sort, selection sort, bubble sort, stack implementation using array, Fibonacci series using recursion, queue implementation using array, and binary search tree operations like insertion, deletion, display and traversal.
2. The codes include functions for searching an element, sorting arrays, implementing stacks and queues as well as common operations on binary search trees.
3. Main functions are included to accept user input, call the relevant functions and output the results of operations like searching, sorting or tree traversals.
This document contains C code examples for various programming concepts like functions, loops, arrays, structures, pointers etc. There are a total of 40 code snippets showing how to use different features in C like printing output, taking input, if-else conditions, switch case, loops (while, for, do-while), functions (call by value, call by reference), arrays (single, multi-dimensional), structures, pointers etc. Each code snippet is commented and labeled to explain the concept demonstrated in that section.
The document discusses different types of selection and looping structures in C programming such as if-else statements, switch statements, while loops, for loops, and nested loops. It provides syntax examples and sample code to demonstrate if-else ladders, nested if statements, while, do-while and for loops. Examples include calculating grades based on marks, finding roots of quadratic equations, Fibonacci series, swapping values and reversing numbers.
An array is a collection of data items stored at contiguous memory locations. Arrays can have one or more dimensions. A one-dimensional array is declared with the data type, array name, and size. Elements are accessed using indexes within brackets. Two-dimensional arrays are declared with the data type, array name with two sets of brackets and sizes. Elements are accessed using row and column indexes. Arrays can be passed to functions by passing a pointer to the first element or by passing the entire array. Array elements can be accessed and modified within functions.
SPL 6.1 | Advanced problems on Operators and Math.h function in CMohammad Imam Hossain
The document provides code samples for solving various problems involving mathematical operations and conversions in C programming language. It includes code to take input, perform calculations using functions like pow(), tan(), exp() etc. and display output. Problems covered are calculating expressions, swapping values, temperature conversion, volume of cylinder, area of triangle, time conversion etc. Detailed code is given with comments to explain each step like variable declaration, input, processing and output.
The document contains C code examples demonstrating various array operations including:
1) Defining and initializing a single dimensional array, printing its elements, and sorting the array using selection sort.
2) Implementing linear and binary search algorithms to search for elements in an array.
3) Defining and initializing a double dimensional (2D) array and printing its elements.
The document contains C code snippets for various programming problems including calculating the area of shapes, finding roots of quadratic equations, sorting arrays, matrix multiplication, and more. The last problem is a program to list the names of students who scored over 60% total marks across three subjects, using a structure variable to store student data.
The document discusses C programming with arrays. It includes 8 programs demonstrating different array operations and concepts like initializing arrays, accessing array elements, passing arrays to functions, 2D arrays, and using pointers with arrays. It also includes diagrams explaining memory representation of arrays and pointer notation. The programs are accompanied by output screenshots and brief descriptions. Overall it provides examples of basic to some advanced array concepts in C programming.
C provides various built-in operators to manipulate data and variables. These operators can be classified as arithmetic, relational, logical, bitwise, assignment, conditional, and special operators. Arithmetic operators perform basic math operations like addition and subtraction. Relational operators compare values. Logical operators combine conditional statements. Bitwise operators perform manipulations at the bit level. Assignment operators assign values. Conditional operators provide an if-else statement in a single line. Precedence and associativity determine the order of evaluation for expressions containing multiple operators.
Work common problems out via a functional approach. Think in terms of functions, be lazy, use pipelines and handle concurrency with immutable data borrowing concepts from Haskell/Scala/Erlang. All of this in Python.
The document provides examples of basic C programs that demonstrate fundamental programming concepts like printing values, arithmetic operations, arrays, functions, conditionals, loops, and matrices. The programs cover topics such as printing and reading integers, adding/multiplying numbers, swapping values, checking vowels/consonants, Armstrong numbers, palindromes, summing matrices, and finding the transpose of a matrix.
Functions allow programmers to organize code into reusable blocks. There are two types of functions: pre-defined/library functions which are provided for use and user-defined functions which are created by the programmer. User-defined functions help reduce code length and make debugging easier. Functions can receive input parameters, return values, or do both. Arrays allow storing and accessing related data through indexes. One-dimensional arrays store data in a single list while multi-dimensional arrays can represent tables of data through multiple indexes.
The document contains code snippets demonstrating the use of blocks and Grand Central Dispatch (GCD) in C. It shows examples of creating and using blocks, dispatch queues, dispatch groups, semaphores, and other GCD features for concurrency and parallelism.
This document describes a C program that implements a double linked list. It includes functions to insert, delete, search, and display nodes in the list. The insert function allocates a new node, gets the insertion position and data from the user, and adds the new node to the list by updating the next and prev pointers of neighboring nodes. It checks for special cases like insertion at the head or end of the list. The other functions are not described in detail.
The document discusses implementation of linked lists in C programming language. It includes functions to create, insert, delete and display nodes in a linked list. The functions demonstrated are to insert nodes at the beginning, end or after a particular node. It also includes functions to delete nodes from the beginning, end or anywhere in the list. The main function uses a switch case to call these functions and operate on a linked list based on user input.
The document discusses functions in C programming. It provides examples of defining functions with parameters and return types, calling functions by passing arguments, using header files to declare functions, and recursion. It shows functions being defined and called to perform tasks like calculating factorials, displaying prices based on hotel rates and nights, and converting numbers to binary. Functions allow breaking programs into smaller, reusable components.
This document provides information about computing fundamentals and C programming concepts such as data types, variables, operators, and decision making structures. It includes code examples demonstrating the use of scanf to read input, basic arithmetic operators, if statements, and more. The document is authored by Dr. Muhammad Yousaf Hamza and covers fundamental C programming topics for beginners.
This document discusses functions in C programming. It covers defining and declaring functions, variable scope, parameter passing, inline functions, recursive functions, function arguments, and function applications. It provides examples of function definitions and calls using integers, strings, and arrays. It explains call by value, call by address, and call by reference parameter passing. It also discusses global, private, and static variables and using the scope resolution operator.
The document discusses the anatomy of a C program through an example program. It begins with preprocessor directives like #include that link standard libraries. The main() function acts as the entry point and contains variable declarations and executable code. Variables are initialized, a calculation is performed, and printf displays the output. Braces define code blocks and return 0 indicates successful program termination. Comments help explain the code through comment delimiters like // and /* */.
The document discusses different parameter passing techniques in C like pass by value, pass by reference, and how to pass arrays to functions. It provides examples of passing single and multi-dimensional arrays to functions using pass by value and pass by reference. It also discusses nesting of functions and using pointers as function arguments.
The document discusses call-by-value in function invocation in C. When a function is called, only the values of the arguments are passed to the function, not the variables themselves. So any changes made to the parameters inside the function are not reflected in the calling function. This causes an issue when trying to swap variables by passing them to a Swap function.
This document provides an overview of programming with Go Lang. It discusses why Go Lang is useful, including its support for multicore performance, microservices, concurrency, static binaries, and testing. It then covers various Go Lang content like first apps, types, loops, functions, arrays/slices/maps, interfaces, methods, empty interfaces, pointers, and error handling. Code examples are provided to demonstrate many of these concepts.
The document discusses loops in C programming. It provides examples of using for loops to print stars, numbers from 1 to 10, and numbers from 1 to 1000. The for loop syntax of initialization, condition, and increment is explained. Additional examples are given to illustrate using arithmetic expressions and incrementing/decrementing the counter variable. The for loop provides an efficient way to repeat a block of code a fixed number of times without lengthy repetitive code.
The documents contain program code snippets for various sorting and searching algorithms in C programming language including selection sort, bubble sort, quick sort, merge sort, insertion sort, binary search and linear search. The programs take input from the user, implement the respective algorithms to sort or search arrays of numbers, and output the results.
The document discusses loops and switch case statements in C language programming. It provides sample codes and screenshots of outputs to explain steps. Functions like for loops, while loops and do-while loops are looping statements used to repeatedly execute a block of code until a condition is met. Switch case statements are used as alternatives to long if-else statements to compare a variable to multiple integral values. Break and continue keywords are used to control loop flow.
The document provides examples of using functions in C programming. It explains what a function is, how to define a function with return type, parameters, and body. It also discusses function declaration, calling a function, function arguments, and the difference between call by value and call by reference. Examples are given to demonstrate defining, declaring, calling functions, and how call by value does not actually change the argument values unlike call by reference. The document also briefly mentions formal parameters and how they behave like local variables inside a function.
The document discusses functions in computer programming. It defines functions as subprograms that allow code to be reused and tested in isolation. There are three main parts to a function: the definition, which specifies the return type, name, parameters and body; the declaration, which specifies the return type, name and parameters; and the call, which invokes the function. Functions can be categorized based on whether they have arguments and/or return values. Arrays can also be passed as arguments to functions.
The document contains C code implementations of several numerical methods for solving equations, performing numerical integration, and solving ordinary differential equations. These include the bisection method, Newton-Raphson method, interpolation methods, trapezoidal rule, Simpson's rules, and Euler and Runge-Kutta methods. For each method, the relevant theory is briefly explained, then C code is provided as an example to solve a sample problem using that particular method.
The document discusses recursion and pointers in C programming. It provides examples of using recursion to calculate factorials and print a series of numbers. Recursion involves defining a base case and dividing a problem into sub-problems that are similar to the original problem. Pointers store memory addresses and can be used to pass arguments by reference. The address operator & returns the memory address of a variable, while the indirection operator * accesses the value at a pointer's address. Pointers allow returning multiple values from functions and are important for advanced data structures.
1) Functions allow breaking down programs into smaller, self-contained blocks of code that perform specific tasks. Functions make code more organized and reusable.
2) There are two types of functions in C: library functions that are predefined in header files, and user-defined functions that are defined by the user.
3) Functions make code more modular and reusable by allowing the same block of code to be easily called multiple times by name rather than having to rewrite the block.
PROVIDE COMMENTS TO FELLOW STUDENTS ANSWERS AND PLEASE DON’T SAY G.docxamrit47
PROVIDE COMMENTS TO FELLOW STUDENTS ANSWERS AND PLEASE DON’T SAY GOOD WORK NICE FORMULA OR SOMETHING LIKE THAT, BUT ACTULLY HE CAN USE. THANK YOU.
Hartleys Function Code
Contains unread posts
Actions for Hartleys Function Code
Chad Hartley posted Nov 5, 2015 5:10 PM
Subscribe
This program will add an integer number and a decimal number up to 2 decimal places. I have included notes in the code to explain what each thing does. I hope I did this right. It compiles successfully.
PseudoCode
Start
Declare int O1; Stands for Output1
O1=sum; Sum is the functions name
Int sum()
Declare variables
Int num1;
Float num2;
Write “Enter a number.”
Scanf num1
Write”Enter a decimal number.”
Scanf num2
Return num1+num2
end
C Code
#include <stdio.h>
int sum();//prototype
int main()//calling program
{
//Declare a varaiable
int O1;
O1=sum();//main is calling sum one time.
//if I listed this twice it would run the function 'sum' twice.
// Example: if I add a new int (int O1, O2) and declare O2 to
//be O2=sum then the function would run twice.
}
int sum ()//function 'sum'
{
int num1;// Declare intergers/variables
float num2;
printf("Enter a number.\n");
scanf("%d",&num1);// Take first input and assign it to num1
printf("Enter a decimal number.\n");
scanf("%.2f",&num2);
//Can use the printf statement but when you are calling an integer you can use the return.
//printf("The sum of %d, %d, is %d", num1,num2,num1+num2);
return num1+num2;
}
ADD COMMENT HERE
Chaotic Function
Contains unread posts
Actions for Chaotic Function
Joshua Ray posted Nov 5, 2015 2:33 PM
Subscribe
float tmp
int i
function float chaos(float num)
{
for i < 20
num = 3.9*num*(1-num)
print num
}
main
print "Program description"
print "Request input btw 0 and 1"
tmp = input
chaos(tmp)
/*
* File: main.c
* Author: JaiEllRei
*
* Created on November 5, 2015, 2:04 PM
*/
#include <stdio.h>
#include <stdlib.h>
float chaos(float num);
int main(void)
{
float tmp;
printf("This program illustrates a choatic function. \n");
printf("Input a number between 0 and 1: ");
scanf("%f", &tmp);
chaos(tmp);
}
float chaos(float num)
{
for (int i=0; i<20; i++){
/*Chaotic Formula*/
num = 3.9 * num * (1-num);
printf("%.3f \n", num);
}
}
This program illustrates a choatic function.
Input a number between 0 and 1: .2
0.624
0.915
0.303
0.824
0.566
0.958
0.156
0.514
0.974
0.098
0.345
0.881
0.409
0.943
0.210
0.647
0.891
0.379
0.918
0.293
ADD COMMENT HERE
//MPH to KPH Conversion Function
Function KPHConv(value) as float
Set KPHConv = value*1.609344
End Function
Pseudocode for simple conversion program calling function
//Declare function
// MPH to KPH Conversion Function
Functio ...
Unit 1- PROGRAMMING IN C OPERATORS LECTURER NOTESLeahRachael
This document summarizes operators in the C programming language. It discusses arithmetic, unary, relational, logical, and assignment operators. For each operator type, it provides examples of common operators like addition, subtraction, increment, decrement, equality, inequality and examples of how to use them in simple C code snippets. It also covers unary operators like unary minus and plus, and operators for type sizes like sizeof. Overall, the document serves as a basic introduction to different operator categories and syntax in C programming.
This document contains C program code examples for various programming problems. It is divided into 5 weeks. Some of the programs included are: exchanging values between two variables with and without a temporary variable, finding the sum of digits of a positive integer, generating factors of numbers, calculating the factorial of a number, computing the sine function as a series, generating the Fibonacci sequence, reversing digits of an integer, converting decimal to binary, octal and hexadecimal, calculating terms of a series, and performing basic mathematical operations based on user input. The document provides the code and output for each problem.
The document discusses functions in C programming. It defines what a function is and explains why functions are used to avoid duplicating code and make programs easier to design, understand and maintain. It describes the different types of functions like pre-defined and user-defined functions. It also covers function prototypes, parameters, return values, recursion, library functions and pointers.
Bubble Sort,Insertion Sort, Structures,Students Mark statement ,Pointers, Arithmetic operations on pointers, Files,Creating file, Reading file,Writing a text file,binary file,lab programs,c programs,example programs,c program,Bubble Sort in c,Insertion Sort in c, Structures in c,Students Mark statement in c ,Pointers in c, Arithmetic operations on pointers in c, Files in c,Creating file in c, Reading file in c,Writing a text file in c,binary file in c,lab program in c,c program,example program,c program,thiruvalluvar university,lab manual,c lab manual
The document discusses various topics related to file handling and sorting algorithms in C programming. It begins with an introduction to file handling, describing how to open, write, and read from files. It then covers different modes for opening files and examples of writing data to multiple files. The document later discusses linear and binary search algorithms for arrays as well as bubble, selection, and insertion sorts. Code examples are provided for each algorithm discussed.
1) The document discusses structures in C programming, which allow grouping of related data types into a single data type.
2) A structure called student is defined containing member variables like rollnumber, semnumber, and age_years. A variable of this structure type is initialized and its members are accessed.
3) Structures can contain other structures to represent nested relationships between data. They provide a way to organize and manage related data in an application.
Arrays and pointers have a close relationship in C. An array name is a pointer to the first element of the array. Pointers can be used to access and modify array elements. Functions can modify arrays passed by reference by using pointers to the array elements. Pointer arithmetic and array indexing are equivalent and allow accessing successive elements of an array. Pointers to arrays can be returned from functions to access modified arrays.
The document discusses computing fundamentals and functions in C programming. It begins with examples of adding two integers with and without a function. It then defines key terms related to functions such as function prototype, definition, header, calling a function, passing arguments, and returning a value. The document provides examples and notes about different types of functions and their components. It discusses benefits of using functions such as modularity, reusability, and avoiding code repetition.
The document discusses computing fundamentals and string manipulation in C programming. It covers ASCII codes, comparing strings, generating random numbers and the Fibonacci sequence. ASCII codes assign numeric values to characters that are stored in computer memory. Strings can be compared using strcmp() which returns 0 if equal or >0 if the first string is greater. Random numbers are generated between 1-100 using rand()%100+1. The Fibonacci sequence is generated by adding the previous two values to get the next one in the series.
The document discusses various string handling functions in C including strlen(), strcpy(), strcat(), strlwr(), strupr(), strchr(), and continues. It provides examples of using each function, such as using strlen() to get the length of a string, strcpy() to copy one string to another, and strcat() to concatenate two strings. It also discusses using continue in a for loop to count vowels and consonants in a string. The document is authored by Dr. Muhammad Yousaf Hamza and covers fundamental computing and C string operations.
The document discusses computing fundamentals and strings in C programming. It covers that characters are the building blocks of programs and strings are arrays of characters that end with a null character. It provides examples of declaring and initializing strings, printing strings, accessing individual characters, and modifying strings.
The document discusses storing and manipulating two-dimensional arrays in C programming. It explains how to define two-dimensional arrays using nested brackets, initialize them with values, and access elements using row and column subscripts. It also demonstrates how to print two-dimensional arrays in a matrix format using for loops, and provides examples of adding and multiplying matrices using two-dimensional arrays.
The document discusses arrays in C programming. It begins by defining an array as a structure that contains a group of related data items of the same type. It notes that arrays allow accessing elements via an index, with the first element having an index of 0. The document then provides examples of declaring, initializing, accessing, and printing single-dimensional and multi-dimensional arrays. It also demonstrates how to store user input into arrays and perform operations like addition and multiplication on 2D arrays representing matrices.
The document discusses arrays in C programming. It begins by explaining what arrays are and how they are declared and initialized. It provides examples of one-dimensional arrays and shows how to print, read from, and perform calculations on array elements. The document also discusses important points about arrays like initializing with fewer values than size, scanning more values than size, and accessing out of bounds elements. It provides examples of using arrays to find sum, maximum value, and reordering elements based on user input.
The document contains lecture notes from Dr. Muhammad Yousaf Hamza on computing fundamentals and nested loops. It includes examples of C programs to print star patterns using for loops, and modifications to print different patterns. It encourages the reader to write programs to print additional star patterns on their own.
The document discusses various C programming concepts including infinite loops, break, continue, and goto statements. It provides code examples to demonstrate how these statements work, such as using break to exit a loop early or continue to skip the remaining code in the current loop iteration. The exit() function is also covered as a way to terminate a program mid-execution. Overall the document serves as teaching material on flow control statements and functions in C.
The document discusses various loop constructs in C programming such as while, do-while, and for loops. It provides examples of using each loop to count from 1 to 10, print even numbers between two given integers, and calculate a factorial. The key differences between each loop are explained, such as how for loops are preferable when the number of iterations is known beforehand and do-while loops will always execute the body at least once.
The document contains code examples and explanations of conditional statements in C programming. It discusses if, if-else, if-else if statements and uses examples to demonstrate how to check conditions and execute different code blocks based on whether the conditions are true or false. It also covers logical operators like &&, || and ! that are used to combine multiple conditions. Finally, it briefly introduces the ternary conditional operator ?: that allows writing if-else statements in a single line.
This document contains a summary of computing fundamentals and C programming concepts provided by Dr. Muhammad Yousaf Hamza. It includes:
1) An example C program that declares variables, performs basic math operations, and prints outputs using printf.
2) An explanation of escape sequences in C and examples of their usage.
3) Guidelines for naming variables in C, including allowed characters and conventions.
4) An overview of comments in C, including how to write single-line and multi-line comments.
This document provides information about a computing fundamentals course taught by Dr. Muhammad Yousaf Hamza. It includes details about the instructor's qualifications, course contents covering basic computer components and programming in C, recommended textbooks, and objectives of the course which are to learn computer fundamentals and the C programming language. It also presents sample C code for a basic program that calculates the sum and difference of two integers as an example of the first program students will write in the course.
it describes the bony anatomy including the femoral head , acetabulum, labrum . also discusses the capsule , ligaments . muscle that act on the hip joint and the range of motion are outlined. factors affecting hip joint stability and weight transmission through the joint are summarized.
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UPRAHUL
This Dissertation explores the particular circumstances of Mirzapur, a region located in the
core of India. Mirzapur, with its varied terrains and abundant biodiversity, offers an optimal
environment for investigating the changes in vegetation cover dynamics. Our study utilizes
advanced technologies such as GIS (Geographic Information Systems) and Remote sensing to
analyze the transformations that have taken place over the course of a decade.
The complex relationship between human activities and the environment has been the focus
of extensive research and worry. As the global community grapples with swift urbanization,
population expansion, and economic progress, the effects on natural ecosystems are becoming
more evident. A crucial element of this impact is the alteration of vegetation cover, which plays a
significant role in maintaining the ecological equilibrium of our planet.Land serves as the foundation for all human activities and provides the necessary materials for
these activities. As the most crucial natural resource, its utilization by humans results in different
'Land uses,' which are determined by both human activities and the physical characteristics of the
land.
The utilization of land is impacted by human needs and environmental factors. In countries
like India, rapid population growth and the emphasis on extensive resource exploitation can lead
to significant land degradation, adversely affecting the region's land cover.
Therefore, human intervention has significantly influenced land use patterns over many
centuries, evolving its structure over time and space. In the present era, these changes have
accelerated due to factors such as agriculture and urbanization. Information regarding land use and
cover is essential for various planning and management tasks related to the Earth's surface,
providing crucial environmental data for scientific, resource management, policy purposes, and
diverse human activities.
Accurate understanding of land use and cover is imperative for the development planning
of any area. Consequently, a wide range of professionals, including earth system scientists, land
and water managers, and urban planners, are interested in obtaining data on land use and cover
changes, conversion trends, and other related patterns. The spatial dimensions of land use and
cover support policymakers and scientists in making well-informed decisions, as alterations in
these patterns indicate shifts in economic and social conditions. Monitoring such changes with the
help of Advanced technologies like Remote Sensing and Geographic Information Systems is
crucial for coordinated efforts across different administrative levels. Advanced technologies like
Remote Sensing and Geographic Information Systems
9
Changes in vegetation cover refer to variations in the distribution, composition, and overall
structure of plant communities across different temporal and spatial scales. These changes can
occur natural.
Leveraging Generative AI to Drive Nonprofit InnovationTechSoup
In this webinar, participants learned how to utilize Generative AI to streamline operations and elevate member engagement. Amazon Web Service experts provided a customer specific use cases and dived into low/no-code tools that are quick and easy to deploy through Amazon Web Service (AWS.)
Main Java[All of the Base Concepts}.docxadhitya5119
This is part 1 of my Java Learning Journey. This Contains Custom methods, classes, constructors, packages, multithreading , try- catch block, finally block and more.
This document provides an overview of wound healing, its functions, stages, mechanisms, factors affecting it, and complications.
A wound is a break in the integrity of the skin or tissues, which may be associated with disruption of the structure and function.
Healing is the body’s response to injury in an attempt to restore normal structure and functions.
Healing can occur in two ways: Regeneration and Repair
There are 4 phases of wound healing: hemostasis, inflammation, proliferation, and remodeling. This document also describes the mechanism of wound healing. Factors that affect healing include infection, uncontrolled diabetes, poor nutrition, age, anemia, the presence of foreign bodies, etc.
Complications of wound healing like infection, hyperpigmentation of scar, contractures, and keloid formation.
Beyond Degrees - Empowering the Workforce in the Context of Skills-First.pptxEduSkills OECD
Iván Bornacelly, Policy Analyst at the OECD Centre for Skills, OECD, presents at the webinar 'Tackling job market gaps with a skills-first approach' on 12 June 2024
Strategies for Effective Upskilling is a presentation by Chinwendu Peace in a Your Skill Boost Masterclass organisation by the Excellence Foundation for South Sudan on 08th and 09th June 2024 from 1 PM to 3 PM on each day.
Temple of Asclepius in Thrace. Excavation resultsKrassimira Luka
The temple and the sanctuary around were dedicated to Asklepios Zmidrenus. This name has been known since 1875 when an inscription dedicated to him was discovered in Rome. The inscription is dated in 227 AD and was left by soldiers originating from the city of Philippopolis (modern Plovdiv).
Philippine Edukasyong Pantahanan at Pangkabuhayan (EPP) CurriculumMJDuyan
(𝐓𝐋𝐄 𝟏𝟎𝟎) (𝐋𝐞𝐬𝐬𝐨𝐧 𝟏)-𝐏𝐫𝐞𝐥𝐢𝐦𝐬
𝐃𝐢𝐬𝐜𝐮𝐬𝐬 𝐭𝐡𝐞 𝐄𝐏𝐏 𝐂𝐮𝐫𝐫𝐢𝐜𝐮𝐥𝐮𝐦 𝐢𝐧 𝐭𝐡𝐞 𝐏𝐡𝐢𝐥𝐢𝐩𝐩𝐢𝐧𝐞𝐬:
- Understand the goals and objectives of the Edukasyong Pantahanan at Pangkabuhayan (EPP) curriculum, recognizing its importance in fostering practical life skills and values among students. Students will also be able to identify the key components and subjects covered, such as agriculture, home economics, industrial arts, and information and communication technology.
𝐄𝐱𝐩𝐥𝐚𝐢𝐧 𝐭𝐡𝐞 𝐍𝐚𝐭𝐮𝐫𝐞 𝐚𝐧𝐝 𝐒𝐜𝐨𝐩𝐞 𝐨𝐟 𝐚𝐧 𝐄𝐧𝐭𝐫𝐞𝐩𝐫𝐞𝐧𝐞𝐮𝐫:
-Define entrepreneurship, distinguishing it from general business activities by emphasizing its focus on innovation, risk-taking, and value creation. Students will describe the characteristics and traits of successful entrepreneurs, including their roles and responsibilities, and discuss the broader economic and social impacts of entrepreneurial activities on both local and global scales.
Communicating effectively and consistently with students can help them feel at ease during their learning experience and provide the instructor with a communication trail to track the course's progress. This workshop will take you through constructing an engaging course container to facilitate effective communication.
2. // Addition of two integers using
//Function
#include<stdio.h>
int addnumbers(int x, int y);
int main()
{
int num1, num2, add_result;
printf("Enter first numbern");
scanf("%d", &num1);
printf("Enter second numbern");
scanf("%d", &num2);
add_result = addnumbers(num1,
num2);
printf("Addition result is
%dn",add_result);
getchar(); return 0;
}
int addnumbers(int x, int y)
{
int z;
z = x +y;
return z;
}
Dr. Yousaf, PIEAS
3. // Addition of two integers using
//Function
#include<stdio.h>
int addnumbers(int x, int y);
int main()
{
int num1, num2, add_result;
printf("Enter first numbern");
scanf("%d", &num1);
printf("Enter second numbern");
scanf("%d", &num2);
add_result = addnumbers(num1,
num2);
printf("Addition result is
%dn",add_result);
printf(“%d”, z) // Error
getchar(); return 0; }
int addnumbers(int x, int y)
{
int z;
z = x +y;
printf(“%d”, num1) // Error
return z;
}
Dr. Yousaf, PIEAS
Any variable declared in a function is
not visible inside main and vice versa.
4. Dr. Yousaf, PIEAS
Example of Function
// To determine the even or odd using
// a function
#include<stdio.h>
void EvenOrOdd(int num);
int main()
{
int num;
printf("Enter a number to know even
or oddn");
printf("Enter -100 to exitn");
while (1)
{
scanf("%d", &num);
if (num == -100)
break;
EvenOrOdd(num);
}
printf("OK");
getchar(); return 0; }
void EvenOrOdd(int num)
{
if(num%2==0)
printf("Evenn");
else
printf("Oddn");
}
5. Dr. Yousaf, PIEAS
Example of Function
#include<stdio.h>
void printLine(void)
{
printf("n*****************n");
}
void main ()
{
int num;
printLine();
printf("Enter a Number :");
scanf("%d",&num);
if(num%2==0)
printf("Even Number");
else
printf("Odd Number");
printLine();
getchar();
}
Output
*****************
Enter a Number :13
Odd Number
*****************
6. Returning a value using if else statement
A single value is returned, however, multiple
return statements can be used within a single
function using “if-then-else” statement.
Dr. Yousaf, PIEAS
7. Dr. Yousaf, PIEAS
// Returning a value and if else
#include<stdio.h>
int myfunc(int x, int y);
int main()
{
int num1, num2, smaller;
printf("Enter first numbern");
scanf("%d", &num1);
printf("Enter second numbern");
scanf("%d", &num2);
smaller = myfunc(num1, num2);
printf("%d is smallern",smaller);
getchar();
getchar();
return 0;
}
int myfunc(int x, int y)
{
if(x < y )
return x;
else
return y;
}
8. Home/Lab Assignments
Write a function that returns the greater of the two numbers i.e.
make a function that takes two integer arguments and returns the
greater of the two. Write program to use this function.
(Try Yourself)
Write a function should accept two arguments i.e. length and
width of the rectangle and should return the area of the
rectangle, the prototype of the function is as under:
float areaRect(float, float);
(Try Yourself)
Develop a function that accepts two values as length and width of
a shape and returns 0 or 1. A 1 will be returned if the shape is a
square otherwise a 0 will be returned.
(Try Yourself).
Dr. Yousaf, PIEAS
9. Home/Lab Assignments
A normal dice has 6 sides numbered from 1 to 6, when the dice is
rolled the number on top side of the dice is considered to be the
result of rolling the dice. Dices are used in many games etc. Your
task is to write a function int rollDice(), the function should return
an integer value ranging from 1 to 6, to make function return a
random number each time use the library function rand() and
srand() (. Write a program that allow the user to call this function
multiple times , display the value returned by the function.
(Try Yourself)
Dr. Yousaf, PIEAS
10. Pass by Value Versus Pass by Reference
Dr. Yousaf, PIEAS
11. // Addition of two integers using Function
#include<stdio.h>
int addnumbers(int x, int y);
int main()
{
int num1, num2, add_result;
printf("Enter first numbern");
scanf("%d", &num1);
printf("Enter second numbern");
scanf("%d", &num2);
add_result = addnumbers(num1, num2);
printf("Addition result is
%dn",add_result);
getchar(); return 0; }
int addnumbers(int x, int y)
{
int z;
z = x +y;
return z;
}
Dr. Yousaf, PIEAS
Pass by Value
12. Dr. Yousaf, PIEAS
/* Passing arguments by value */
//Page Example 366
#include <stdio.h>
void by_value(int x, int y, int z);
int main()
{
int x = 2, y = 4, z = 6;
printf("n Before calling by_value,
x = %d, y = %d, z = %d.", x, y, z);
by_value(x, y, z);
printf("nn After calling by_value, x
= %d, y = %d, z = %d.",
x, y, z);
getchar();
return(0);
}
void by_value(int x, int y, int z)
{ printf("nn Within function
by_value, x = %d, y = %d, z =
%d.", x, y, z);
x = 0; y = 0; z = 0;
printf("nn Again within
function by_value , x = %d, y =
%d, z = %d.", x, y, z); }
Before calling by_value,
x = 2, y = 4, z = 6.
// Within function by_value,
x = 2, y = 4, z = 6.
// Again Within function
by_value,
x = 0, y = 0, z = 0.
//After calling y_value(),
x = 2, y = 4, z = 6.
Pass by Value
13. Calling Functions:
Call by Value and Call by Reference
• Used when invoking functions
• Call by value
– Copy of argument passed to function
– Changes in function do not effect original
– Use when function does not need to modify argument
• Avoids accidental changes
• Call by reference
– Passes original argument
– Changes in function effect original
– Only used with trusted functions
• At this stage, we focus on call by value
• We will discuss call by reference later.
Dr. Yousaf, PIEAS
14. Parameters Passed by Value
• Parameters passed by
value!!
– This means they are
basically local variables
initialized to the values
that the function is
called with.
– They can be modified
as you wish but these
modifications will not
be seen in the calling
routine!
#include<stdio.h>
int twice(int x);
int main()
{
int x=10,y;
y=twice(x);
printf("%d,%dn",x,y);
getchar(); retun 0;
}
int twice(int x)
{
x=x+x;
return x;
}
Dr. Yousaf, PIEAS
16. Functions can access other functions
Once you have written a function, it can be accessed
from other functions. We can therefore build more
complex functions from simpler functions
Dr. Yousaf, PIEAS
17. Dr. Yousaf, PIEAS
// Function calling other function
#include <stdio.h>
float getavg(float x, float y, float z, int totnum);
float calavg(float sum_res, int totalnum);
int main() { float num1 = 3.5, num2 = 5.9, num3 = 1.7, avg;
int totnumbers = 3;
avg = getavg(num1,num2,num3,totnumbers);
printf("Average is %fn",avg); getchar(); return 0; }
float getavg(float x, float y, float z, int totnum)
{ float sum = x + y + z, average;
average = calavg(sum, totnum);
return average;
}
float calavg(float sum_res, int totalnum)
{ float avrg = sum_res/totalnum;
return avrg; }
18. Calling a function by Another Function
void a(void)
{
printf(“Function a”);
b();
}
void b(void)
{
printf(“Function b”);
}
void main()
{
a();
b();
}
Dr. Yousaf, PIEAS
Can we call function b() inside function a() ?
No, as function a() does not know anything
about function b().
A function can call only those functions
which are defined or declared before it.
20. // Calculate factorial without function
#include<stdio.h>
int main()
{
int i, fact, num1;
printf("Enter a positive integern");
scanf("%d", &num1);
fact = 1;
for (i = num1; i >=1; i--)
{
fact = fact * i;
}
printf("Factorial of %d is %dn",num1, fact);
getchar();
return 0;
}
Dr. Yousaf, PIEAS
21. Dr. Yousaf, PIEAS
// Calculate factorial using
//Functions
#include<stdio.h>
int cal_fac(int x);
int main()
{
int i, fact, num1;
printf("Enter a positive integren");
scanf("%d", &num1);
fact = cal_fac(num1);
printf("Factorial of %d is
%dn",num1, fact);
getchar();
return 0;
}
int cal_fac(int x)
{
int i, fact;
fact = 1;
if(x == 0)
fact = 1;
else
{
for (i = x; i >=1; i--)
{
fact = fact*i;
}
}
return fact;
}
22. Dr. Yousaf, PIEAS
/* demonstrates a function that does
not take any arguments and does not
provide output to main. */
#include <stdio.h>
void stars (); //function declaration
// (prototype)
int main()
{
int x = 5, y = 13;
stars (); //call to function
x = x+10;
y = x*x + (10/2);
stars (); //call to function
getchar(); return 0;
}
// function definition
void stars ()
{
int j;
for(j=0; j < 10; j++)
printf("*");
printf("n");
}
Printing stars through a function
23. Dr. Yousaf, PIEAS
// demonstrates of passing
//constants to a function
#include <stdio.h>
void stars (char ch, int n) ;
int main()
{
int x = 5, y = 13, z;
stars (‘%’, 7); //call to function
x = x+10;
y = x*x + (10/2);
stars (‘$’, 18); //call to function
z = x + y;
return 0;
}
// function definition
void stars (char ch, int n)
{
int j;
for(j=0; j < n; j++)
printf(“%c“, ch);
printf("n");
}
Printing any symbol any times
24. Dr. Yousaf, PIEAS
// demonstrates of passing values from
//variables to a function
#include <stdio.h>
void stars (char ch, int n) ;
int main()
{
char chp;
int nt ;
printf(“Please enter a symbol you want
to printn”);
chp = getchar();
printf(“Please enter the number of times
you want to print the charactern”);
scanf(“%d”, nt);
stars (chp, nt); //call to function
// Rest of the code here
return 0;
}
// function definition
void stars (char ch, int n)
{
int j;
for(j=0; j < n; j++)
printf(“%c“, ch);
printf("n");
}
Passing Variables
25. Dr. Yousaf, PIEAS
// Demonstration of missing arguments
#include <stdio.h>
void stars (char ch = ‘*’, int n = 10) ;
int main()
{
char chp;
int nt ;
// Rest of the code
stars (); //call to function
stars (‘#’); //call to function
stars (‘+’, 5); //call to function
chp = ‘~’;
nt = 12;
stars (chp, nt); //call to function
stars();
// Rest of the code here
return 0; }
// function definition
void stars (char ch, int n)
{
int j;
for(j=0; j < n; j++)
printf(“%c“, ch);
printf("n");
}
Missing Arguments
26. Returning a value from function
Dr. Yousaf, PIEAS
/* Program that will pass temperature in
centigrade to a function that converts it
into Fahrenheit and returns the value to
the main function*/
#include <stdio.h>
float ctof (float); //declaration
int main()
{
float centi, farhen;
printf("nEnter temperature in
centigraden");
scanf("%f",¢i);
farhen = ctof(centi);
printf(“ %f Centigrade = %f Faherenheit”,
centi, fahren);
getchar();
return 0;
}
/* converts centigrade to
Fahrenheit */
float ctof (float cgrade)
{
float fgrade;
fgrade = (9/5)*cgrade+ 32.0;
return fgrade;
}
27. Arguments and Parameters
• stars (‘%’, 7); //call to function
• Arguments: The values as ‘%’, 7 that are passed to a
function are called arguments.
• void stars (char ch, int n)
• The variables within the function that hold the
arguments are called parameters. In this example, ch
and n are parameters.
• We should note that many programmers use the terms
argument and parameter somewhat interchangeably.
• When the function is called, its parameters are
automatically initialized to the values passed by the
calling program.
Dr. Yousaf, PIEAS
28. // Finding the maximum of three numbers using a function
#include<stdio.h>
int maximum( int, int, int );
int main()
{
int a, b, c;
printf("Enter three integers: " );
scanf("%d%d%d", &a, &b, &c );
printf( "Maximum is: %dn", maximum( a, b, c ) );
getchar(); return 0;
}
int maximum( int x, int y, int z )
{
int max = x;
if ( y > max )
max = y;
if ( z > max )
max = z;
return max;}
Dr. Yousaf, PIEAS
29. Passing string to a function
#include <stdio.h>
void Display(char ch[]);
int main()
{
char c[50];
printf("Enter string: ");
gets(c);
Display(c); // Passing string c to function.
getchar(); return 0;
}
// Function definition
void Display(char ch[]) // It will automatically fix its size
{
printf("String Output: ");
puts(ch);
}
Dr. Yousaf, PIEAS
30. #include <stdio.h>
void func1(void);
int main()
{
int count;
for (count = 0; count < 20; count++)
{
printf("At iteration %d: ", count);
func1();
}
getchar(); return 0;
}
void func1(void)
{
int x = 0;
int y = 0;
printf("x = %d, y = %dn", x, y);
x++;
y++;
}
Dr. Yousaf, PIEAS
• At iteration 0: x = 0, y = 0
• At iteration 1: x = 0, y = 0
• At iteration 2: x = 0, y = 0
• At iteration 3: x = 0, y = 0
• At iteration 4: x = 0, y = 0
• At iteration 5: x = 0, y = 0
• At iteration 6: x = 0, y = 0
• At iteration 7: x = 0, y = 0
• At iteration 8: x = 0, y = 0
• At iteration 9: x = 0, y = 0
• and so on
32. //Concept of local variables
#include <stdio.h>
void demo(void);
int main()
{
int x = 1, y = 2;
printf("nnBefore calling demo(), x = %d and y = %d", x, y); //x=1, y=2
demo();
printf("nnAfter calling demo(), x = %d and y = %dn", x, y); //x=1,y=2
getchar(); return 0;
}
void demo(void) // Function header and definition
{
/* Declare and initialize two local variables. */
int x = 88, y = 99;
/* Display their values. */
printf("nnWithin demo(), x = %d and y = %d", x, y); // x=88, y=89
}
Dr. Yousaf, PIEAS
33. What is scope?
• The scope of a variable is where it can be used in
a program
LOCAL VARIABLES
• Normally variables are local in scope - this means
they can only be used in the function where they
are declared.
• All variables declared inside functions are local
variables
– Known only in function defined
Dr. Yousaf, PIEAS
34. Local Variables
• Local Variables
int func1 (int y)
{
int a, b = 10;
float rate;
double cost = 12.55;
.......
}
• Those variables declared “within” the function are
considered “local variables”.
• They values can only be used inside the function they
were declared in, and not elsewhere.
Dr. Yousaf, PIEAS
35. The print stars example
#include <stdio.h>
void print_stars(int);
int main()
{
int i;
for (i= 0; i < 5; i++)
print_stars(5);
return 0;
}
void print_stars (int n)
{
int i;
for (i= 0; i < n; i++)
printf ("*");
printf ("n");
}
This program prints five rows of
five stars
This prints 'n' stars and then
a new line character
Loop around 5 times to
print the stars
*****
*****
*****
*****
*****
Variables here are LOCAL variables
Dr. Yousaf, PIEAS
37. // Scope of variables, Page 80
//Local versus global (external) variables, pages; 207-209
// Local Variable
#include<stdio.h>
void demo(int x);
int main()
{
int x = 10;
printf("n in main, before demo x = %d nn", x); // x = 10
demo(x);
printf("in main, after demo x = %d nn", x); // x = 10
getchar(); return 0;
}
void demo (int x)
{
x = x+20;
printf("inside demo x= %d nn", x); // x = 30
}
•
Dr. Yousaf, PIEAS
38. // Global variable
#include<stdio.h>
void demo();
int x = 10; // note the declaration above the main
int main()
{
printf("nin main, before demo x = %d nn", x); // x = 10
demo();
printf("in main, after demo x = %d nn", x); // x = 30
getchar();
return 0;
}
void demo ()
{
x = x + 20; // x has not been declared in demo
printf("in demo x = %d nn", x); // x = 30
}
Dr. Yousaf, PIEAS
39. Global Variables
• We can also declare global variables.
• If we declare a variable outside a function it can be
used in any function beneath where it is declared,
hence called global variables.
• Global variables are also sometimes called external
variables, since they are defined external to any
function.
Dr. Yousaf, PIEAS
40. // Again x is global variable
#include<stdio.h>
void demo(int y); // y is local variable
int x = 10; // x is global variable
int main()
{
printf("nin main, before demo x = %d nn", x); // x = 10
demo(x);
printf("in main, after demo x = %d nn", x); // x = 30
getchar();
return 0;
}
void demo (int y) // y has been declared in demo
{
x = y + 20; // x has not been declared in demo
printf("in demo x = %d nn", x); // x = 30
}
Dr. Yousaf, PIEAS
41. // Still Local variable
#include<stdio.h>
void demo(int x);
int x = 10;
int main()
{
printf("nin main, before demo x = %d nn", x); // x = 10
demo(x);
printf("nin main, after demo x = %d nn", x); // x = 10
getchar();
return 0;
}
void demo (int x) // demo has its own x, so now local for this function.
{
x = x + 20;
printf("in demo x = %d nn", x); // x = 30
} Dr. Yousaf, PIEAS
42. Example: Global Variable
Dr. Yousaf, PIEAS
#include <stdio.h>
float total = 0.0;
void caltot (float num1, float num2,
float num3); //declaration
void printtot ();
int main()
{
float x = 4.5, y = 3.7, z = 8.1;
caltot(x, y, z);
printtot();
printf(“Total is %fn”, total);
getchar();
return 0;
}
void caltot (float num1,
float num2, float num3)
{
total = num1 + num2 +
num3;
}
void printtot ()
{
printf(“Total is %fn”, total);
}
43. Example: Previous Example Without
Global Variable // Error
Dr. Yousaf, PIEAS
#include <stdio.h>
void caltot (float num1, float num2,
float num3); //declaration
void printtot ();
int main()
{
float x = 4.5, y = 3.7, z = 8.1;
float total = 0.0;
caltot(x, y, z);
printtot();
printf(“Total is %fn”, total);
getchar();
return 0;
}
void caltot (float num1,
float num2, float num3)
{
total = num1 + num2 +
num3; // error
}
void printtot ()
{
printf(“Total is %fn”, total);
// error
}
44. Notes About Global Variables
– Global variables are also called extern
variables.
– Global variables are known in any function
• A global variable is used when it must be accessible to
more than one function in a program.
• Global variables are often the most important variables
in procedural programs.
• However, global variables create organizational problems
because they can be accessed by any function.
• The wrong functions may access them, or functions may
access them incorrectly.
Dr. Yousaf, PIEAS
45. Notes About Global Variables
Question:
Can there be a local and a global variable of same name?
Ans:
Yes, if a function has a variable whose name is same as
previously declared global variable, then the local
variable will take precedence inside such a function
Dr. Yousaf, PIEAS
46. Home Take Assignment
(1) Declare a global array of 10 integers, declare a variable size that
will store the size of the array, now write the following functions.
A. void PrintArray(void) : This function should print the global array
B. void SumArray(void): This function should print the sum of all
elements of the array
(2) A palindrome is a number that reads the same from left to right or
from right to left. For example 121 , 222, 62226 are all palindrome
numbers.
Write a program (without function) that should accept three digits
number from the user. You code should tell whether the given number
is palindrome or not?
(3) Modify the above program such that it should accept three digits
number from the user. Write a function isPalindrome. Pass the
number provided by the user from main to this function. This function
should determine whether the number is palindrome or not? The
function should return the result to the main. The main should display
it.
Dr. Yousaf, PIEAS
47. Home Take Assignment
A stack is a container of objects such that objects are placed on top of
each other just like dishes are placed on top of each other.
Write a program that declares a global array of 10 integers, name this
array as stack. 2‐ Write the following functions
1‐push: This function should put the value of a variable to the stack.
2‐pop: This function should return the first element of the array
3‐show: The function should display the contents of the array stack
4-shift_right : This function should shift the elements of the array 1
place toward right i.e. element at index 0 will move to index 1 ,
element at index 1 will move to index 2 and so on till the last array
element is processed
5. void shift_left(void) : this function should shift the elements of the
array 1 place towards left i.e. element at index 1 will be shifted to
index 0, element at index 2 will be shifted to index 1.
Dr. Yousaf, PIEAS