Let us C (by yashvant Kanetkar) chapter 3 SolutionHazrat Bilal
All rights reserved. No part of this slide
may be reproduced, stored in a retrieval
system, or transmitted, in any form or by
any means, without the prior permission.
hey this is Rupendra choudhary..!! i shared my "c" lang ppt..!!! u just goto that ppt if u r in deep with "c" ..!!! i create after i hv played a much with "c"..(sorry bt ppt is slightly disturbd may be due to unsupportable msppt2010 by slideshare)...find me on rupendrachoudhary1990@gmail.com or https://rupendrachoudhary.wordpress.com
PowerPoint presentation of functions in C language. It will give you brief idea how function works in C along with its unique features like return statement.
Let us C (by yashvant Kanetkar) chapter 3 SolutionHazrat Bilal
All rights reserved. No part of this slide
may be reproduced, stored in a retrieval
system, or transmitted, in any form or by
any means, without the prior permission.
hey this is Rupendra choudhary..!! i shared my "c" lang ppt..!!! u just goto that ppt if u r in deep with "c" ..!!! i create after i hv played a much with "c"..(sorry bt ppt is slightly disturbd may be due to unsupportable msppt2010 by slideshare)...find me on rupendrachoudhary1990@gmail.com or https://rupendrachoudhary.wordpress.com
PowerPoint presentation of functions in C language. It will give you brief idea how function works in C along with its unique features like return statement.
This is a Chapter extracted from the book 'Bella and Geeky Quba' published by baabtra.com for nourishing programmings skills in students at very early age itself. The book is aimed at primary and pre-primary school students to teach programming concepts through story lines and gaming environments
At the end of this lecture students should be able to;
Describe the looping structures in C programming language.
Practice the control flow of different looping structures in C programming language.
Practice the variants in control flow of different looping structures in C programming language.
Apply taught concepts for writing programs.
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 ...
This is continuation of the slide Advanced C part 1. In part 1 you learnt about fundamentals of C - How to build an algorithm, operators. In this module - Advanced C part 2 you will be learning about functions, pointers and standard Input Output functions. This slide will help you to move a further ahead in Advanced C and gain deeper knowledge on it.
BKK16-503 Undefined Behavior and Compiler Optimizations – Why Your Program St...Linaro
Compilers such as GCC may use undefined behaviour in language specifications to generate efficient code (especially newer recent versions). The rules for undefined behaviour can be subtle and programming mistakes can lead to correctness and/or security issues. This presentation will examine issues resulting from undefined behavior in applications. It will also discuss the position of the relevant language standards and address what compilers can do to exploit the standard in order to generate optimized code. We will also look at tools that can help us in detecting undefined behaviours so that these correctness issues can be prevented.
This PPT will help to understand how learning happens in brain. How you can adjust your skill acquisition in the right way so that maximum output is obtained.
Baabtra.com has a solution to provide programming for kids in school. This is based on the CBSE curriculum of India. The main subjects covered are Mathematics and Physics.
99LMS is a mobile based comprehensive enterprise learning environment in which learning processes of a company can be managed and integrated. It ensures employees have the right skills by enabling course content management, providing classroom training and e-learning. Through the APIs, you can develop your resources before they join your company.
How to Make a Field invisible in Odoo 17Celine George
It is possible to hide or invisible some fields in odoo. Commonly using “invisible” attribute in the field definition to invisible the fields. This slide will show how to make a field invisible in odoo 17.
Palestine last event orientationfvgnh .pptxRaedMohamed3
An EFL lesson about the current events in Palestine. It is intended to be for intermediate students who wish to increase their listening skills through a short lesson in power point.
Embracing GenAI - A Strategic ImperativePeter Windle
Artificial Intelligence (AI) technologies such as Generative AI, Image Generators and Large Language Models have had a dramatic impact on teaching, learning and assessment over the past 18 months. The most immediate threat AI posed was to Academic Integrity with Higher Education Institutes (HEIs) focusing their efforts on combating the use of GenAI in assessment. Guidelines were developed for staff and students, policies put in place too. Innovative educators have forged paths in the use of Generative AI for teaching, learning and assessments leading to pockets of transformation springing up across HEIs, often with little or no top-down guidance, support or direction.
This Gasta posits a strategic approach to integrating AI into HEIs to prepare staff, students and the curriculum for an evolving world and workplace. We will highlight the advantages of working with these technologies beyond the realm of teaching, learning and assessment by considering prompt engineering skills, industry impact, curriculum changes, and the need for staff upskilling. In contrast, not engaging strategically with Generative AI poses risks, including falling behind peers, missed opportunities and failing to ensure our graduates remain employable. The rapid evolution of AI technologies necessitates a proactive and strategic approach if we are to remain relevant.
Unit 8 - Information and Communication Technology (Paper I).pdfThiyagu K
This slides describes the basic concepts of ICT, basics of Email, Emerging Technology and Digital Initiatives in Education. This presentations aligns with the UGC Paper I syllabus.
Acetabularia Information For Class 9 .docxvaibhavrinwa19
Acetabularia acetabulum is a single-celled green alga that in its vegetative state is morphologically differentiated into a basal rhizoid and an axially elongated stalk, which bears whorls of branching hairs. The single diploid nucleus resides in the rhizoid.
Model Attribute Check Company Auto PropertyCeline George
In Odoo, the multi-company feature allows you to manage multiple companies within a single Odoo database instance. Each company can have its own configurations while still sharing common resources such as products, customers, and suppliers.
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdfTechSoup
In this webinar you will learn how your organization can access TechSoup's wide variety of product discount and donation programs. From hardware to software, we'll give you a tour of the tools available to help your nonprofit with productivity, collaboration, financial management, donor tracking, security, and more.
Introduction to AI for Nonprofits with Tapp NetworkTechSoup
Dive into the world of AI! Experts Jon Hill and Tareq Monaur will guide you through AI's role in enhancing nonprofit websites and basic marketing strategies, making it easy to understand and apply.
Operation “Blue Star” is the only event in the history of Independent India where the state went into war with its own people. Even after about 40 years it is not clear if it was culmination of states anger over people of the region, a political game of power or start of dictatorial chapter in the democratic setup.
The people of Punjab felt alienated from main stream due to denial of their just demands during a long democratic struggle since independence. As it happen all over the word, it led to militant struggle with great loss of lives of military, police and civilian personnel. Killing of Indira Gandhi and massacre of innocent Sikhs in Delhi and other India cities was also associated with this movement.
3. ● A substantial portion of a knowledge
worker's life may be spent waiting for a
computer program to produce output.
● Users and organizations control their wait time
by purchasing faster computers, adding memory, or using
faster network connections.
● Developers of application programs have a responsibility to
design their programs make the best use of these limited and
expensive resources.
4. What Is Code Optimization
● Optimization is the process of transforming a piece of code to make
it more efficient without changing its output
● Code optimization is a set of methods for code modification that
improves the code quality and efficiency.
● Optimization aims at -smaller size
-less memory consumption
-rapid executions (only few I/O operations)
5. Where To Optimize
● Check which portion or which module of the program is
running slow or using huge memory.
● If each part is separately being optimized then the total
programme will automatically get optimised.
● Optimization should be done on those part of program that
are run the most,especially on those methods which are called
repeatedly
6. Code Optimization Techniques
A program consist of :
• variables
• control statements
decision
loops
• functions
we need to optimize all these parts to run the program faster
7. Variable
The C compilers support the basic types
char,
short,
int,
long (signed and unsigned),
float and
double.
Using the most appropriate type for variables is very important, as it can reduce code
and data size and increase performance considerably.
8. Integers
Use unsigned int instead of int if we know the value will never be negative.
Some processors can handle unsigned integer arithmetic considerably faster than signed
So, the best declaration for an int variable in a tight loop would be:
unsigned int variable_name;
integer arithmetic is much faster than floating-point arithmetic, as it can usually be
done directly by the processor, rather than relying on external FPUs or floating point
math libraries.
9. Global variables
● Global variables are never allocated to registers.
● Global variables can be changed by assigning them indirectly using a pointer, or
by a function call.
● The compiler cannot cache the value of a global variable in a register, resulting in
extra loads and stores when globals are used.
int f(void);
int g(void);
int errs;
void test1(void)
{
errs += f();
errs += g();
}
Here a function uses global
variables heavily
10. Global variables
int f(void);
int g(void);
int errs;
void test1(void)
{
errs += f();
errs += g();
}
it is beneficial to copy
those global variables into
local variables so that they
can be assigned to
registers.
If a function uses global
variables heavily
void test2(void)
{
unsigned int localerrs = errs;
localerrs += f();
localerrs += g();
errs = localerrs;
}
11. Try it out….
Write a c program to find sum of N integer
#include<stdio.h>
#include<conio.h>
main()
{
int n=10,sum=0,i;
for(i=0;i<n;i++)
sum=sum+i;
printf("Sum:%d",sum);
getch();
}
12. Try it out….
write a c program to find sum of N integer
#include<stdio.h>
#include<conio.h>
main()
{
int n=10,sum=0,i;
for(i=0;i<n;i++)
sum=sum+i;
printf("Sum:%d",sum);
getch();
}
#include<stdio.h>
#include<conio.h>
main()
{
unsigned int n=10,sum=0,i;
for(i=0;i<n;i++)
sum=sum+i;
printf("Sum:%d",sum);
getch();
}
13. #include <stdio.h>
int area=100;
int square(){
int x=10;
return x*x; }
int rectangle(){
int l=10,b=20;
int ar=2*(l+b);
return ar;
}
main()
{
area=area+square();
area=area+rectangle();
printf("area:%d",area);
}
Try it out
Write a program to find total area of a plot having a square shaped and rectangular shaped plot
global variable
14. #include <stdio.h>
int area=100;
int square(){
int x=10;
return x*x; }
int rectangle(){
int l=10,b=20;
int ar=2*(l+b);
return ar;
}
Try it out
Write a program to find total area of a plot having a square shaped and rectangular shaped plot
Making global variable local
main()
{
unsigned int localarea=area;
area=area+square();
area=area+rectangle();
printf("area:%d",area);
area=localarea;
}
15. Using array indices
switch ( queue ) {
case 0 : letter = 'W';
break;
case 1 : letter = 'S';
break;
case 2 : letter = 'U';
break;
}
if ( queue == 0 )
letter = 'W';
else if ( queue == 1
)
letter = 'S';
else
letter = 'U';
If you wished to set a variable to a particular character, depending upon the value of
something, you might do this:
16. Using array indices
A neater (and quicker) method is to simply use the value as an
index into a character array, e.g.:
static char *classes="WSU";
letter = classes[queue];
17. Control Statements
switch() instead of if...else...
For large decisions involving if...else...else..., like this:
if( val == 1)
dostuff1();
else if (val == 2)
dostuff2();
else if (val == 3)
dostuff3();
18. Control Statements
switch() instead of if...else...
It may be faster to use a switch
switch( val )
{
case 1: dostuff1(); break;
case 2: dostuff2(); break;
case 3: dostuff3(); break;
}
19. Try it out...
Write a c program to set index to english alphabet
#include<stdio.h>
#include<string.h>
main()
{char letter; int ch;
printf("enter the pos");
scanf("%d",&ch);
switch(ch){
case 0:letter='a';break;
case 1:letter='b'; break;
- - -
}
printf("%c",letter); }
20. Try it out...
write a c program to set index to english alphabet
#include<stdio.h>
#include<string.h>
main()
{char letter; int ch;
printf("enter the pos");
scanf("%d",&ch);
switch(ch){
case 0:letter='a';break;
case 1:letter='b'; break;
- - -
}
printf("%c",letter); }
#include<stdio.h>
#include<conio.h>
main()
{
char *classes="abcdefghi";
int i,ch,letter[26],queue=0;;
for(i=1;i<=26;i++) {
letter[i]=classes[queue];
queue++;
}
printf("enter the position");
scanf("%d",&ch);
printf("%c",letter[ch]);
getch(); }
21. Loop jamming
Never use two loops where one will suffice
for(i=0; i<100; i++){
stuff();
}
for(i=0; i<100; i++){
morestuff();
}
22. Loop jamming
It will be better to do this way:
for(i=0; i<100; i++){
stuff();
}
for(i=0; i<100; i++){
morestuff();
}
for(i=0; i<100; ++)
{
stuff();
morestuff();
}
23. Try it out….
main()
{int a[100],sum=0,product=1,i;
printf("enter elements into array");
for(i=0;i<5;i++)
scanf("%d",&a[i]);
for(i=0;i<5;i++)
sum=sum+a[i];
for(i=0;i<5;i++)
product=product*a[i];
printf("nsum:%d n
product:%d",sum,product); }
Write program to find sum and product of elements in a array
24. Try it out….
main()
{int a[100],sum=0,product=1,i;
printf("enter elements into array");
for(i=0;i<5;i++)
scanf("%d",&a[i]);
for(i=0;i<5;i++)
sum=sum+a[i];
for(i=0;i<5;i++)
product=product*a[i];
printf("nsum:%d n
product:%d",sum,product); }
Write program to find sum and product of elements in a array
for(i=0;i<5;i++)
{
scanf("%d",&a[i]);
sum=sum+a[i];
product=product*a[i];
}
25. Function Looping
If a function is often called from within a loop ,it may be possible to put that loop
inside the function to cut down the overhead of calling the function repeatedly
for(i=0 ; i<100 ; i++)
{
func(t,i);
}
-
-
-
void func(int w,d)
{
lots of stuff.
}
func(t);
-
-
void func(w)
{
for(i=0 ; i<100 ; i++)
{
//lots of stuff.
}
}
26. Try it out
Write a program to find sum of n numbers
#include<stdio.h>
#include<conio.h>
main()
{
int n=10,i,total=0;
for(i=0;i<10;i++)
total+=sum(i);
printf("n sum is:%d",total);
getch();
}
sum(int i)
{ int sum=0;
sum=sum+i;
}
27. Try it out
Write a program to find sum of n numbers
#include<stdio.h>
#include<conio.h>
main()
{
int n=10,i,total=0;
for(i=0;i<10;i++)
total += sum(i);
printf("n sum is:%d",total);
getch();
}
sum(int i)
{ int sum=0;
sum=sum+i;
}
main()
{ int total=0;
total=sum();
printf("n sum is:%d",total);
getch();
}
int sum()
{ int sum=0,i;
for(i=0;i<10;i++)
sum=sum+i;
return sum;
}
28. Faster for() loops
Ordinarily, we used to code a simple for() loop like this:
for( i=0; i<10; i++){ ... } [ i loops through the values 0,1,2,3,4,5,6,7,8,9 ]
If we needn't care about the order of the loop counter, we can do this instead:
for( i=10; ; i-- ) { ... }
Using this code, i loops through the values 9,8,7,6,5,4,3,2,1,0, and the loop should be
faster.
This works because it is quicker to process i--
29. Try it out….
Write a program to find factorial of a number
main()
{
int factorial=0,n=3;
factorial=fact(n);
clrscr();
printf("%d",factorial);
getch();
}
fact(int n)
{
int i,fact=1;
for(i=0;i<n;i++)
fact*=i;
return fact;
}
30. Try it out….
Write a program to find factorial of a number
main()
{
int factorial=0,n=3;
factorial=fact(n);
clrscr();
printf("%d",factorial);
getch();
}
fact(int n)
{
int i,fact=1;
for(i=0;i<n;i++)
fact*=i;
return fact;
}
main()
{ int
factorial=0,n=3;
factorial=fact(n);
clrscr();
printf("%d",factorial);
getch();
}
fact(int n)
{ int i,fact=1;
for(i=n;i!=0;i--)
fact*=i;
return fact*;
}
31. loop unrolling
● Small loops can be unrolled for higher performance.
● If the loop iterates only a few times, it can be fully unrolled, so that the loop
overhead completely disappears.
This can make a big difference. It is well known that unrolling loops can produce
considerable savings, e.g.:
for(i=0; i<3; i++){
something(i);
}
something(0);
something(1);
something(2);
32. Early loop breaking
It is often not necessary to process the entirety of a loop.
Example, if we are searching an array for a particular item, break out of the loop as
soon as we have got what we need.
Example: this loop searches a list of 10000 numbers to see if there is a -99 in it.
found = FALSE;
for(i=0;i<10000;i++)
{
if( list[i] == -99 )
{
found = TRUE;
}
}
if( found ) printf("Yes,
there is a -99. Hooray!n");
found = FALSE;
for(i=0; i<10000; i++)
{
if( list[i] == -99 )
{
found = TRUE;
break;
}
}
if( found )
printf("Yes, there is a -
99. Hooray!n");
33. Try it out
write a program to find position of an element in array
main( )
{ int arr[10],i,element,f=0;
printf("enter the elements");
for(i=0;i<10;i++)
scanf("%d",&arr[i]);
printf("enter the elements to search");
scanf("%d",&element);
for(i=0;i<10;i++)
{ if(arr[i]==element)
f=1;
}
if(f = =1) printf("element found");
}
34. Try it out
write a program to find position of an element in array
main( )
{ int arr[10],i,element,f=0;
printf("enter the elements");
for(i=0;i<10;i++)
scanf("%d",&arr[i]);
printf("enter the elements to search");
scanf("%d",&element);
for(i=0;i<10;i++)
{ if(arr[i]==element)
f=1;
}
if(f = =1) printf("element found");
}
early loop
breaking
main( ) {
int arr[10],i,element,f=0;
printf("enter the elements");
for(i=0;i<10;i++)
scanf("%d",&arr[i]);
printf("enter the elements to search");
scanf("%d",&element);
for(i=0;i<10;i++)
{ if(arr[i]==element)
{ f=1; break;}
}
if(f = =1) printf("element found");
}
35. Code Motion
Code motion involves identifying bits of code that occur within loops, but need only
be executed once during that particular loop.
For example,
void shift_char(char *str){
int i;
for(i=0;i<strlen(str);i++){
str[i]++;
}
}
void shift_char(char *str){
int i;
int len=strlen(str)
for(i=0;i<len;i++){
str[i]++;
}
}
36. Try it out
Write a program to search a character in a string
main()
{ char arr[10];
int i,ch,f=0,len;
printf("enter the string");
scanf("%s",&arr);
printf("enter the character to
search");
scanf("%s",&ch);
len=strlen(arr);
for(i=0;i<len;i++)
{ if(arr[i]==ch)
{ f=1; break;}
}
if(f==1) printf("element found");
}
function strlen is called once and set
to variable len
37. Function Design
● keep functions small and simple.
● This enables the compiler to perform optimizations
such as register allocation more efficiently.
function call overhead
● There is some limitation upto which words of argument
can be passed to a function in register.
● If the argument limitation is 4 then the 5th and
subsequent words are passed on the stack.
38. int f2(int a, int b, int c, int d, int e, int f)
{
return a + b + c + d + e + f;
}
int g2(void) {
return f2(1, 2, 3, 4, 5, 6);
}
The fifth and sixth parameters are stored on the stack in g2, and reloaded
in f2, costing two memory accesses per parameter.
int f1(int a, int b, int c, int d)
{
return a + b + c + d;
}
int g1(void) {
return f1(1, 2, 3, 4);
}
This code works fine.
39. Minimizing parameter passing overhead
To minimize the overhead of passing parameters to functions:
● Try to ensure that small functions take four or fewer arguments.This will reduce
the number of parameters and increase readability.
● Pass pointers to structures instead of passing the structure itself.
void print_data_of_a_structure ( const Thestruct *data_pointer)
{
...printf contents of the structure...
}
● Avoid functions with a variable number of parameters. Those functions effectively
pass all their arguments on the stack.
40. Try it out
write a c program to print content of a structure
struct student
{ int id;
char name[20];
float percentage };
void func(struct student *record);
int main()
{ struct student record;
record.id=1;
strcpy(record.name, "Raju");
record.percentage = 86.5;
func(&record);
return 0; }
void func(struct student *record)
{
printf(" Id is: %d n", record->id);
printf(" Name is: %s n", record->name);
printf(" Percentage is: %f n", record->percentage);
}
struct student
{ int id;
char name[20];
float percentage; };
void func(struct student record);
int main()
{ struct student record;
record.id=1;
strcpy(record.name, "Raju");
record.percentage = 86.5;
func(record);
return 0; }
void func(struct student record)
{ printf(" Id is: %d n", record.id);
printf(" Name is: %s n", record.name);
printf(" Percentage is: %f n",
record.percentage);
}
Pass pointers of a
structure
41. Inline function
● Inlining is the process by which the contents of a function are copied and pasted
instead of a traditional call to that function.
● This form of optimization avoids the overhead of function calls, by eliminating the
need to jump, create a new stack frame, and reverse this process at the end of the
function.
Inline int square(int x)
{
return x*x
}
#include<math.h>
double length(int x,int y)
{
return sqrt(square(x)*square(y))
}
42. Try it out
write a program to implement square root of x2+y2
#include<stdio.h>
#include<conio.h>
#include<math.h>
main()
{
int x=4,y=3,a;
a= sqrt(square(x)+square(y));
clrscr();
printf("n %d",a);
getch();
}
int square(int x)
{ return x*x;
}
#include <stdio.h>
#include<math.h>
int main() {
int tmp,x=4,y=3;
tmp = sqrt(square(x)+square(y));
printf("square val=%dn", tmp);
return 0;
}
int inline square(int x) {
return x*x;
}
Inline function
43. Advantage of using inline function
● No function call overhead
As the code is substituted directly ,there is no overhead like saving and storing
register
● Lower argument evaluation overhead
The overhead of parameter passing is generally lower,since it is not
necessary to copy variables