SlideShare uma empresa Scribd logo
1 de 22
For any help regarding C Programming Homework Help
Visit :- https://www.programminghomeworkhelp.com/ ,
Email :- support@programminghomeworkhelp.com or
call us at :- +1 678 648 4277 programminghomeworkhelp.com
Problem:1
Code profiling and registers. In this problem,wewill usesomebasiccodeprofilingto examine theeffectsofexplicitly declaring
variablesasregisters.Considerthefibonaccisequencegenerating functionfibonacci in prob1.c, whichisreproducedat theendof
this problemset(andcanbe downloadedfromStellar).The main() functionhandlesthecodeprofiling,callingfibonacci() many
timesandmeasuringtheaverageprocessor time.
(a) First, to get a baseline (without any explicitly declared registers), compile and run prob1.c. Code profiling is one of the rare
cases where using a debugger like gdb is discouraged, because the debugger’soverhead can impact the execution time.
Also, wewantto turnoffcompiler optimization. Please use the following commands to compile and run the program:
dweller@dwellerpc:~$ gcc -O0 -Wall prob1.c -o prob1.o dweller@dwellerpc:~$
./prob1.o
Avg. execution time: 0.000109 msec ← exampleoutput
dweller@dwellerpc:~$
How long does a single iteration take to execute (on average)?
(b) Now, modify the fibonacci() function by making the variables a, b, and c register variables. Recompile and run the code. How
long does a single iteration take now, on average? Turn in a printout of your modified code (the fibonacci() function itself would
suffice).
(c) Modify the fibonacci() function onemoretime bymakingthe variable n alsoaregister variable. Recompileandrunthe codeonce
more.Howlongdoesasingleiteration takewith all fourvariablesasregister variables?
(d) Commentonyourobservedresults.What canyouconcludeaboutusingregistersin your code?
Problem :2
We are writing a simple searchable dictionary using modular programming. First, the program reads a file containing words and their
definitions into an easily searchable data structure. Then, the user can type a word, and the program will search the dictionary, and
assumingthewordis found,outputsthedefinition.The programproceedsuntiltheuserchoosesto quit.
Wesplit thecodeintoseveralfiles:main.c, dict.c, anddict.h. The contentsofthesefilesare describedbrieflybelow.
Practical Programming in C
programminghomeworkhelp.com
main.c: dict.c: dict.h:
#include <stdio.h> #include "dict.h" /* data structure
#include <stdlib.h> for the dictionary */
#include "dict.h" /* data structure char * thedictionary[1000];
for the dictionary */
int main() { char * thedictionary[1000]; /* declarations */
... void loaddictionary();
} void load dictionary(){
...
char * lookup(char []);
}
char * lookup(char []) {
...
}
Answerthefollowingquestionsbasedontheaboveprogramstructure.
(a) In implementingthis program,you wantto accesstheglobal variablethe dictionary from main.c, aswellasfromdict.c. However,
due to the header file’s inclusion in both source documents, the variable gets declared in both places, creating an ambiguity. How
wouldyou resolvethisambiguity?
(b) Now, suppose you want to restrict the dictionary data structure to be accessible only from functions in dict.c. You remove the
declaration from dict.h. Is it still possible to directly access or modify the variable from main.c, even without the declaration in
dict.h? If so, howwouldyouensurethedatastructurevariableremains private?
(c) Congratulations! You’re done and ready to compile your code. Write the command line that you should use to compile this code
(usinggcc). Let’scallthedesiredoutput program dictionary.o.
Problem : 3
Both thefor loop andthedo-while loop canbetransformedintoasimplewhile loop.Foreach ofthefollowingexamples,write
equivalentcodeusingawhile loop instead.
(a)int f a c t o r i a l ( int n) {
int i , re t = 1 ;
for ( i = 2 ; i <= n ; i ++) re t ∗= i ;
return re t ;
} programminghomeworkhelp.co
m
double q ; int n = 0 ; do {
q = rand double ( ) ; n++;
} while ( q >= p ) ;
return n ;
}
Note:You only needto modifythesample geometric rv()function.
(b)#include <s t d l i b . h>
double rand double () {
/∗ g e ne rate random number in [ 0 , 1 ) ∗/
double re t = ( double ) rand ( ) ;
return re t /(RAND MAX+1 );
}
int s ampl e g e o me tri c rv ( double p) {
programminghomeworkhelp.com
Problem:4
’wc’isaunix utility that displaythecountofcharacters,wordsandlinespresentin afile.If no fileisspecifiedit readsfromthe
standard input. If more than one file name is specified it displays the counts for each file along with the filename. In this
problem,wewill beimplementingwc.
One of the ways to build a complex program is to develop it iteratively, solving one problem at a time and testing it
throroughly.Forthis problem,startwith thefollowingshellandthen iterativelyaddthemissingcomponents.
#include <s t d i o . h>
#include <s t d l i b . h>
int main ( int argc , char ∗ argv [ ] )
{
FILE∗ fp=NULL ;
int n f i l e s =− argc ; /∗ i g no re the name o f the program
int i t s e l f ∗/
/∗ i g no re the name o f the program i t s e
lf ∗/
char
∗
cha
r
argidx =1;
c u r r f i l
e=""; c ;
/∗ count o f words , l i n e s , c h a ra c te rs ∗/
unsigned long nw=0 , nl =0 , nc =0;
i f ( n f i l e s ==0)
{
fp=s tdi n ; /∗ standard input ∗/ n f i l e s ++;
}
else /∗ s e t to f i r s t ∗/
{
c u r r f i l e=argv [ argidx ++]; fp=fopen ( c u r r f i l e ,
"r") ;
}
while ( n f i l e s >0) /∗ f i l e s l e f t >0∗/
{
i f ( fp==NULL)
{
programminghomeworkhelp.com
f p r i n t f ( s tde rr , "Unable to open inputn" ) ; e x i t (
−1 );
}
nc=nw=n l =0;
while (( c=g etc ( fp ))! =EOF)
{
/∗TODO: FILL HERE
pro c e s s the f i l e using g etc ( fp )
∗/
}
p r i n t f ( " ld sn" , nc , c u r r f i l e ) ;
/∗ next f i l e i f e x i s t s ∗/ n f i l e s −−;
i f ( n f i l e s >0)
{
c u r r f i l e=argv [ argidx ++];
fp =fopen ( c u r r f i l e , "r") ;
}
}
return 0 ;
}
Hint: In order to count words, count the transitions from non-white spaceto white space characters.
programminghomeworkhelp.com
"FLORIDA" 590800
"NEW HAMPSHIRE" 421986
..........
Problem 3.5
In this problem, we will be reading in formatted data and generating a report. One of the common formats for
interchangeofformatted data is ’tab delimited’whereeachline corresponds to asinglerecord.The individual fieldsof
the record are separated by tabs. For this problem, download the file stateoutflow0708.txt from Stellar. This
containsthe emigrationof people fromindividual states. The first rowofthe filecontainsthe columnheadings.There
areeightself explanatoryfields.Your task isto readthefileusingfscanfandgenerateareport outlining the migration
of people from Massachusetts to all the other states. Use the field ”Aggr AGI” to report the numbers. Also, at the
end, display a total and verify it is consistent with the one shown below. An example report should look like the
following:
STATE TOTAL
Total 4609483
Makesurethat thefieldsarealigned.
programminghomeworkhelp.com
CodelistingforProblem:1:prob1.c
#include <s t d l i b . h> #include <s t d i o . h> #include <time
. h>
#define NMAX 25
static unsigned int r e s u l t s b u f f e r [NMAX] ;
void f i b o n a c c i ()
{
/∗ here are the v a r i a b l e s to s e t as r e g i s t e r s ∗/
unsigned int a = 0 ; unsigned int b = 1 ; unsigned int c ;
int n ;
/∗ do not e d i t below t h i s l i n e ∗/ r e s u l t s b u f f e r [ 0 ] = a ;
r e s u l t s b u f f e r [ 1 ] = b ;
for ( n = 2 ; n < NMAX; n++) {
c = a + b ;
r e s u l t s b u f f e r [ n ] = c ; /∗ s t o r e code in r e s u l t s b u f f e r ∗/ a = b ;
b = c ;
}
}
int main ( void ) {
int n , n t e s t s = 10000000 ; c l o c k t ts ta rt , tend ; double favg
;
/∗ do p r o f i l i n g ∗/ t s t a r t = c l o c k ( ) ;
programminghomeworkhelp.com
for ( n = 0 ; n < n t e s t s ; n++) f i b o n a c c i ( ) ;
tend = c l o c k ( ) ;
/∗ end p r o f i l i n g ∗/
/∗ compute average e xe c uti o n time ∗/
favg = (( double )( tend − t s t a r t ))/CLOCKS PER SEC/ n t e s t s ;
/∗ pri nt avg e xe c uti o n time in m i l l i s e c o n d s ∗/ p r i n t f ( "Avg.
execution time: g msecn" , favg ∗1 0 0 0 ) ; return 0 ;
}
programminghomeworkhelp.com
Problem:1
Code profiling and registers. In this problem, we will use some basic code profiling to examine the effects of
explicitly declaring variables as registers. Consider the fibonacci sequence generating function fibonacci in prob1.c,
which is reproduced at the end of this problem set (and can be downloaded from Stellar). The main() function
handles the code profiling, calling fibonacci() many times and measuring the average processor time.
(a) First, to get a baseline (without any explicitly declared registers), compile and run prob1.c. Code profiling is one
of the rare cases where using a debugger like gdb is discouraged, because the debugger’s overhead can impact
the execution time. Also, we want to turn off compiler optimization. Please use the following commands to
compile and run the program:
dweller@dwellerpc:~$ gcc -O0 -Wall prob1.c -o prob1.o dweller@dwellerpc:~$ ./prob1.o
Avg. execution time: 0.000109 msec ← example output
dweller@dwellerpc:~$
How long does a single iteration take to execute (on average)?
Answer: On my 64-bit machine (results may differ slightly for 32-bit machines), the original
fibonacci() function took 0.000109 msec onaverage.
(b) Now, modify the fibonacci() function by making the variables a, b, and c register variables. Recompile and run the
code. How long does a single iteration take now, on average? Turn in a printout of your modified code (the
fibonacci() function itself wouldsuffice).
Answer: Here’s the modified fibonacci() function for part (b):
void f ib on acci ()
{
/∗ here are the va ri ab l es to set as r e g i s t e r s ∗/
register unsigned int a = 0 ; register unsigned int b = 1 ;
register unsigned int c ;
int n ;
/∗ do not e d i t below t h i s l i n e ∗/ r e s u l t s b u f f e r [ 0 ] = a ;
r e s u l t s b u f f e r [ 1 ] = b ;
for ( n = 2 ; n < NMAX; n++) {
c = a + b;
Solutions
programminghomeworkhelp.com
r e s u l t s b u f f e r [ n ] = c ; /∗ store code in r e s u l t s buffe r ∗/ a = b ;
b = c ;
}
}
On my 64-bit machine (results may differ slightly for 32-bit machines), the modified function took 0.000111 msec on
average.
(c) Modify the fibonacci() function one more time by making the variable n also a register variable. Recompile and run the
code once more. How long does a single iteration take with all four variables as register variables?
Answer: Here’s the modified fibonacci() function for part (c):
void f ib on acci ()
{
/∗ here are the va ri ab l es to set as r e g i s t e r s ∗/
register unsigned int a = 0 ; register unsigned int b = 1 ;
register unsigned int c ; register int n ;
/∗ do not e d i t below t h i s l i n e ∗/ r e s u l t s b u f f e r [ 0 ] = a ;
r e s u l t s b u f f e r [ 1 ] = b ;
for ( n = 2 ; n < NMAX; n++) {
c = a + b;
r e s u l t s b u f f e r [ n ] = c ; /∗ store code in r e s u l t s buffe r ∗/ a = b ;
b = c ;
}
}
On my 64-bit machine (results may differ slightly for 32-bit machines), the further modified
fibonacci() function took 3.4e-05 msec onaverage.
(d) Comment on your observed results. What can you conclude about using registers in your code?
Answer: The observed results suggest that storing some variables in a register vs. in memory may or may not impact
performance. In particular, storing a, b, and c in registers do not appear to improve the performance at all, while
storing nin a register improves performance by a factor of 3.
programminghomeworkhelp.com
programminghomeworkhelp.com
Problem:2
We are writing a simple searchable dictionary using modular programming. First, the program reads a file
containing words and their definitions into an easily searchable data structure. Then, the user can type a word,
and the program will search the dictionary, and assuming the word is found, outputs the definition. The program
proceeds until the user chooses toquit.
We split the code into several files: main.c, dict.c, and dict.h. The contents of these files are described briefly
below.
main.c: dict.c: dict.h:
#include <stdio.h> #include "dict.h" /* data structure
#include <stdlib.h> for the dictionary */
#include "dict.h" /* data structure char * thedictionary[1000];
for the dictionary */
int main() { char * thedictionary[1000]; /* declarations */
... void loaddictionary();
} void load dictionary(){
...
char * lookup(char []);
}
char * lookup(char []) {
...
}
Answer the following questions based on the above program structure.
(a) In implementing this program, you want to access the global variable the dictionary from main.c, as well
as from dict.c. However, due to the header file’s inclusion in both source documents, the variable gets
declared in both places, creating an ambiguity. How would you resolve this ambiguity?
Answer: Adding the extern keyword immediately before the declaration in dict.h resolves the ambiguity,
causing both files to reference the variable declared in dict.c.
(b) Now, suppose you want to restrict the dictionary data structure to be accessible only from functions in
dict.c. You remove the declaration from dict.h. Is it still possible to directly access or modify the variable
from main.c, even without the declaration in dict.h? If so, how would you ensure the data structure
variable remains private?
Answer: Simply removing the declaration from dict.h does not make the variable private to dict.c. One
could simply add an extern declaration to main.c or any other source file and still be able to access or
modify the dictionary directly. In order to prevent direct access, the dictionary should be declared with the
statickeyword in dict.c.
(c) Congratulations! You’re done and ready to compile your code. Write the command line that you should
use to compile this code (using gcc). Let’s call the desired output program dictionary.o.
Answer: gcc -g -O0 -Wall main.c dict.c -o dictionary.o. Note that the order of
main.c and dict.cis not important, as long as they are both specified.
programminghomeworkhelp.com
Problem :3
Both the for loop and the do-while loop can be transformed into a simple whileloop. For each of the
following examples, write equivalent code using a while loopinstead.
(a) int f a c t o r i a l ( int n) {
int i , r e t = 1 ;
for ( i = 2 ; i <= n ; i ++) r e t ∗= i ;
return r e t ;
}
int f a c t o r i a l ( int n) { int i = 1 , r e t = 1 ; while (++ i <= n )
r e t ∗= i ;
return r e t ;
}
(b) #include <s t d l i b . h>
double rand double ( ) {
/∗ generate random number in [0 ,1 ) ∗/
double ret = (double) rand ( ) ;
return ret /(RANDMAX+1);
}
int sample geometric rv (double p) {
double q ; int n = 0 ; do {
q = rand double ( ) ; n++;
} while ( q >= p ) ;
return n ;
}
Note: You only need to modify the sample geometric rv()function. Answer:
int sample geometric rv (double p) {
double q ;
int n = 0 , c o n d i t i o n = 1 ;
while ( condition ) { q = rand double ( ) ; n++;
condition = q >= p ;
}
return n ;
programminghomeworkhelp.com
Problem:4
’wc’ is a unix utility that display the count of characters, words and lines present in a file. If no file is specified
it reads from the standard input. If more than one file name is specified it displays the counts for each file along
with the filename. In this problem, we will be implementingwc.
One of the ways to build a complex program is to develop it iteratively, solving one problem at a time and
testing it throroughly. For this problem, start with the following shell and then iteratively add the missing
components.
#include <stdio . h>
#include <s t d l i b . h>
int main ( int argc , char∗ argv [ ] )
{
FILE∗ fp=NULL;
int n f i l e s =− argc ; /∗ ignore the name of the program
int i t s e l f ∗/
/∗ ignore the name of the program i t s e l f ∗/
char∗
char
ar g i dx =1; c u r r f i l e=""; c
;
/∗count of words , l i nes , characters ∗/
unsigned long nw=0, nl =0,nc=0;
if ( n f i l e s ==0)
{
fp=s tdin ; /∗standard input ∗/ n f i l e s ++;
}
else /∗ s e t to f i r s t ∗/
{
c u r r f i l e=argv [ arg idx ++]; fp=fopen ( c u r r fi l e , "
r") ;
}
while( n f i l e s >0) /∗ f i l e s l e f t >0∗/
{
if ( fp==NULL)
{
f p r i n t f ( stderr , "Unable to open inputn") ; exi t ( −1);
}
programminghomeworkhelp.com
programminghomeworkhelp.com
nc=nw=nl =0;
while (( c=getc ( fp ))! =EOF)
{
/∗TODO: FILL HERE
process the f i l e using getc ( fp )
∗/
}
p r i n t f (" ld sn", nc , c u r r f i l e ) ;
/∗next f i l e i f e x i s t s ∗/ nf i l e s −−;
if ( n f i l e s >0)
{
c u r r f i l e=argv [ arg idx ++];
fp =fopen ( c u r r f i l e , "r") ;
}
}
return 0;
}
Hint: In order to count words, count the transitions from non-white space to white space characters.
Answer: Here’s the code with the shell filled in
/∗
6 . 087 IAP Spring 2010
Problem s e t 2
∗/
#include <stdio . h>
#include <s t d l i b . h>
int main ( int argc , char∗ argv [ ] )
{
FILE∗ fp=NULL;
int n f i l e s =− argc ;
int
/∗ ignore the name of the program i t s e l f ∗/
/∗ ignore the name of the program i t s e l f ∗/
char
∗
char
ar g i dx =1; c u r r f i l e=""; c
;
/∗ fol low ing used to count words ∗/
enumstate {INSIDE ,OUTSIDE};
enumstate cu rrstate=INSIDE ;
/∗count of words , l i nes , characters ∗/
unsigned long nw=0, nl =0,nc=0;
if ( n f i l e s ==0)
{
fp=s tdin ; /∗standard input ∗/ n f i l e s ++;
}
else /∗ s e t to f i r s t ∗/
{
c u r r f i l e=argv [ arg idx ++]; fp=fopen ( c u r r fi l e , "r") ;
}
while( n f i l e s >0) /∗ f i l e s l e f t >0∗/
{
if ( fp==NULL)
{
f p r i n t f ( stderr , "Unable to open inputn") ; exi t ( −1);
}
/∗TODO: FILL HERE
process the f i l e using getc ( fp )
∗/ nc=nw=nl=0;
while (( c=getc ( fp ))! =EOF)
programminghomeworkhelp.com
{
nc++;
if ( c==’n’)
{
nl++;
}
if ( isspace ( c ))
{
if ( curr state==INSIDE) nw++;
currstate=OUTSIDE;
}
else
{
currs tate=INSIDE ;
}
}
/∗update to ta l s ∗/
p r i n t f (" ld ld ld sn", nl ,nw, nc , c u r r f i l e ) ;
/∗next f i l e i f e x i s t s ∗/ nf i l e s −−;
if ( n f i l e s >0)
{
c u r r f i l e=argv [ arg idx ++];
fp =fopen ( c u r r f i l e , "r") ;
}
}
}
programminghomeworkhelp.com
"FLORIDA" 590800
"NEW HAMPSHIRE" 421986
..........
Problem:5
In this problem, we will be reading in formatted data and generating a report. One of the common formats for
interchange of formatted data is ’tab delimited’ where each line corresponds to a single record. The individual
fields of the record are separated by tabs. For this problem, download the file stateoutflow0708.txt from Stellar.
This contains the emigration of people from individual states. The first row of the file contains the column
headings. There are eight self explanatory fields. Your task is to read the file using fscanf and generate a report
outlining the migration of people from Massachusetts to all the other states. Use the field ”Aggr AGI” to report
the numbers. Also, at the end, display a total and verify it is consistent with the one shown below. An example
report should look like the following:
STATE TOTAL
Total 4609483
Make sure that the fields are aligned.
Answer: Here’s the code with the shell filled in
#include <stdio . h> #include <s t d l i b . h> #include <str in g .
h>
#define STRSIZE 100
#define NFIELDS 9
int main ( )
{
char i n p u t f i l e []= "stateoutflow0708.txt";
/∗ define a l l the f i e l d s ∗/
char state code org [ STRSIZE ] ;
programminghomeworkhelp.com
/∗ parse the f i e l d s ∗/
pr i n tf (" -30s, 6sn","STATE","TOTAL") ;
pr i n tf ("---------------------------------------n") ;
while( f ge ts ( line , STRSIZE∗NFIELDS, fp ))
{
f i e l d s r e a d=sscanf ( line , " s s s s s
s d
s t a t e c o d e o r g , cou nt ry cod e o
rg , s t a t e c o d e d e s t , country c
ode dest , state abbrv ,
state name , &return num ,
&exmpt num , &aggr agi ) ;
if ( strcmp ( state code org , ""25"")==0)
programminghomeworkhelp.com
char
char
char
country code org [STRSIZE ] ; sta te co de des
t [STRSIZE ] ; country code dest [STRSIZE ] ; s
tate abbrv [ STRSIZE ] ;
char state name [ STRSIZE ] ;
char l i n e [ STRSIZE∗NFIELDS] ;
int int int long
return num =0; exmpt num=0;
aggr agi =0;
tot al =0;
/∗ f i l e related ∗/
int f i e l d s r e a d =0;
FILE∗ fp=fopen ( i np u t fi l e , "r") ;
if ( fp==NULL)
{
f p r i n t f ( stderr , "Cannot open filen") ; ex it ( −1);
}
/∗ skip f i r s t l i n e ∗/
f g e ts ( line , STRSIZE∗NFIELDS, fp ) ;
/∗ print the header ∗/
programminghomeworkhelp.com
{
pr i n tf (" -30s, 6dn", state name , aggr agi ) ; t
o t al += aggr agi ;
}
}
/∗ print the header ∗/
pr i n tf ("----------------------------------------n") ;
pr i n tf (" -30s, 6lun","TOTAL", t ot a l ) ; f c l
o s e ( fp ) ;
return 0;
}
Code listing for Problem 3.1: prob1.c
#include <s td l i b . h>
#include <stdio . h>
#include <time . h>
#define NMAX 25
static unsigned int r e s u l t s b u f f e r [NMAX];
void f ib on acc i ()
{
/∗ here are the va ri ab l es to set as r e g i s t e r s ∗/
unsigned int a = 0 ; unsigned int b = 1 ; unsigned int c
;
int n ;
/∗ do not e d i t below t h i s l i n e ∗/ r e s u l t s b u f f e r [ 0 ] = a ;
r e s u l t s b u f f e r [ 1 ] = b ;
for ( n = 2 ; n < NMAX; n++) {
c = a + b;
r e s u l t s b u f f e r [ n ] = c ; /∗ store code in r e s u l t s buffe r ∗/ a = b ;
b = c ;
}
}
int main ( void ) {
int n , n t e s t s = 10000000 ; c l o c k t t s t a r t , tend ; double
favg ;
/∗ do p r o f i l i n g ∗/ ts t a r t = clock ( ) ;
for ( n = 0 ; n < n t e s t s ; n++) fi bon acc i ( ) ;
tend = clock ( ) ;
/∗ end p r o f i l i n g ∗/
/∗ compute average execution time ∗/
favg = (( double)( tend − t s t a r t ))/CLOCKS PER SEC/ ntests ;
/∗ print avg execution time in mi l l i seco nd s ∗/ pr i n t f ( "Avg. execution time:
g msecn", favg ∗1000); return 0;
}
programminghomeworkhelp.com

Mais conteúdo relacionado

Mais procurados

Computer Science Programming Assignment Help
Computer Science Programming Assignment HelpComputer Science Programming Assignment Help
Computer Science Programming Assignment HelpProgramming Homework Help
 
Python programing
Python programingPython programing
Python programinghamzagame
 
C aptitude.2doc
C aptitude.2docC aptitude.2doc
C aptitude.2docSrikanth
 
Maharishi University of Management (MSc Computer Science test questions)
Maharishi University of Management (MSc Computer Science test questions)Maharishi University of Management (MSc Computer Science test questions)
Maharishi University of Management (MSc Computer Science test questions)Dharma Kshetri
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to pythonMarian Marinov
 
Introduction to Recursion (Python)
Introduction to Recursion (Python)Introduction to Recursion (Python)
Introduction to Recursion (Python)Thai Pangsakulyanont
 
仕事で使うF#
仕事で使うF#仕事で使うF#
仕事で使うF#bleis tift
 
Game of Life - Polyglot FP - Haskell - Scala - Unison - Part 3
Game of Life - Polyglot FP - Haskell - Scala - Unison - Part 3Game of Life - Polyglot FP - Haskell - Scala - Unison - Part 3
Game of Life - Polyglot FP - Haskell - Scala - Unison - Part 3Philip Schwarz
 
C interview question answer 2
C interview question answer 2C interview question answer 2
C interview question answer 2Amit Kapoor
 
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part ...
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part ...Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part ...
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part ...Philip Schwarz
 
Docase notation for Haskell
Docase notation for HaskellDocase notation for Haskell
Docase notation for HaskellTomas Petricek
 

Mais procurados (20)

Computer Science Programming Assignment Help
Computer Science Programming Assignment HelpComputer Science Programming Assignment Help
Computer Science Programming Assignment Help
 
CPP Homework Help
CPP Homework HelpCPP Homework Help
CPP Homework Help
 
Python programing
Python programingPython programing
Python programing
 
Cpp Homework Help
Cpp Homework Help Cpp Homework Help
Cpp Homework Help
 
Captitude 2doc-100627004318-phpapp01
Captitude 2doc-100627004318-phpapp01Captitude 2doc-100627004318-phpapp01
Captitude 2doc-100627004318-phpapp01
 
C aptitude.2doc
C aptitude.2docC aptitude.2doc
C aptitude.2doc
 
CPP Homework Help
CPP Homework HelpCPP Homework Help
CPP Homework Help
 
Rx workshop
Rx workshopRx workshop
Rx workshop
 
Maharishi University of Management (MSc Computer Science test questions)
Maharishi University of Management (MSc Computer Science test questions)Maharishi University of Management (MSc Computer Science test questions)
Maharishi University of Management (MSc Computer Science test questions)
 
Python
PythonPython
Python
 
Python 3000
Python 3000Python 3000
Python 3000
 
Functions
FunctionsFunctions
Functions
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
 
Introduction to Recursion (Python)
Introduction to Recursion (Python)Introduction to Recursion (Python)
Introduction to Recursion (Python)
 
Computer Network Assignment Help
Computer Network Assignment HelpComputer Network Assignment Help
Computer Network Assignment Help
 
仕事で使うF#
仕事で使うF#仕事で使うF#
仕事で使うF#
 
Game of Life - Polyglot FP - Haskell - Scala - Unison - Part 3
Game of Life - Polyglot FP - Haskell - Scala - Unison - Part 3Game of Life - Polyglot FP - Haskell - Scala - Unison - Part 3
Game of Life - Polyglot FP - Haskell - Scala - Unison - Part 3
 
C interview question answer 2
C interview question answer 2C interview question answer 2
C interview question answer 2
 
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part ...
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part ...Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part ...
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - Part ...
 
Docase notation for Haskell
Docase notation for HaskellDocase notation for Haskell
Docase notation for Haskell
 

Semelhante a C Programming Homework Help

Kamil witecki asynchronous, yet readable, code
Kamil witecki asynchronous, yet readable, codeKamil witecki asynchronous, yet readable, code
Kamil witecki asynchronous, yet readable, codeKamil Witecki
 
Cpp17 and Beyond
Cpp17 and BeyondCpp17 and Beyond
Cpp17 and BeyondComicSansMS
 
C Programming Language Tutorial for beginners - JavaTpoint
C Programming Language Tutorial for beginners - JavaTpointC Programming Language Tutorial for beginners - JavaTpoint
C Programming Language Tutorial for beginners - JavaTpointJavaTpoint.Com
 
Introduction to Compiler Development
Introduction to Compiler DevelopmentIntroduction to Compiler Development
Introduction to Compiler DevelopmentLogan Chien
 
(8) cpp abstractions separated_compilation_and_binding_part_i
(8) cpp abstractions separated_compilation_and_binding_part_i(8) cpp abstractions separated_compilation_and_binding_part_i
(8) cpp abstractions separated_compilation_and_binding_part_iNico Ludwig
 
20145-5SumII_CSC407_assign1.htmlCSC 407 Computer Systems II.docx
20145-5SumII_CSC407_assign1.htmlCSC 407 Computer Systems II.docx20145-5SumII_CSC407_assign1.htmlCSC 407 Computer Systems II.docx
20145-5SumII_CSC407_assign1.htmlCSC 407 Computer Systems II.docxeugeniadean34240
 
Best C++ Programming Homework Help
Best C++ Programming Homework HelpBest C++ Programming Homework Help
Best C++ Programming Homework HelpC++ Homework Help
 
Optimization in Programming languages
Optimization in Programming languagesOptimization in Programming languages
Optimization in Programming languagesAnkit Pandey
 
EMBEDDED SYSTEMS 4&5
EMBEDDED SYSTEMS 4&5EMBEDDED SYSTEMS 4&5
EMBEDDED SYSTEMS 4&5PRADEEP
 

Semelhante a C Programming Homework Help (20)

Kamil witecki asynchronous, yet readable, code
Kamil witecki asynchronous, yet readable, codeKamil witecki asynchronous, yet readable, code
Kamil witecki asynchronous, yet readable, code
 
Csdfsadf
CsdfsadfCsdfsadf
Csdfsadf
 
C
CC
C
 
C
CC
C
 
Cpp17 and Beyond
Cpp17 and BeyondCpp17 and Beyond
Cpp17 and Beyond
 
C Programming Language Tutorial for beginners - JavaTpoint
C Programming Language Tutorial for beginners - JavaTpointC Programming Language Tutorial for beginners - JavaTpoint
C Programming Language Tutorial for beginners - JavaTpoint
 
Introduction to Compiler Development
Introduction to Compiler DevelopmentIntroduction to Compiler Development
Introduction to Compiler Development
 
C++ Homework Help
C++ Homework HelpC++ Homework Help
C++ Homework Help
 
C++ Core Guidelines
C++ Core GuidelinesC++ Core Guidelines
C++ Core Guidelines
 
C notes.pdf
C notes.pdfC notes.pdf
C notes.pdf
 
Programming in C
Programming in CProgramming in C
Programming in C
 
(8) cpp abstractions separated_compilation_and_binding_part_i
(8) cpp abstractions separated_compilation_and_binding_part_i(8) cpp abstractions separated_compilation_and_binding_part_i
(8) cpp abstractions separated_compilation_and_binding_part_i
 
CppTutorial.ppt
CppTutorial.pptCppTutorial.ppt
CppTutorial.ppt
 
Cpp tutorial
Cpp tutorialCpp tutorial
Cpp tutorial
 
20145-5SumII_CSC407_assign1.htmlCSC 407 Computer Systems II.docx
20145-5SumII_CSC407_assign1.htmlCSC 407 Computer Systems II.docx20145-5SumII_CSC407_assign1.htmlCSC 407 Computer Systems II.docx
20145-5SumII_CSC407_assign1.htmlCSC 407 Computer Systems II.docx
 
Best C++ Programming Homework Help
Best C++ Programming Homework HelpBest C++ Programming Homework Help
Best C++ Programming Homework Help
 
Optimization in Programming languages
Optimization in Programming languagesOptimization in Programming languages
Optimization in Programming languages
 
88 c-programs
88 c-programs88 c-programs
88 c-programs
 
EMBEDDED SYSTEMS 4&5
EMBEDDED SYSTEMS 4&5EMBEDDED SYSTEMS 4&5
EMBEDDED SYSTEMS 4&5
 
Ppt of c vs c#
Ppt of c vs c#Ppt of c vs c#
Ppt of c vs c#
 

Mais de Programming Homework Help

Design and Analysis of Algorithms Assignment Help
Design and Analysis of Algorithms Assignment HelpDesign and Analysis of Algorithms Assignment Help
Design and Analysis of Algorithms Assignment HelpProgramming Homework Help
 
programminghomeworkhelp.com_Advanced Algorithms Homework Help.pptx
programminghomeworkhelp.com_Advanced Algorithms Homework Help.pptxprogramminghomeworkhelp.com_Advanced Algorithms Homework Help.pptx
programminghomeworkhelp.com_Advanced Algorithms Homework Help.pptxProgramming Homework Help
 

Mais de Programming Homework Help (20)

C Assignment Help
C Assignment HelpC Assignment Help
C Assignment Help
 
Python Question - Python Assignment Help
Python Question - Python Assignment HelpPython Question - Python Assignment Help
Python Question - Python Assignment Help
 
Best Algorithms Assignment Help
Best Algorithms Assignment Help Best Algorithms Assignment Help
Best Algorithms Assignment Help
 
Design and Analysis of Algorithms Assignment Help
Design and Analysis of Algorithms Assignment HelpDesign and Analysis of Algorithms Assignment Help
Design and Analysis of Algorithms Assignment Help
 
Algorithm Homework Help
Algorithm Homework HelpAlgorithm Homework Help
Algorithm Homework Help
 
programminghomeworkhelp.com_Advanced Algorithms Homework Help.pptx
programminghomeworkhelp.com_Advanced Algorithms Homework Help.pptxprogramminghomeworkhelp.com_Advanced Algorithms Homework Help.pptx
programminghomeworkhelp.com_Advanced Algorithms Homework Help.pptx
 
Algorithm Homework Help
Algorithm Homework HelpAlgorithm Homework Help
Algorithm Homework Help
 
Algorithms Design Assignment Help
Algorithms Design Assignment HelpAlgorithms Design Assignment Help
Algorithms Design Assignment Help
 
Algorithms Design Homework Help
Algorithms Design Homework HelpAlgorithms Design Homework Help
Algorithms Design Homework Help
 
Algorithm Assignment Help
Algorithm Assignment HelpAlgorithm Assignment Help
Algorithm Assignment Help
 
Algorithm Homework Help
Algorithm Homework HelpAlgorithm Homework Help
Algorithm Homework Help
 
C Homework Help
C Homework HelpC Homework Help
C Homework Help
 
C Homework Help
C Homework HelpC Homework Help
C Homework Help
 
Algorithm Assignment Help
Algorithm Assignment HelpAlgorithm Assignment Help
Algorithm Assignment Help
 
Algorithm Homework Help
Algorithm Homework HelpAlgorithm Homework Help
Algorithm Homework Help
 
Computer Science Assignment Help
Computer Science Assignment Help Computer Science Assignment Help
Computer Science Assignment Help
 
Algorithm Assignment Help
Algorithm Assignment HelpAlgorithm Assignment Help
Algorithm Assignment Help
 
C Programming Homework Help
C Programming Homework HelpC Programming Homework Help
C Programming Homework Help
 
Computational Assignment Help
Computational Assignment HelpComputational Assignment Help
Computational Assignment Help
 
Computation Assignment Help
Computation Assignment Help Computation Assignment Help
Computation Assignment Help
 

Último

Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...christianmathematics
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxAreebaZafar22
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17Celine George
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptxMaritesTamaniVerdade
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...ZurliaSoop
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseAnaAcapella
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfPoh-Sun Goh
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxVishalSingh1417
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfAdmir Softic
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxheathfieldcps1
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhikauryashika82
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docxPoojaSen20
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...Nguyen Thanh Tu Collection
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.MaryamAhmad92
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701bronxfugly43
 

Último (20)

Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please Practise
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docx
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701
 

C Programming Homework Help

  • 1. For any help regarding C Programming Homework Help Visit :- https://www.programminghomeworkhelp.com/ , Email :- support@programminghomeworkhelp.com or call us at :- +1 678 648 4277 programminghomeworkhelp.com
  • 2. Problem:1 Code profiling and registers. In this problem,wewill usesomebasiccodeprofilingto examine theeffectsofexplicitly declaring variablesasregisters.Considerthefibonaccisequencegenerating functionfibonacci in prob1.c, whichisreproducedat theendof this problemset(andcanbe downloadedfromStellar).The main() functionhandlesthecodeprofiling,callingfibonacci() many timesandmeasuringtheaverageprocessor time. (a) First, to get a baseline (without any explicitly declared registers), compile and run prob1.c. Code profiling is one of the rare cases where using a debugger like gdb is discouraged, because the debugger’soverhead can impact the execution time. Also, wewantto turnoffcompiler optimization. Please use the following commands to compile and run the program: dweller@dwellerpc:~$ gcc -O0 -Wall prob1.c -o prob1.o dweller@dwellerpc:~$ ./prob1.o Avg. execution time: 0.000109 msec ← exampleoutput dweller@dwellerpc:~$ How long does a single iteration take to execute (on average)? (b) Now, modify the fibonacci() function by making the variables a, b, and c register variables. Recompile and run the code. How long does a single iteration take now, on average? Turn in a printout of your modified code (the fibonacci() function itself would suffice). (c) Modify the fibonacci() function onemoretime bymakingthe variable n alsoaregister variable. Recompileandrunthe codeonce more.Howlongdoesasingleiteration takewith all fourvariablesasregister variables? (d) Commentonyourobservedresults.What canyouconcludeaboutusingregistersin your code? Problem :2 We are writing a simple searchable dictionary using modular programming. First, the program reads a file containing words and their definitions into an easily searchable data structure. Then, the user can type a word, and the program will search the dictionary, and assumingthewordis found,outputsthedefinition.The programproceedsuntiltheuserchoosesto quit. Wesplit thecodeintoseveralfiles:main.c, dict.c, anddict.h. The contentsofthesefilesare describedbrieflybelow. Practical Programming in C programminghomeworkhelp.com
  • 3. main.c: dict.c: dict.h: #include <stdio.h> #include "dict.h" /* data structure #include <stdlib.h> for the dictionary */ #include "dict.h" /* data structure char * thedictionary[1000]; for the dictionary */ int main() { char * thedictionary[1000]; /* declarations */ ... void loaddictionary(); } void load dictionary(){ ... char * lookup(char []); } char * lookup(char []) { ... } Answerthefollowingquestionsbasedontheaboveprogramstructure. (a) In implementingthis program,you wantto accesstheglobal variablethe dictionary from main.c, aswellasfromdict.c. However, due to the header file’s inclusion in both source documents, the variable gets declared in both places, creating an ambiguity. How wouldyou resolvethisambiguity? (b) Now, suppose you want to restrict the dictionary data structure to be accessible only from functions in dict.c. You remove the declaration from dict.h. Is it still possible to directly access or modify the variable from main.c, even without the declaration in dict.h? If so, howwouldyouensurethedatastructurevariableremains private? (c) Congratulations! You’re done and ready to compile your code. Write the command line that you should use to compile this code (usinggcc). Let’scallthedesiredoutput program dictionary.o. Problem : 3 Both thefor loop andthedo-while loop canbetransformedintoasimplewhile loop.Foreach ofthefollowingexamples,write equivalentcodeusingawhile loop instead. (a)int f a c t o r i a l ( int n) { int i , re t = 1 ; for ( i = 2 ; i <= n ; i ++) re t ∗= i ; return re t ; } programminghomeworkhelp.co m
  • 4. double q ; int n = 0 ; do { q = rand double ( ) ; n++; } while ( q >= p ) ; return n ; } Note:You only needto modifythesample geometric rv()function. (b)#include <s t d l i b . h> double rand double () { /∗ g e ne rate random number in [ 0 , 1 ) ∗/ double re t = ( double ) rand ( ) ; return re t /(RAND MAX+1 ); } int s ampl e g e o me tri c rv ( double p) { programminghomeworkhelp.com
  • 5. Problem:4 ’wc’isaunix utility that displaythecountofcharacters,wordsandlinespresentin afile.If no fileisspecifiedit readsfromthe standard input. If more than one file name is specified it displays the counts for each file along with the filename. In this problem,wewill beimplementingwc. One of the ways to build a complex program is to develop it iteratively, solving one problem at a time and testing it throroughly.Forthis problem,startwith thefollowingshellandthen iterativelyaddthemissingcomponents. #include <s t d i o . h> #include <s t d l i b . h> int main ( int argc , char ∗ argv [ ] ) { FILE∗ fp=NULL ; int n f i l e s =− argc ; /∗ i g no re the name o f the program int i t s e l f ∗/ /∗ i g no re the name o f the program i t s e lf ∗/ char ∗ cha r argidx =1; c u r r f i l e=""; c ; /∗ count o f words , l i n e s , c h a ra c te rs ∗/ unsigned long nw=0 , nl =0 , nc =0; i f ( n f i l e s ==0) { fp=s tdi n ; /∗ standard input ∗/ n f i l e s ++; } else /∗ s e t to f i r s t ∗/ { c u r r f i l e=argv [ argidx ++]; fp=fopen ( c u r r f i l e , "r") ; } while ( n f i l e s >0) /∗ f i l e s l e f t >0∗/ { i f ( fp==NULL) { programminghomeworkhelp.com
  • 6. f p r i n t f ( s tde rr , "Unable to open inputn" ) ; e x i t ( −1 ); } nc=nw=n l =0; while (( c=g etc ( fp ))! =EOF) { /∗TODO: FILL HERE pro c e s s the f i l e using g etc ( fp ) ∗/ } p r i n t f ( " ld sn" , nc , c u r r f i l e ) ; /∗ next f i l e i f e x i s t s ∗/ n f i l e s −−; i f ( n f i l e s >0) { c u r r f i l e=argv [ argidx ++]; fp =fopen ( c u r r f i l e , "r") ; } } return 0 ; } Hint: In order to count words, count the transitions from non-white spaceto white space characters. programminghomeworkhelp.com
  • 7. "FLORIDA" 590800 "NEW HAMPSHIRE" 421986 .......... Problem 3.5 In this problem, we will be reading in formatted data and generating a report. One of the common formats for interchangeofformatted data is ’tab delimited’whereeachline corresponds to asinglerecord.The individual fieldsof the record are separated by tabs. For this problem, download the file stateoutflow0708.txt from Stellar. This containsthe emigrationof people fromindividual states. The first rowofthe filecontainsthe columnheadings.There areeightself explanatoryfields.Your task isto readthefileusingfscanfandgenerateareport outlining the migration of people from Massachusetts to all the other states. Use the field ”Aggr AGI” to report the numbers. Also, at the end, display a total and verify it is consistent with the one shown below. An example report should look like the following: STATE TOTAL Total 4609483 Makesurethat thefieldsarealigned. programminghomeworkhelp.com
  • 8. CodelistingforProblem:1:prob1.c #include <s t d l i b . h> #include <s t d i o . h> #include <time . h> #define NMAX 25 static unsigned int r e s u l t s b u f f e r [NMAX] ; void f i b o n a c c i () { /∗ here are the v a r i a b l e s to s e t as r e g i s t e r s ∗/ unsigned int a = 0 ; unsigned int b = 1 ; unsigned int c ; int n ; /∗ do not e d i t below t h i s l i n e ∗/ r e s u l t s b u f f e r [ 0 ] = a ; r e s u l t s b u f f e r [ 1 ] = b ; for ( n = 2 ; n < NMAX; n++) { c = a + b ; r e s u l t s b u f f e r [ n ] = c ; /∗ s t o r e code in r e s u l t s b u f f e r ∗/ a = b ; b = c ; } } int main ( void ) { int n , n t e s t s = 10000000 ; c l o c k t ts ta rt , tend ; double favg ; /∗ do p r o f i l i n g ∗/ t s t a r t = c l o c k ( ) ; programminghomeworkhelp.com
  • 9. for ( n = 0 ; n < n t e s t s ; n++) f i b o n a c c i ( ) ; tend = c l o c k ( ) ; /∗ end p r o f i l i n g ∗/ /∗ compute average e xe c uti o n time ∗/ favg = (( double )( tend − t s t a r t ))/CLOCKS PER SEC/ n t e s t s ; /∗ pri nt avg e xe c uti o n time in m i l l i s e c o n d s ∗/ p r i n t f ( "Avg. execution time: g msecn" , favg ∗1 0 0 0 ) ; return 0 ; } programminghomeworkhelp.com
  • 10. Problem:1 Code profiling and registers. In this problem, we will use some basic code profiling to examine the effects of explicitly declaring variables as registers. Consider the fibonacci sequence generating function fibonacci in prob1.c, which is reproduced at the end of this problem set (and can be downloaded from Stellar). The main() function handles the code profiling, calling fibonacci() many times and measuring the average processor time. (a) First, to get a baseline (without any explicitly declared registers), compile and run prob1.c. Code profiling is one of the rare cases where using a debugger like gdb is discouraged, because the debugger’s overhead can impact the execution time. Also, we want to turn off compiler optimization. Please use the following commands to compile and run the program: dweller@dwellerpc:~$ gcc -O0 -Wall prob1.c -o prob1.o dweller@dwellerpc:~$ ./prob1.o Avg. execution time: 0.000109 msec ← example output dweller@dwellerpc:~$ How long does a single iteration take to execute (on average)? Answer: On my 64-bit machine (results may differ slightly for 32-bit machines), the original fibonacci() function took 0.000109 msec onaverage. (b) Now, modify the fibonacci() function by making the variables a, b, and c register variables. Recompile and run the code. How long does a single iteration take now, on average? Turn in a printout of your modified code (the fibonacci() function itself wouldsuffice). Answer: Here’s the modified fibonacci() function for part (b): void f ib on acci () { /∗ here are the va ri ab l es to set as r e g i s t e r s ∗/ register unsigned int a = 0 ; register unsigned int b = 1 ; register unsigned int c ; int n ; /∗ do not e d i t below t h i s l i n e ∗/ r e s u l t s b u f f e r [ 0 ] = a ; r e s u l t s b u f f e r [ 1 ] = b ; for ( n = 2 ; n < NMAX; n++) { c = a + b; Solutions programminghomeworkhelp.com
  • 11. r e s u l t s b u f f e r [ n ] = c ; /∗ store code in r e s u l t s buffe r ∗/ a = b ; b = c ; } } On my 64-bit machine (results may differ slightly for 32-bit machines), the modified function took 0.000111 msec on average. (c) Modify the fibonacci() function one more time by making the variable n also a register variable. Recompile and run the code once more. How long does a single iteration take with all four variables as register variables? Answer: Here’s the modified fibonacci() function for part (c): void f ib on acci () { /∗ here are the va ri ab l es to set as r e g i s t e r s ∗/ register unsigned int a = 0 ; register unsigned int b = 1 ; register unsigned int c ; register int n ; /∗ do not e d i t below t h i s l i n e ∗/ r e s u l t s b u f f e r [ 0 ] = a ; r e s u l t s b u f f e r [ 1 ] = b ; for ( n = 2 ; n < NMAX; n++) { c = a + b; r e s u l t s b u f f e r [ n ] = c ; /∗ store code in r e s u l t s buffe r ∗/ a = b ; b = c ; } } On my 64-bit machine (results may differ slightly for 32-bit machines), the further modified fibonacci() function took 3.4e-05 msec onaverage. (d) Comment on your observed results. What can you conclude about using registers in your code? Answer: The observed results suggest that storing some variables in a register vs. in memory may or may not impact performance. In particular, storing a, b, and c in registers do not appear to improve the performance at all, while storing nin a register improves performance by a factor of 3. programminghomeworkhelp.com
  • 12. programminghomeworkhelp.com Problem:2 We are writing a simple searchable dictionary using modular programming. First, the program reads a file containing words and their definitions into an easily searchable data structure. Then, the user can type a word, and the program will search the dictionary, and assuming the word is found, outputs the definition. The program proceeds until the user chooses toquit. We split the code into several files: main.c, dict.c, and dict.h. The contents of these files are described briefly below. main.c: dict.c: dict.h: #include <stdio.h> #include "dict.h" /* data structure #include <stdlib.h> for the dictionary */ #include "dict.h" /* data structure char * thedictionary[1000]; for the dictionary */ int main() { char * thedictionary[1000]; /* declarations */ ... void loaddictionary(); } void load dictionary(){ ... char * lookup(char []); } char * lookup(char []) { ... }
  • 13. Answer the following questions based on the above program structure. (a) In implementing this program, you want to access the global variable the dictionary from main.c, as well as from dict.c. However, due to the header file’s inclusion in both source documents, the variable gets declared in both places, creating an ambiguity. How would you resolve this ambiguity? Answer: Adding the extern keyword immediately before the declaration in dict.h resolves the ambiguity, causing both files to reference the variable declared in dict.c. (b) Now, suppose you want to restrict the dictionary data structure to be accessible only from functions in dict.c. You remove the declaration from dict.h. Is it still possible to directly access or modify the variable from main.c, even without the declaration in dict.h? If so, how would you ensure the data structure variable remains private? Answer: Simply removing the declaration from dict.h does not make the variable private to dict.c. One could simply add an extern declaration to main.c or any other source file and still be able to access or modify the dictionary directly. In order to prevent direct access, the dictionary should be declared with the statickeyword in dict.c. (c) Congratulations! You’re done and ready to compile your code. Write the command line that you should use to compile this code (using gcc). Let’s call the desired output program dictionary.o. Answer: gcc -g -O0 -Wall main.c dict.c -o dictionary.o. Note that the order of main.c and dict.cis not important, as long as they are both specified. programminghomeworkhelp.com Problem :3 Both the for loop and the do-while loop can be transformed into a simple whileloop. For each of the following examples, write equivalent code using a while loopinstead. (a) int f a c t o r i a l ( int n) { int i , r e t = 1 ; for ( i = 2 ; i <= n ; i ++) r e t ∗= i ; return r e t ; }
  • 14. int f a c t o r i a l ( int n) { int i = 1 , r e t = 1 ; while (++ i <= n ) r e t ∗= i ; return r e t ; } (b) #include <s t d l i b . h> double rand double ( ) { /∗ generate random number in [0 ,1 ) ∗/ double ret = (double) rand ( ) ; return ret /(RANDMAX+1); } int sample geometric rv (double p) { double q ; int n = 0 ; do { q = rand double ( ) ; n++; } while ( q >= p ) ; return n ; } Note: You only need to modify the sample geometric rv()function. Answer: int sample geometric rv (double p) { double q ; int n = 0 , c o n d i t i o n = 1 ; while ( condition ) { q = rand double ( ) ; n++; condition = q >= p ; } return n ; programminghomeworkhelp.com
  • 15. Problem:4 ’wc’ is a unix utility that display the count of characters, words and lines present in a file. If no file is specified it reads from the standard input. If more than one file name is specified it displays the counts for each file along with the filename. In this problem, we will be implementingwc. One of the ways to build a complex program is to develop it iteratively, solving one problem at a time and testing it throroughly. For this problem, start with the following shell and then iteratively add the missing components. #include <stdio . h> #include <s t d l i b . h> int main ( int argc , char∗ argv [ ] ) { FILE∗ fp=NULL; int n f i l e s =− argc ; /∗ ignore the name of the program int i t s e l f ∗/ /∗ ignore the name of the program i t s e l f ∗/ char∗ char ar g i dx =1; c u r r f i l e=""; c ; /∗count of words , l i nes , characters ∗/ unsigned long nw=0, nl =0,nc=0; if ( n f i l e s ==0) { fp=s tdin ; /∗standard input ∗/ n f i l e s ++; } else /∗ s e t to f i r s t ∗/ { c u r r f i l e=argv [ arg idx ++]; fp=fopen ( c u r r fi l e , " r") ; } while( n f i l e s >0) /∗ f i l e s l e f t >0∗/ { if ( fp==NULL) { f p r i n t f ( stderr , "Unable to open inputn") ; exi t ( −1); } programminghomeworkhelp.com
  • 16. programminghomeworkhelp.com nc=nw=nl =0; while (( c=getc ( fp ))! =EOF) { /∗TODO: FILL HERE process the f i l e using getc ( fp ) ∗/ } p r i n t f (" ld sn", nc , c u r r f i l e ) ; /∗next f i l e i f e x i s t s ∗/ nf i l e s −−; if ( n f i l e s >0) { c u r r f i l e=argv [ arg idx ++]; fp =fopen ( c u r r f i l e , "r") ; } } return 0; } Hint: In order to count words, count the transitions from non-white space to white space characters. Answer: Here’s the code with the shell filled in /∗ 6 . 087 IAP Spring 2010 Problem s e t 2 ∗/ #include <stdio . h> #include <s t d l i b . h> int main ( int argc , char∗ argv [ ] ) { FILE∗ fp=NULL;
  • 17. int n f i l e s =− argc ; int /∗ ignore the name of the program i t s e l f ∗/ /∗ ignore the name of the program i t s e l f ∗/ char ∗ char ar g i dx =1; c u r r f i l e=""; c ; /∗ fol low ing used to count words ∗/ enumstate {INSIDE ,OUTSIDE}; enumstate cu rrstate=INSIDE ; /∗count of words , l i nes , characters ∗/ unsigned long nw=0, nl =0,nc=0; if ( n f i l e s ==0) { fp=s tdin ; /∗standard input ∗/ n f i l e s ++; } else /∗ s e t to f i r s t ∗/ { c u r r f i l e=argv [ arg idx ++]; fp=fopen ( c u r r fi l e , "r") ; } while( n f i l e s >0) /∗ f i l e s l e f t >0∗/ { if ( fp==NULL) { f p r i n t f ( stderr , "Unable to open inputn") ; exi t ( −1); } /∗TODO: FILL HERE process the f i l e using getc ( fp ) ∗/ nc=nw=nl=0; while (( c=getc ( fp ))! =EOF) programminghomeworkhelp.com
  • 18. { nc++; if ( c==’n’) { nl++; } if ( isspace ( c )) { if ( curr state==INSIDE) nw++; currstate=OUTSIDE; } else { currs tate=INSIDE ; } } /∗update to ta l s ∗/ p r i n t f (" ld ld ld sn", nl ,nw, nc , c u r r f i l e ) ; /∗next f i l e i f e x i s t s ∗/ nf i l e s −−; if ( n f i l e s >0) { c u r r f i l e=argv [ arg idx ++]; fp =fopen ( c u r r f i l e , "r") ; } } } programminghomeworkhelp.com
  • 19. "FLORIDA" 590800 "NEW HAMPSHIRE" 421986 .......... Problem:5 In this problem, we will be reading in formatted data and generating a report. One of the common formats for interchange of formatted data is ’tab delimited’ where each line corresponds to a single record. The individual fields of the record are separated by tabs. For this problem, download the file stateoutflow0708.txt from Stellar. This contains the emigration of people from individual states. The first row of the file contains the column headings. There are eight self explanatory fields. Your task is to read the file using fscanf and generate a report outlining the migration of people from Massachusetts to all the other states. Use the field ”Aggr AGI” to report the numbers. Also, at the end, display a total and verify it is consistent with the one shown below. An example report should look like the following: STATE TOTAL Total 4609483 Make sure that the fields are aligned. Answer: Here’s the code with the shell filled in #include <stdio . h> #include <s t d l i b . h> #include <str in g . h> #define STRSIZE 100 #define NFIELDS 9 int main ( ) { char i n p u t f i l e []= "stateoutflow0708.txt"; /∗ define a l l the f i e l d s ∗/ char state code org [ STRSIZE ] ; programminghomeworkhelp.com
  • 20. /∗ parse the f i e l d s ∗/ pr i n tf (" -30s, 6sn","STATE","TOTAL") ; pr i n tf ("---------------------------------------n") ; while( f ge ts ( line , STRSIZE∗NFIELDS, fp )) { f i e l d s r e a d=sscanf ( line , " s s s s s s d s t a t e c o d e o r g , cou nt ry cod e o rg , s t a t e c o d e d e s t , country c ode dest , state abbrv , state name , &return num , &exmpt num , &aggr agi ) ; if ( strcmp ( state code org , ""25"")==0) programminghomeworkhelp.com char char char country code org [STRSIZE ] ; sta te co de des t [STRSIZE ] ; country code dest [STRSIZE ] ; s tate abbrv [ STRSIZE ] ; char state name [ STRSIZE ] ; char l i n e [ STRSIZE∗NFIELDS] ; int int int long return num =0; exmpt num=0; aggr agi =0; tot al =0; /∗ f i l e related ∗/ int f i e l d s r e a d =0; FILE∗ fp=fopen ( i np u t fi l e , "r") ; if ( fp==NULL) { f p r i n t f ( stderr , "Cannot open filen") ; ex it ( −1); } /∗ skip f i r s t l i n e ∗/ f g e ts ( line , STRSIZE∗NFIELDS, fp ) ; /∗ print the header ∗/
  • 21. programminghomeworkhelp.com { pr i n tf (" -30s, 6dn", state name , aggr agi ) ; t o t al += aggr agi ; } } /∗ print the header ∗/ pr i n tf ("----------------------------------------n") ; pr i n tf (" -30s, 6lun","TOTAL", t ot a l ) ; f c l o s e ( fp ) ; return 0; } Code listing for Problem 3.1: prob1.c #include <s td l i b . h> #include <stdio . h> #include <time . h> #define NMAX 25 static unsigned int r e s u l t s b u f f e r [NMAX]; void f ib on acc i () {
  • 22. /∗ here are the va ri ab l es to set as r e g i s t e r s ∗/ unsigned int a = 0 ; unsigned int b = 1 ; unsigned int c ; int n ; /∗ do not e d i t below t h i s l i n e ∗/ r e s u l t s b u f f e r [ 0 ] = a ; r e s u l t s b u f f e r [ 1 ] = b ; for ( n = 2 ; n < NMAX; n++) { c = a + b; r e s u l t s b u f f e r [ n ] = c ; /∗ store code in r e s u l t s buffe r ∗/ a = b ; b = c ; } } int main ( void ) { int n , n t e s t s = 10000000 ; c l o c k t t s t a r t , tend ; double favg ; /∗ do p r o f i l i n g ∗/ ts t a r t = clock ( ) ; for ( n = 0 ; n < n t e s t s ; n++) fi bon acc i ( ) ; tend = clock ( ) ; /∗ end p r o f i l i n g ∗/ /∗ compute average execution time ∗/ favg = (( double)( tend − t s t a r t ))/CLOCKS PER SEC/ ntests ; /∗ print avg execution time in mi l l i seco nd s ∗/ pr i n t f ( "Avg. execution time: g msecn", favg ∗1000); return 0; } programminghomeworkhelp.com