diff --git a/.gitignore b/.gitignore index eed432eb..9e37a517 100644 --- a/.gitignore +++ b/.gitignore @@ -400,3 +400,4 @@ Module.symvers Mkfile.old dkms.conf +.idea/ diff --git a/.readthedocs.yml b/.readthedocs.yml deleted file mode 100644 index b843136e..00000000 --- a/.readthedocs.yml +++ /dev/null @@ -1,24 +0,0 @@ -# .readthedocs.yml -# Read the Docs configuration file -# See https://docs.readthedocs.io/en/stable/config-file/v2.html for details - -# Required -version: 2 - -# Build documentation in the docs/ directory with Sphinx -sphinx: - configuration: source/conf.py - -# Build documentation with MkDocs -#mkdocs: -# configuration: mkdocs.yml - -# Optionally build your docs in additional formats such as PDF and ePub -formats: [] - -# Optionally set the version of Python and requirements required to build your docs -python: - version: 3.7 - install: - - requirements: source/requirements.txt - diff --git a/LICENSE b/LICENSE index 39bdc1cb..471fbc92 100644 --- a/LICENSE +++ b/LICENSE @@ -1,4 +1,4 @@ -Copyright (c) 2016, Senthil Kumaran +Copyright (c) 2024, Senthil Kumaran All rights reserved. diff --git a/Makefile b/Makefile index 70f793fb..81a2da1c 100644 --- a/Makefile +++ b/Makefile @@ -1,5 +1,4 @@ # Makefile for Sphinx documentation -# # You can set these variables from the command line. SPHINXOPTS = @@ -27,7 +26,6 @@ help: @echo " latexpdf to make LaTeX files and run them through pdflatex" @echo " changes to make an overview of all changed/added/deprecated items" @echo " linkcheck to check all external links for integrity" - @echo " doctest to run all doctests embedded in the documentation (if enabled)" clean: -rm -rf $(BUILDDIR)/* @@ -112,8 +110,3 @@ linkcheck: @echo @echo "Link check complete; look for any errors in the above output " \ "or in $(BUILDDIR)/linkcheck/output.txt." - -doctest: - $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest - @echo "Testing of doctests in the sources finished, look at the " \ - "results in $(BUILDDIR)/doctest/output.txt." diff --git a/README.md b/README.md new file mode 100644 index 00000000..7acf7011 --- /dev/null +++ b/README.md @@ -0,0 +1,24 @@ +# https://learntosolveit.com + +[https://learntosolveit.com](https://learntosolveit.com) is a website to learn C programming using K&R book. It uses modern tools, and is designed to be used along with the book. + +I recommend [https://exercism.org](https://exercism.org) as the platform to +learn programming, including C, and practice with a community of intrinsically +motivated developers. + +### References + +* C Programming Language by Kernighan and Ritchie. +* https://github.com/jflaherty/ptrtut13/blob/master/md/ch1x.md +* https://manual.cs50.io/ + + +[![Netlify Status](https://api.netlify.com/api/v1/badges/27a766e4-762c-420f-92e2-f35441c79f63/deploy-status)](https://app.netlify.com/sites/learntosolveit/deploys) +[![Documentation Status](https://readthedocs.org/projects/learntosolveit/badge/?version=latest)](http://www.learntosolveit.com/?badge=latest) + + +## Author + +* Senthil Kumaran +* Email: [senthil@uthcode.com](mailto:senthil@uthcode.com) +* Blog: [https://senthil.learntosolveit.com](https://senthil.learntosolveit.com) diff --git a/README.rst b/README.rst deleted file mode 100644 index bb0bff67..00000000 --- a/README.rst +++ /dev/null @@ -1,28 +0,0 @@ -Learn To Solve It -================= - -Please visit https://exercism.org to "Learn To Solve It" using your favorite programming language. - -.. image:: https://readthedocs.org/projects/learntosolveit/badge/?version=latest - :target: https://www.learntosolveit.com/?badge=latest - :alt: Documentation Status - - -For the suggest-improve and better-explain C programming contents - -:: - - :c-suggest-improve:`filename.c` - :c-better-explain:`filename.rst` - - -Dependencies ------------- - -* https://github.com/sphinx-doc/sphinx/ - - -Contact -------- - -* Senthil Kumaran diff --git a/languages/cprogs/CMakeLists.txt b/languages/cprogs/CMakeLists.txt deleted file mode 100644 index 4915b8ca..00000000 --- a/languages/cprogs/CMakeLists.txt +++ /dev/null @@ -1,7 +0,0 @@ -cmake_minimum_required(VERSION 3.6) -project(learntosolveit) - -set(CMAKE_C_STANDARD 11) - -set(SOURCE_FILES Ex_1.14_Hist_Freq.c) -add_executable(learntosolveit ${SOURCE_FILES}) \ No newline at end of file diff --git a/languages/cprogs/Ex_1.10_TbsBlnkSpaces.c b/languages/cprogs/Ex_1.10_TbsBlnkSpaces.c index 2c59024e..e06534e3 100644 --- a/languages/cprogs/Ex_1.10_TbsBlnkSpaces.c +++ b/languages/cprogs/Ex_1.10_TbsBlnkSpaces.c @@ -7,11 +7,22 @@ #include +const char *input = "This\tis\ta\b\btest\tstring."; +int input_index = 0; + +int _getchar(void) { + if (input[input_index] == '\0') { + return EOF; + } else { + return input[input_index++]; + } +} + int main(void) { int c; - while((c = getchar()) != EOF) + while((c = _getchar()) != EOF) { if(c == '\t') { diff --git a/languages/cprogs/Ex_1.8_count_blanks_etc.c b/languages/cprogs/Ex_1.8_count_blanks_etc.c index 5f59bd67..4ca14c52 100644 --- a/languages/cprogs/Ex_1.8_count_blanks_etc.c +++ b/languages/cprogs/Ex_1.8_count_blanks_etc.c @@ -6,6 +6,16 @@ #include +const char *input = "This\tis\ta\ttest\\string\bwith\ttabs\\and\\backspaces.\n\nnewline"; +int input_index = 0; + +int _getchar(void) { + if (input[input_index] == '\0') { + return EOF; + } else { + return input[input_index++]; + } +} int main() { @@ -13,7 +23,7 @@ int main() blanks = tabs = newlines = 0; - while ((c = getchar()) != EOF) { + while ((c = _getchar()) != EOF) { if (c == ' ') ++blanks; if (c == '\t') diff --git a/languages/cprogs/Ex_1.9_SinBlank.c b/languages/cprogs/Ex_1.9_SinBlank.c index 28551142..b04acd53 100644 --- a/languages/cprogs/Ex_1.9_SinBlank.c +++ b/languages/cprogs/Ex_1.9_SinBlank.c @@ -6,6 +6,19 @@ #include +const char *input = "This line has many blanks to be replaced by single blank"; +int input_index = 0; + +int custom_getchar(void) { + if (input[input_index] == '\0') { + return EOF; + } else { + return input[input_index++]; + } +} + + + #define NONBLANK '-' int main(void) @@ -14,7 +27,7 @@ int main(void) lastc = NONBLANK; - while((c = getchar()) != EOF) + while((c = custom_getchar()) != EOF) { if(c == ' ') { diff --git a/languages/cprogs/Ex_4.3_rpn_modulus_negative.c b/languages/cprogs/Ex_4.3_rpn_modulus_negative.c index 1858ce2a..70f97bab 100644 --- a/languages/cprogs/Ex_4.3_rpn_modulus_negative.c +++ b/languages/cprogs/Ex_4.3_rpn_modulus_negative.c @@ -1,142 +1,127 @@ -/* Adding the Modulus operator and provision for negative numbers -* Program is given the input in a single and and it print the output upon -* getting a \n character. -* For e.g: -* -* 10 10 + 100 + 2 * -* 240 -*/ +/** In the RPN calculator, add the modulus operator and provision for negative + * numbers. + * Program is given the input in a single and and it print the output upon + * getting a \n character. + * + * For e.g: + * + * 10 10 + 100 + 2 * + * 240 + */ -#include -#include -#include +#include +#include +#include +#include + + +#define BUFSIZE 100 #define MAXOP 100 +#define MAXVAL 100 #define NUMBER '0' -int getop(char []); +int getop(char[]); void push(double); double pop(void); +int getch(void); +void ungetch(int); -/* reverse polish calculator */ - -int main(void) -{ - int type; - double op2; - char s[MAXOP]; - - while((type = getop(s)) != EOF) - { - switch(type) - { - case NUMBER: - push(atof(s)); - break; - case '+': - push(pop()+pop()); - break; - case '*': - push(pop()*pop()); - break; - case '-': - op2 = pop(); - push(pop()-op2); - break; - case '/': - op2 = pop(); - if(op2 != 0.0) - push(pop()/op2); - else - printf("error:zero divisor\n"); - break; - case '%': - op2 = pop(); - if(op2 != 0.0) - push(fmod(pop(),op2)); - else - printf("erro:zero divisor\n"); - break; - case '\n': - printf("\t%.8g\n",pop()); - break; - default: - printf("error: unknown command %s\n",s); - break; - - } - } - return 0; -} - - -#define MAXVAL 100 - +int bufp = 0; int sp = 0; +char buf[BUFSIZE]; + double val[MAXVAL]; -void push(double f) -{ - if(sp < MAXVAL) - val[sp++]=f; - else - printf("error:stack full, cant push %g\n",f); +void push(double f) { + if (sp < MAXVAL) + val[sp++] = f; + else + printf("error:stack full, cant push %g\n", f); } - -double pop(void) -{ - if(sp>0) - return val[--sp]; - else - { - printf("error: stack empty\n"); - return 0.0; - } +double pop(void) { + if (sp > 0) + return val[--sp]; + else { + printf("error: stack empty\n"); + return 0.0; + } } -#include - -int getch(void); -void ungetch(int); - int getop(char s[]) { - int i, c; - while ((s[0] = c = getch()) == ' ' || c == '\t') - ; - s[1] = '\0'; - if (!isdigit(c) && c != '.' && c != '-') - return c; // not a number - i = 0; - if (c == '-' || isdigit(c)) // collect integer part along with '-' - while (isdigit(s[++i] = c = getch())) - ; - if (c == '.') // collect fraction part - while (isdigit(s[++i] = c = getch())) - ; - s[i] = '\0'; - if (c != EOF) - ungetch(c); - if (strcmp(s, "-") == 0) - return '-'; - return NUMBER; + int i, c; + while ((s[0] = c = getch()) == ' ' || c == '\t') + ; + s[1] = '\0'; + if (!isdigit(c) && c != '.' && c != '-') + return c; // not a number + i = 0; + if (c == '-' || isdigit(c)) // collect integer part along with '-' + while (isdigit(s[++i] = c = getch())) + ; + if (c == '.') // collect fraction part + while (isdigit(s[++i] = c = getch())) + ; + s[i] = '\0'; + if (c != EOF) + ungetch(c); + if (strcmp(s, "-") == 0) + return '-'; + return NUMBER; } -#define BUFSIZE 100 - -char buf[BUFSIZE]; -int bufp = 0; +int getch(void) { return (bufp > 0) ? buf[--bufp] : getchar(); } -int getch(void) -{ - return (bufp > 0) ? buf[--bufp] : getchar(); +void ungetch(int c) { + if (bufp >= BUFSIZE) + printf("ungetch: too many characters\n"); + else + buf[bufp++] = c; } -void ungetch(int c) -{ - if(bufp >= BUFSIZE) - printf("ungetch: too many characters\n"); - else - buf[bufp++] = c; +/* Reverse Polish Calculator */ +int main(void) { + int type; + double op2; + char s[MAXOP]; + + while ((type = getop(s)) != EOF) { + switch (type) { + case NUMBER: + push(atof(s)); + break; + case '+': + push(pop() + pop()); + break; + case '*': + push(pop() * pop()); + break; + case '-': + op2 = pop(); + push(pop() - op2); + break; + case '/': + op2 = pop(); + if (op2 != 0.0) + push(pop() / op2); + else + printf("error:zero divisor\n"); + break; + case '%': + op2 = pop(); + if (op2 != 0.0) + push(fmod(pop(), op2)); + else + printf("erro:zero divisor\n"); + break; + case '\n': + printf("\t%.8g\n", pop()); + break; + default: + printf("error: unknown command %s\n", s); + break; + } + } + return 0; } - diff --git a/languages/cprogs/Ex_5.14_sortrevnum.c b/languages/cprogs/Ex_5.14_sortrevnum.c index fde3e4a1..897f865d 100644 --- a/languages/cprogs/Ex_5.14_sortrevnum.c +++ b/languages/cprogs/Ex_5.14_sortrevnum.c @@ -48,7 +48,7 @@ int main(int argc,char *argv[]) if(option & NUMERIC) myqsort((void **)lineptr,0,nlines -1,(int (*)(void *,void *))numcmp); else - myqsort((void **)lineptr,0,nlines -1,(int (*)(void *,void *))numcmp); + myqsort((void **)lineptr,0,nlines -1,(int (*)(void *,void *))strcmp); writelines(lineptr,nlines,option & DECR); } else diff --git a/languages/cprogs/Ex_5.17_sortdfnr-withoption.c b/languages/cprogs/Ex_5.17_sortdfnr-withoption.c index d4f7e269..d796e651 100644 --- a/languages/cprogs/Ex_5.17_sortdfnr-withoption.c +++ b/languages/cprogs/Ex_5.17_sortdfnr-withoption.c @@ -3,6 +3,7 @@ #include #include +#include #define NUMERIC 1 /* numeric sort */ #define DECR 2 /* sort in decreasing order */ @@ -15,7 +16,7 @@ void error(char *); int numcmp(char *,char *); void readargs(int argc,char *argv[]); int readlines(char *lineptr[],int maxlines); -void mqsort(void *v[],int left,int right,int (*comp)(void *,void *)); +void myqsort(void *v[],int left,int right,int (*comp)(void *,void *)); void writelines(char *lineptr[],int nlines,int order); int option = 0; @@ -57,7 +58,6 @@ int main(int argc,char *argv[]) void readargs(int argc,char *argv[]) { int c; - int atoi(char *); while(--argc > 0 && (c=(*++argv)[0])=='-' || c == '+') { @@ -177,7 +177,7 @@ void error(char *); /* substr: get a substring of S and put in str */ -void substr(char *s,char *str) +void substr(char *s,char *str, int maxstr) { int i,j,len; extern int pos1,pos2; @@ -258,7 +258,7 @@ int readlines(char *lineptr[],int maxlines) } /* writelines: write output lines */ -void writelines(char *lineptr[],int nlines) +void writelines(char *lineptr[],int nlines, int order) { int i; @@ -296,7 +296,7 @@ int mgetline(char s[],int lim) { int c,i; - for(i=0;i #include #include -enum { NAME,PARENS,BRACKETS }; -enum { NO, YES }; +#define MAXTOKEN 100 + +enum {NAME,PARENS,BRACKETS}; +enum { NO, YES}; void dcl(void); void dirdcl(void); void errmsg(char *); int gettoken(void); -extern int tokentype; /* type of last token */ -extern char token[]; /* last token string */ -extern char name[]; /* identifier name */ -extern char out[]; +int tokentype; /* type of last token */ +char token[MAXTOKEN]; /* last token string */ +char name[MAXTOKEN]; /* identifier name */ +char out[1000]; +char datatype[MAXTOKEN]; extern int prevtoken; +extern int tokentype; +extern char token[]; +int prevtoken = NO; - -/* dcl: parse a declarator */ -void dcl(void) -{ - int ns; - - for(ns = 0; gettoken() == '*';) /* count *'s */ - ns++; - - dirdcl(); - - while(ns-- > 0) - strcat(out,"pointer to"); -} - - -/* dirdcl: parse a direct declaration */ -void dirdcl(void) +int main(void) { - int type; - - if(tokentype == '(' ) - { - dcl(); - - if(tokentype != ')') - errmsg("error: missing ) \n"); + int i; + + if(gettoken()!=EOF) + { + strcpy(datatype,token); + out[0]='\0'; + dcl(); + + if(tokentype != '\n') + printf("syntax error \n"); + + printf(" %s %s %s \n",name,out,datatype); + for(i=0;i -#include +/* dcl: parse a declarator */ -/* enum { NAME,PARENS,BRACKETS}; */ -/* enum { NO,YES }; */ - -extern int tokentype; /* type of last token */ -extern char token[]; /* last token string */ -int prevtoken = NO; - -/* gettoken : return next token */ - -int gettoken(void) +void dcl(void) { - int c,getch(void); - void ungetch(int); + int ns; - char *p = token; - - if(prevtoken == YES) - { - prevtoken = NO; - - return tokentype; - } + for(ns=0;gettoken()=='*';) /* count *'s */ + ns++; - while((c=getch()) == ' ' || c == '\t') - ; + dirdcl(); + while(ns-- > 0) + strcat(out," pointer to"); +} - if(c == '(') - { - if((c = getch()) == ')') - { - strcpy(token,"()"); - return tokentype = PARENS; - } - else - { - ungetch(c); - return tokentype = '('; - } - } - else if (c == '[') - { - for(*p++ = c; ( *p++ = getch()) != ']';) - ; - *p ='\0'; +/* dirdcl: parse a direct declarator */ - return tokentype = BRACKETS; - } - else if (isalpha(c)) - { - for(*p++ = c; isalnum(c=getch()); ) - *p++ = c; - - *p = '\0'; - - ungetch(c); - return tokentype = NAME; - } - else - return tokentype = c; +void dirdcl(void) +{ + int type; + + if(tokentype == '(') /* dcl */ + { + dcl(); + + if(tokentype != ')') + errmsg("error: missing ) \n"); + } + else if(tokentype == NAME) /* variable name */ + strcpy(name,token); + else + errmsg("error: expected name or (dcl) \n"); + + while((type=gettoken()) == PARENS || type == BRACKETS ) + if((type = PARENS)) + strcat(out,"function returning"); + else + { + strcat(out," arg"); + strcat(out,token); + strcat(out," of"); + } } -#define BUFSIZE 100 +void errmsg(char *msg) +{ + printf("%s", msg); + prevtoken = YES; +} +#define BUFSIZE 100 -char buf[BUFSIZE]; /* buffer for ungetch */ -int bufp = 0; /* next free position in buf */ +char buf[BUFSIZE]; /* buffer for ungetch */ +int bufp = 0; /* next free position in buf */ -int getch(void) /* get a (possibly pushed back) character */ +int getch(void) /* get a (possibly pushed back) character */ { - return (bufp > 0) ? buf[--bufp]: getchar(); + return (bufp > 0) ? buf[--bufp]:getchar(); } -void ungetch(int c) +void ungetch(int c) /* push a character back on input */ { - if ( bufp >= BUFSIZE) - printf("ungetch: too many characters \n"); - else - buf[bufp++] = c; + if(bufp >= BUFSIZE) + printf("ungetch: too many characters \n"); + else + buf[bufp++] = c; } - diff --git a/languages/cprogs/Ex_5.1_getint.c b/languages/cprogs/Ex_5.1_getint.c index de97f9ff..e80f1cda 100644 --- a/languages/cprogs/Ex_5.1_getint.c +++ b/languages/cprogs/Ex_5.1_getint.c @@ -59,11 +59,9 @@ int getint(int *pn) int main(void) { - int n,s,array[SIZE],getint(int *); + int n,s,array[SIZE]; - for(n=0;n=0;n--) - printf("%f",array[n]); - + { + for(;n>=0;n--) + printf("%f\n",array[n]); + } return 0; } diff --git a/languages/cprogs/Ex_5.4_strend.c b/languages/cprogs/Ex_5.4_strend.c index c093df10..8c042840 100644 --- a/languages/cprogs/Ex_5.4_strend.c +++ b/languages/cprogs/Ex_5.4_strend.c @@ -1,4 +1,5 @@ #include + #define MAXLINE 1000 int mgetline(char s[],int max); diff --git a/languages/cprogs/Ex_5.5_strncpy.c b/languages/cprogs/Ex_5.5_strncpy.c index f75719f2..342f6089 100644 --- a/languages/cprogs/Ex_5.5_strncpy.c +++ b/languages/cprogs/Ex_5.5_strncpy.c @@ -18,7 +18,7 @@ void mystrncpy(char *, char *, int); void mystrncat(char *, char *, char *, int); int mystrncmp(char *, char *, int); -int mystrlen(char *s); +int mystrnlen(char *s); int main(int argc, char *argv[]) { @@ -77,7 +77,7 @@ void mystrncpy(char *dest,char *source,int n) int extra = mystrnlen(dest) - n; while (extra-- > 0) { - *dest++; + dest++; } *dest = '\0'; diff --git a/languages/cprogs/Ex_5.7_readlines_using_array.c b/languages/cprogs/Ex_5.7_readlines_using_array.c index 11417f62..eedaf555 100644 --- a/languages/cprogs/Ex_5.7_readlines_using_array.c +++ b/languages/cprogs/Ex_5.7_readlines_using_array.c @@ -43,9 +43,10 @@ int readlines(char *lineptr[],char *linestor,int maxlines) char line[MAXLEN]; char *p = linestor; char *linestop = linestor + MAXSTOR; + char c; nlines=0; - +loop: while((len=mgetline(line,MAXLEN)) > 0) if(nlines >= maxlines || p+len > linestop) return -1; @@ -55,8 +56,14 @@ int readlines(char *lineptr[],char *linestor,int maxlines) strcpy(p,line); lineptr[nlines++]=p; p+=len; + printf("get a newline? 0 for no, ENTER to input next line."); + c = getchar(); + if(c != '0') + goto loop; + else if(c == '0') + return nlines; } - return nlines; + return 0; } /* writelines: write output lines */ @@ -128,4 +135,3 @@ int mgetline(char *s,int lim) return s-t; } - diff --git a/languages/cprogs/Ex_6.3.c b/languages/cprogs/Ex_6.3.c index 6d648b6d..ee0dd3e1 100644 --- a/languages/cprogs/Ex_6.3.c +++ b/languages/cprogs/Ex_6.3.c @@ -1,316 +1,249 @@ /* - * Write a cross-referencer that prints a list of all words in a document, and for each word, a list of the line numbers - * on which it occurs. Remove noise words like "the" and "and" so on. + * Write a cross-referencer that prints a list of all words in a document, + * and for each word, a list of the line numbers on which it occurs. + * Remove noise words like "the" and "and" so on. * */ - /* - * 1. Add all the word structures (word structure will have word and line numbers to the tree. - * 2. A word can occur in more than one line, if the same word is found and the new line number to the line numbers. - * 3. So line numbers should be a linked list of numbers. - * 4. Print it. + * 1. Create a binary tree that will contain words and structure with lines on which words occur. + * 2. Check if the word is noisy with binary search. + * 3. Print the words and lines. * */ +#define N_OF_NOISEWORDS 123 + +const char *noiseWords[N_OF_NOISEWORDS]={"a", "about", "after", "all", +"also", "an", "another", "any", "are", "as", "and", "at", "be", +"because", "been", "before", "being", "between", "but", "both", +"by", "came", "can", "come", "could","did", "do","each", "even", +"for", "from", "further", "furthermore","get", "got","has", "had", +"he", "have", "her", "here", "him", "himself", "his", "how", "hi", +"however","i", "if", "in", "into", "is", "it", "its", "indeed","just", +"like","made", "many", "me", "might", "more", "moreover", "most", +"much","must", "my","never", "not", "now","of", "on", "only", "other", +"our", "out", "or", "over","said", "same", "see", "should", "since", +"she", "some", "still", "such","take", "than", "that", "the", "their", +"them", "then", "there", "these", "therefore", "they", "this", "those", +"through", "to", "too", "thus","under", "up","very","was", "way", "we", +"well", "were", "what", "when", "where", "which", "while", "who", +"will", "with", "would","you", "your"}; #include -#include #include +#include #include -#include -#define MAXWORD 1000 /* longest word that can be read by mgetword */ -#define DEFAULT_COMP_LEN 8 /* default length to compare */ +#define MAXWORD 500 -/* - * tnode: Tree node from K&R2 page 140. Words are initially read into - * the tree by getword. - */ -struct tnode -{ - char *word; - int count; - struct linenumber *linenumbers; - struct tnode *left; - struct tnode *right; -}; - -struct linenumber { - int *number; - struct linenumber *nextnumber; -}; + struct tnode{ + char *word; + unsigned int count; + struct ocurLine *lineOfOccurence; -/* - * simroot: Part of a linked list of pointers to simword lists with - * a common root. - */ -struct simroot -{ - struct simword *firstword; /* points to the list of words */ - struct simroot *nextroot; /* points to the next node in the list */ -}; + struct tnode *left; + struct tnode *right; + }; -/* - * simword: Part of a linked list of words with a common root. Points - * to the word in the tnodes. - */ -struct simword -{ - char *word; /* points to the word in the tree */ - int count; /* copied from the tree */ - int linenumber; /* copied from the tree */ - struct simword *nextword; /* next node */ -}; - -struct tnode *addtree(struct tnode *, char *, int); -void treeprint(const struct tnode *); -int mgetword(char *, int, int *); -struct linenumber *lnumberalloc(void); -struct linenumber *addlinenumber(struct linenumber *, int); - -int main(int argc, char *argv[]) -{ - struct tnode *root; - char word[MAXWORD]; - int len; - int lineno = 0; - - - /* get all the words */ - root = NULL; - while(mgetword(word, MAXWORD, &lineno) != 'x') - if(isalpha(word[0])) - root = addtree(root, word, lineno); - - if(argc == 1) - len = DEFAULT_COMP_LEN; - else if(argc == 2) - len = atoi(argv[1]); - else { - printf("Incorrect number of arguments.\n"); - return 1; - } - - printf("Words with line numbers\n"); - treeprint(root); /* prints all the words */ + struct ocurLine{ + unsigned int line; + struct ocurLine *next; + }; - return 0; -} /* end of main() */ +int binarySearch(const char *arr[], int l, int r, char *x); -struct tnode *talloc(void); -char *mstrdup(char *); +void treeprint(const struct tnode *p); +char *mstrdup(char *s); -/* mgetword from Ex6.1 */ +int getWord(char *word, int lim); -#define IN 1 -#define OUT 0 +void ungetch(char c); +int getch(void); -int mgetword(char *word, int lim, int *lineno_addr) -{ - int c, d, getch(void), comment, string, directive; - void ungetch(int); - char *w = word; +char buf; /* buffer for getch/ungetch */ - comment = string = directive = OUT; - - while (isspace(c = getch())) { - if (c == '\n') { - - *lineno_addr = *lineno_addr +1; +struct tnode *talloc(void); +struct tnode *addtree(struct tnode *p, char *w, unsigned int l); - } - } +void printline(const struct ocurLine *p); - /* Check if inside a comment */ +struct ocurLine *linealloc(void); +struct ocurLine *addLine(struct ocurLine *p, unsigned int l); - if (c == '/') { - if ((d = getch()) == '*') { - comment = IN; - } else { - comment = OUT; - ungetch(d); - } - } +int main() +{ + int l=1; + struct tnode *root; + char word[MAXWORD]; + + root = NULL; + + while(getWord(word, MAXWORD) != EOF) + if (word[0] == '\n') // Adding 1 to [l] if there is new line + l++; + else if(isalpha(word[0])) + if (binarySearch(noiseWords, 0, N_OF_NOISEWORDS, word) == -1) + root = addtree(root, word, l); + treeprint(root); +} - /* Check if inside a quote */ - if ( c == '\"') { - string = IN; - } + /* Binary search for our array of noise words. */ +int binarySearch(const char *arr[], int l, int r, char *x) +{ + if (r >= l) { + int mid = l + (r - l) / 2; + int cmp = strcmp(arr[mid], x); - /* Check if inside a directive */ + if (cmp == 0) + return mid; - if (c == '#') { - directive = IN; - } + if (cmp > 0) + return binarySearch(arr, l, mid - 1, x); + + return binarySearch(arr, mid + 1, r, x); + } + + return -1; +} - if ( c == '\\') { - c = getch(); /* ignore the \\ character */ - } - if (comment == OUT && string == OUT && directive == OUT) { +int getWord(char *word, int lim) +{ + int c; - if (c != EOF) - *w++ = c; + char *w = word; - if (!isalnum(c) && c !='_' ) { - *w = '\0'; - return c; - } + while (isspace(c = getch()) && c != '\n') + ; - for ( ; --lim > 0; w++) { - *w = getch(); - if (!isalnum(*w) && *w != '_') { - ungetch(*w); - break; - } - } - *w = '\0'; - return word[0]; - } - else if ( comment == IN) { + if (c != EOF) *w++ = c; - *w++ = d; - - while ((*w++ = c = getch())) { - if ( c == '*' ) { - if ( (c = getch()) == '/' ) { - *w++ = c; - comment = OUT; - break; - } else { - ungetch(c); - } - } - } - *w = '\0'; - } - else if ( string == IN) { - *w++ = c; - while ((*w++ = getch()) != '\"') { - if ( *w == '\\') /* Take care of escaped quotes */ - *w++ = getch(); - } - string = OUT; - *w = '\0'; - } - else if (directive == IN) { - *w++ = c; - while ((*w++ = getch()) != '\n') { - if ( c == '\\') { /* Take care of continuation line escape */ - *w++ = getch(); - } - } - directive = OUT; + if (!isalpha(c) && c != '_' && c != '#') { *w = '\0'; + return c; } - return c; + for ( ; --lim > 0; w++) + if (!isalnum(*w = getch())){ + ungetch(*w); + break; + } + *w = '\0'; + return word[0]; } - - -/*************************************************************************** - * All code below here is from K&R2. * - ***************************************************************************/ - -/* - * addtree: From K&R2 page 141. - * Adds a node containing w, at or below node p. - */ -struct tnode *addtree(struct tnode *p, char *w, int linenumber) +/* addtree: adds branch to a tree*/ +struct tnode *addtree(struct tnode *p, char *w, unsigned int l) { int cond; if(p == NULL) { /* new word */ p = talloc(); - p->word = mstrdup(w); + p->word=mstrdup(w); p->count = 1; - p->linenumbers = NULL; - p->linenumbers = addlinenumber(p->linenumbers, linenumber); + p->lineOfOccurence = NULL; + p->lineOfOccurence = addLine(p->lineOfOccurence, l); p->left = p->right = NULL; } - else if((cond = strcmp(w, p->word)) == 0) { - p->count++; - p->linenumbers = addlinenumber(p->linenumbers, linenumber); + else if((cond = strcmp(w, p->word)) == 0){ + p->count++; + p->lineOfOccurence = addLine(p->lineOfOccurence, l); } else if(cond < 0) - p->left = addtree(p->left, w, linenumber); + p->left = addtree(p->left, w, l); else - p->right = addtree(p->right, w, linenumber); + p->right = addtree(p->right, w, l); return p; } -struct linenumber *addlinenumber(struct linenumber *p, int linenumber) { - if (p == NULL) { - p = lnumberalloc(); - p->number = linenumber; - p->nextnumber = NULL; - } else { - p->nextnumber = addlinenumber(p->nextnumber, linenumber); - } +/* treeprint: prints all the branches of the tree with words.*/ +void treeprint(const struct tnode *p) +{ - return p; + if(p != NULL) { + treeprint(p->left); + + printf("%s: [", p->word); + + printline(p->lineOfOccurence); + + printf("]\n"); + + treeprint(p->right); + } } -struct linenumber *lnumberalloc(void) +/* talloc: From K&R2 page 142. Makes a tnode. */ +struct tnode *talloc(void) { - return (struct linenumber *) malloc(sizeof(struct linenumber)); + return (struct tnode *) malloc(sizeof(struct tnode)); } -/* treeprint: From K&R2 page 142. Prints tree p in-order. */ -void treeprint(const struct tnode *p) + +/* printline: Prints all lines.*/ +void printline(const struct ocurLine *p) { - if(p != NULL) { - treeprint(p->left); - printf("\n%s :", p->word); - printnumbers(p->linenumbers); - treeprint(p->right); + if (p->next == NULL) + printf("%i", p->line); + else{ + printf("%i, ", p->line); + printline(p->next); } } -void printnumbers(const struct linenumber *p) { - if (p != NULL) { - printf("%d,", p->number); - printnumbers(p->nextnumber); +/* addLine: adds a line to word. */ +struct ocurLine *addLine(struct ocurLine *p, unsigned int l) +{ + if (p == NULL){ + p = linealloc(); + p->line = l; + p->next = NULL; } + else + p->next = addLine(p->next, l); + return p; } -/* talloc: From K&R2 page 142. Makes a tnode. */ -struct tnode *talloc(void) +/* linealloc: Makes ocurLine*/ +struct ocurLine *linealloc(void) { - return (struct tnode *) malloc(sizeof(struct tnode)); + return (struct ocurLine *) malloc(sizeof(struct ocurLine)); } /* strdup: From K&R2 page 143. Makes a duplicate of s. */ char *mstrdup(char *s) { char *p; + p = (char *) malloc(strlen(s) + 1); + if(p != NULL) strcpy(p, s); return p; } -/* - * getch and ungetch are from K&R2, page 79 - */ -#define BUFSIZE 100 - -char buf[BUFSIZE]; /* buffer for ungetch() */ -int bufp = 0; /* next free position in buf */ +/************************************************************* + * Getch/Ungetch functions from previous exercises * + *************************************************************/ -int getch(void) { /* get a (possibly pushed back) character */ - return (bufp > 0) ? buf[--bufp] : getchar(); +/* getch: gets a (possibly pushed-back) character */ +int getch(void) +{ + if (buf > 0){ + int copy=buf; + buf=0; + return copy; + } + else + return getchar(); } -void ungetch(int c) { /* push character back on input */ - if(bufp >= BUFSIZE) - printf("ungetch: too many characters\n"); - else - buf[bufp++] = c; - return; -} \ No newline at end of file +/* ungetch: pushes character back on input */ +void ungetch(char c) +{ + buf = c; +} diff --git a/languages/cprogs/Ex_6.4.c b/languages/cprogs/Ex_6.4.c index d7698387..2e383d11 100644 --- a/languages/cprogs/Ex_6.4.c +++ b/languages/cprogs/Ex_6.4.c @@ -198,7 +198,7 @@ struct bynumbernode *traverse(const struct tnode *p, struct bynumbernode *q){ return q; } -void main(){ +int main(){ struct tnode *root; char word[MAXWORD]; @@ -218,7 +218,7 @@ void main(){ printf("Words by frequency:\n"); treeprint(nroot); - return; + return 0; } diff --git a/languages/cprogs/Ex_7.1_lower-upper.c b/languages/cprogs/Ex_7.1_lower-upper.c index 5ef30604..847780de 100644 --- a/languages/cprogs/Ex_7.1_lower-upper.c +++ b/languages/cprogs/Ex_7.1_lower-upper.c @@ -1,24 +1,35 @@ -/* Write a program which converts upper case to lower case or lower case to +/* Write a program which converts upper case to lower case or lower case to upper case depending on the name it is involved with as found in argv[0] */ -#include -#include -#include +#include +#include +#include /* lower: converts upper case to lower case */ /* upper: converts lower case to upper case */ -int main(int argc,char *argv[]) -{ - int c; +const char *input = "This\tis\ta\ttest"; +int input_index = 0; - if(strcmp(argv[0],"./lower")==0) - while((c=getchar()) != EOF) - putchar(tolower(c)); - else - while((c=getchar()) != EOF) - putchar(toupper(c)); - - return 0; +int _getchar(void) { + if (input[input_index] == '\0') { + return EOF; + } else { + return input[input_index++]; + } } + + +int main(int argc, char *argv[]) { + int c; + + if (strcmp(argv[0], "./lower") == 0) + while ((c = _getchar()) != EOF) + putchar(tolower(c)); + else + while ((c = _getchar()) != EOF) + putchar(toupper(c)); + + return 0; +} diff --git a/languages/cprogs/Fibonacci.c b/languages/cprogs/Fibonacci.c deleted file mode 100644 index e1ba9c67..00000000 --- a/languages/cprogs/Fibonacci.c +++ /dev/null @@ -1,30 +0,0 @@ -/* Fibonacci Numbers Generator */ -/* Fibonacci series is formed by adding the latest two numbers to get the next one,starting from 0 and 1 */ - -#include - -int main(void) -{ - int first,second,next,limit; - printf("How many Numbers in the Series?"); - scanf("%d",&limit); - - first=0; - second=1; - - printf("%d,%d",first,second); - - while(limit > 2) /* 0 and 1 are default and counted */ - { - next = first + second; - printf(",%d",next); - - first= second; - second = next; - - --limit; - } -return 0; -} - - diff --git a/languages/cprogs/Nofbtn.c b/languages/cprogs/Nofbtn.c deleted file mode 100644 index 54b77e0b..00000000 --- a/languages/cprogs/Nofbtn.c +++ /dev/null @@ -1,24 +0,0 @@ -/* Write a Program to Count Blanks, Tabs and Newlines */ - -#include - -int main(void) -{ - int nb,nt,nl,c; - - nb=nt=nl=0; - - while((c=getchar())!=EOF) - { - if(c==' ') - ++nb; - if(c=='\t') - ++nt; - if(c=='\n') - ++nl; - } - printf("No. of Blanks is %d,No. of Tabs is %d and No. of Newlines is %d",nb,nt,nl); - -return 0; -} - diff --git a/languages/cprogs/alloc_afree.c b/languages/cprogs/alloc_afree.c deleted file mode 100644 index 31cf373c..00000000 --- a/languages/cprogs/alloc_afree.c +++ /dev/null @@ -1,38 +0,0 @@ -#define ALLOCSIZE 1000 /* size of available space */ - -static char allocbuf[ALLOCSIZE]; /* storage for alloc */ -static char *allocp = allocbuf; /* next free position */ - -char *alloc(int n) /* return pointer to n characters */ -{ - if( allocbuf + ALLOCSIZE - allocp >= n) - { - allocp += n; - return allocp - n; /* old p */ - } - else - return 0; -} - - -void afree(char *p) /* free storage pointed to by p */ -{ - if(p >= allocbuf && p < allocbuf + ALLOCSIZE) - allocp = p; -} - -int main(void) -{ - char *p; - printf("%p\n",allocp); - - p=alloc(100); - printf("%p\n",allocp); - - afree(p); - printf("%p\n",allocp); - - return 0; -} - - diff --git a/languages/cprogs/anylonglinelen.c b/languages/cprogs/anylonglinelen.c deleted file mode 100644 index d55e45e6..00000000 --- a/languages/cprogs/anylonglinelen.c +++ /dev/null @@ -1,62 +0,0 @@ -/* Program to print the longest line. - This program prints the length of any-length line with as much possible text it can hold */ - -#include - -#define MAXLINE 1000 - -int getline(char line[],int lim); -void copy(char to[],char from[]); - -int main(void) -{ - int len,max; - char line[MAXLINE],maxline[MAXLINE]; - - max = 0; - - while((len=getline(line,MAXLINE)) > 0) - { - printf("%d\t%s",len,line); - if(len > max) - { - max=len; - copy(maxline,line); - } - } - printf("%s",maxline); - -return 0; -} - -int getline(char s[],int lim) -{ - int i,j,c; - - for(i=0,j=0;(c=getchar())!=EOF && c!= '\n';++i) - if( i < lim-2 ) - { - s[i] = c; - ++j; - } - if( c == '\n') - { - s[i] = c; - ++i; - ++j; - } - s[j] = '\0'; - - return i; -} - -void copy(char to[],char from[]) -{ - int i; - - i=0; - - while((to[i]=from[i]) != '\0') - ++i; -} - diff --git a/languages/cprogs/atoiv2.c b/languages/cprogs/atoiv2.c deleted file mode 100644 index 40868701..00000000 --- a/languages/cprogs/atoiv2.c +++ /dev/null @@ -1,33 +0,0 @@ -/* Ex5.6 */ - -#include -#include - -int atoiv2(char *); - -int main(void) { - char *s = "1234"; - int ret; - - ret = atoiv2(s); - - printf("%d", ret); - - return 0; -} - -int atoiv2(char *s) { - int n, sign; - - for (; isspace(*s); s++) /* skip white space */ - ; - sign = (*s == '-') ? -1 : 1; - - if (*s == '+' || *s == '-') - s++; - for (n = 0; isdigit(*s); s++) - n = 10 * n + *s - '0'; - - return sign * n; -} - diff --git a/languages/cprogs/binsearch.c b/languages/cprogs/binsearch.c deleted file mode 100644 index 87beeaf6..00000000 --- a/languages/cprogs/binsearch.c +++ /dev/null @@ -1,36 +0,0 @@ -/* binsearch: Implementation of Binary Search,In the array v[],search for n in the binary way*/ - -#include - -int binsearch(int x,int v[],int n); - -int main(void) -{ - int arr[]={2,4,5,7,8,9,11,23,45,50}; - int x,n; - - printf("%d",binsearch(9,arr,10)); - - return 0; -} - -int binsearch(int x,int v[],int n) -{ - int low,high,mid; - - low=0; - high=n-1; - - while(low v[mid]) - low = mid + 1; - else - return mid; - } - return -1; -} diff --git a/languages/cprogs/bitcount.c b/languages/cprogs/bitcount.c deleted file mode 100644 index fb9616ff..00000000 --- a/languages/cprogs/bitcount.c +++ /dev/null @@ -1,22 +0,0 @@ -/* bitcount : count 1 bits in x */ -#include - -int bitcount(unsigned x); - -int main(void) -{ - printf("%d",bitcount((unsigned)255)); - - return 0; -} - -int bitcount(unsigned x) -{ - int b; - - for(b=0; x!= 0; x >>=1) - if( x & 01) - b++; - return b; -} - diff --git a/languages/cprogs/counts.c b/languages/cprogs/counts.c deleted file mode 100644 index c8005243..00000000 --- a/languages/cprogs/counts.c +++ /dev/null @@ -1,41 +0,0 @@ -/* Program to count the digits,white spaces and others */ - -#include - -int main(void) -{ - int c,i,nwhite,nother,ndigit[10]; - - nwhite=nother=0; - - for(i=0;i<10;i++) - ndigit[i]=0; - - while((c=getchar())!=EOF) - { - - switch(c) - { - case '0':case '1':case '2':case '3':case '4':case '5':case '6':case '7':case '8':case '9': - ndigit[c-'0']++; - break; - case ' ': - case '\t': - case '\n': - nwhite++; - break; - default: - nother++; - break; - - } - } - - printf("digits ="); - for(i=0;i<10;i++) - printf("%d",ndigit[i]); - printf(", white space = %d, other = %d \n",nwhite,nother); - - return 0; -} - diff --git a/languages/cprogs/day_datev3.c b/languages/cprogs/day_datev3.c deleted file mode 100644 index 76c07ca2..00000000 --- a/languages/cprogs/day_datev3.c +++ /dev/null @@ -1,55 +0,0 @@ -#include - -static char daytab[2][13] = { - {0,31,28,31,30,31,30,31,31,30,31,30,31}, - {0,31,29,31,30,31,30,31,31,30,31,30,31} -}; - -int day_of_year(int year,int month,int day); -void month_day(int year,int yearday,int *pmonth,int *pday); - -int main(void) -{ - int day,dat,mon; - - day=day_of_year(1981,10,2); - printf("%d\n",day); - - month_day(1981,252,&mon,&dat); - printf("%d,%d",mon,dat); - - return 0; -} - -/* day_of_year: set day of year from month and day */ -int day_of_year(int year,int month,int day) -{ - int leap; - char *p; - - leap = year%4 == 0 && year % 100 !=0 || year %400 == 0; - p = daytab[leap]; - - while(--month) - day += *++p; - return day; -} - -/* month_day: set month, day from day of year */ -void month_day(int year,int yearday,int *pmonth,int *pday) -{ - int leap; - char *p; - - leap = year%4 == 0 && year %100 !=0 || year % 400 == 0; - - p = daytab[leap]; - - while(yearday > *++p) - yearday -= *p; - - *pmonth = p - *(daytab + leap); - *pday = yearday; -} - - diff --git a/languages/cprogs/dcl.c b/languages/cprogs/dcl.c deleted file mode 100644 index 41724bb7..00000000 --- a/languages/cprogs/dcl.c +++ /dev/null @@ -1,159 +0,0 @@ -/* DCL: A Recursive Descent Parser */ - -/* dcl: parse a declarator */ - -void dcl(void) -{ - int ns; - - for(ns=0;gettoken()=='*';) /* count *'s */ - ns++; - - dirdcl(); - while(ns-- > 0) - strcat(out,"pointer to"); -} - -/* dirdcl: parse a direct declarator */ - -void dirdcl(void) -{ - int type; - - if(tokentype == '(') /* dcl */ - { - dcl(); - - if(tokentype != ')') - printf("error: missing ) \n"); - } - else if(tokentype == NAME) /* variable name */ - strcpy(name,token); - else - printf("error: expected name or (dcl) \n"); - - while((type=gettoken()) == PARENS || type == BRACKETS ) - if(type = PARENS) - strcat(out,"function returning"); - else - { - strcat(out,"arg"); - strcat(out,token); - strcat(out,"of"); - } -} - - -#include -#include -#include - -#define MAXTOKEN 100 - -enum {NAME,PARENS,BRACKETS}; - -void dcl(void); -void directdcl(void); -int gettoken(void); -int tokentype; /* type of last token */ -char token[MAXTOKEN]; /* last token string */ -char name[MAXTOKEN]; /* identifier name */ -char datatype[MAXTOKEN]; /* data type=char, int etc */ -char out[1000]; /* output string */ - -int main(void) -{ - while(gettoken()!=EOF) - { - strcpy(datatype,token); - out[0]='\0'; - dcl(); - - if(tokentype != '\n') - printf("syntax error \n"); - - printf(" %s %s %s \n",name,out,datatype); - } - -return 0; -} - -int gettoken(void) -{ - int i,getch(void); - void ungetch(int); - char *p = token; - - while((c=getch()) == ' ' || c == '\t') - ; - - if( c == '(') - { - if((c=getch()) == ')') - { - strcpy(token,"()"); - return tokentype = PARENS; - } - else - { - ungetch(c); - return tokentype = '('; - } - else if ( c == '[') - { - for(*p++ = c; (*p++ = getch()) != ']';) - ; - *p = '\0'; - return tokentype = BRACKETS; - } - else if ( isalpha(c)) - { - for(*p++ =c; isalnum(c=getch());) - *p++ = c; - *p = '\0'; - ungetch(c); - return tokentype = NAME; - } - else - return tokentype =c; -} - -#define BUFSIZE 100 - -char buf[BUFSIZE]; /* buffer for ungetch */ -int bufp = 0; /* next free position in buf */ - -int getch(void) /* get a (possibly pushed back) character */ -{ - return (bufp > 0) ? buf[--bufp]:getchar(); -} - -void ungetch(int c) /* push a character back on input */ -{ - if(bufp >= BUFSIZE) - printf("ungetch: too many characters \n"); - else - buf[bufp++] = c; -} - - - - - - - - - - - - - - - - - - - - - - diff --git a/languages/cprogs/endian.c b/languages/cprogs/endian.c deleted file mode 100644 index c0b7559d..00000000 --- a/languages/cprogs/endian.c +++ /dev/null @@ -1,11 +0,0 @@ -#include -int main(int argc, char *argv[]) -{ - int a=0x99000011; - unsigned char *c = (unsigned char *) (&a); - if (*c == 0x11) - printf("little endian\n"); - else - printf("big endian\n"); - -} diff --git a/languages/cprogs/eratosthenes.c b/languages/cprogs/eratosthenes.c deleted file mode 100644 index 5d6ade03..00000000 --- a/languages/cprogs/eratosthenes.c +++ /dev/null @@ -1,31 +0,0 @@ -/** - * Program illustrating sieve of Eratosthenes. - * - **/ - -#include - -#define N 100 - -int main(int argc, char *argv[]) { - int nums[N]; - - for (int i = 2; i < N; ++i) { - nums[i] = i; - } - - for (int i = 2; i < N; ++i) { - for (int j = i; j < N; ++j) { - if (i != j && nums[j] != 0 && (nums[j] % i == 0)) { - nums[j] = 0; - } - } - } - - for (int k = 2; k < N; ++k) { - if (nums[k] != 0) { - printf("%d\n", nums[k]); - } - } - -} diff --git a/languages/cprogs/fork1.c b/languages/cprogs/fork1.c deleted file mode 100644 index d9dd8723..00000000 --- a/languages/cprogs/fork1.c +++ /dev/null @@ -1,8 +0,0 @@ -#include - -int main() -{ - int pid; - pid = fork(); - printf("%d \n",pid); -} diff --git a/languages/cprogs/fsize.c b/languages/cprogs/fsize.c deleted file mode 100644 index 977b7dba..00000000 --- a/languages/cprogs/fsize.c +++ /dev/null @@ -1,133 +0,0 @@ -/* Print File Sizes */ -#include -#include -#include /* flags for read and write */ -#include /* typedefs */ -#include /* structure returned by stat */ -#include "dirent.h" - -void fsize(char *); - -/* print file sizes */ -int main(int argc,char **argv) -{ - if(argc == 1) /* default : current directory */ - fsize("."); - else - while(--argc > 0) - fsize(*++argv); - return 0; -} - -int stat(char *,struct stat *); -void dirwalk(char *,void (*fcn)(char *)); - -/* fsize: print size of file "name" */ -void fsize(char *name) -{ - struct stat stbuf; - - if(stat(name,&stbuf) == -1) - { - fprintf(stderr,"fsize: Can't access %s \n",name); - return; - } - if((stbuf.st_mode & S_IFMT) == S_IFDIR) - dirwalk(name,fsize); - printf("%8ld %s \n",stbuf.st_size,name); -} - - -#define MAX_PATH 1024 - -/* dirwalk: apply fcn to all files in dir */ -void dirwalk(char *dir,void (*fcn)(char *)) -{ - char name[MAX_PATH]; - Dirent *dp; - DIR *dfd; - - if((dfd = opendir(dir)) == NULL) - { - fprintf(stderr,"dirwalk: can't open %s\n",dir); - return; - } - - while((dp = readdir(dfd)) != NULL) - { - if(strcmp(dp->name,".") == 0 || strcmp(dp->name,"..") == 0) - continue; - if(strlen(dir)+strlen(dp->name)+2 > sizeof(name)) - fprintf(stderr,"dirwalk: name %s/ %s too long \n",dir,dp->name); - else - { - sprintf(name,"%s/%s",dir,dp->name); - (*fcn)(name); - } - } - closeddir(dfd); -} - - -#ifndef DIRSIZ -#define DIRSIZ 14 -#endif - -struct direct /* directory entry */ -{ - ino_t d_ino; /* inode number */ - char d_name[DIRSIZ]; /* long name does not have '\0' */ -}; - -int fstat(int fd,struct stat *); - -/* opendir: open a directory for readdir calls */ - -DIR *opendir(char *dirname) -{ - int fd; - struct stat stbuf; - DIR *dp; - - if((fd = open(dirname,O_RDONLY,0)) == -1 - || fstat(fd,&stbuf) == -1 - || (stbuf.st_mode & S_IFMT) != S_IFDIR - || (dp = (DIR *)malloc(sizeof(DIR))) == NULL) - return NULL; - dp->fd = fd; - return dp; -} - -/* closedir: close directory opened by opendir */ -void closedir(DIR *dp) -{ - if(dp) - { - close(dp->fd); - free(dp); - } -} - - -#include /* local directory structure */ -/* readdir: read directory entries in sequence */ - -Dirent *readdir(DIR *dp) -{ - struct direct dirbuf; /* local directory structure */ - static Dirent d; /* return: portable structure */ - - while(read(dp->fd,(char *)&dirbuf,sizeof(dirbuf)) == sizeof(dirbuf)) - { - if(dirbuf.d_ino= 0) - continue; - d.ino = dirbuf.d_ino; - strncpy(d.name,dirbuf.d_name,DIRSIZ); - d.name[DIRSIZ] = '\0'; - return &d; - } - - return NULL; -} - - diff --git a/languages/cprogs/getbits.c b/languages/cprogs/getbits.c deleted file mode 100644 index aaa296ad..00000000 --- a/languages/cprogs/getbits.c +++ /dev/null @@ -1,17 +0,0 @@ -/* getbits: get n bits from the position p */ - -#include - -unsigned getbits(unsigned x,int p,int n); - -int main(void) -{ - printf("%u",getbits((unsigned)8,3,1)); -} - -unsigned getbits(unsigned x,int p,int n) -{ - return (x >> (p+1-n)) & ~(~0 << n); -} - - diff --git a/languages/cprogs/getline_woandr.c b/languages/cprogs/getline_woandr.c deleted file mode 100644 index 3bd85308..00000000 --- a/languages/cprogs/getline_woandr.c +++ /dev/null @@ -1,58 +0,0 @@ -/* Program demonstrates the former getline forloop without && and ||. -Also demonstrates enum data type usage */ - -#include -#define MAXLINE 1000 - -int getline(char line[],int maxline); - -int main(void) -{ - char line[MAXLINE]; - - getline(line,MAXLINE); - - printf("%s",line); - - return 0; -} - -int getline(char s[],int lim) -{ - int c,i; - enum values{NO=0,YES}; - enum values proceed; - - proceed= YES; - - i =0; - - while(proceed == YES) - { - if( i > lim - 1) - proceed = NO; - else if((c=getchar()) == EOF) - proceed = NO; - else if( c == '\n') - proceed = NO; - else - { - s[i] = c; - ++i; - proceed = YES; - } - } - if ( c == '\n') - { - s[i] = c; - ++i; - } - s[i] = '\0'; - - return i; -} - - - - - diff --git a/languages/cprogs/getpass1.c b/languages/cprogs/getpass1.c deleted file mode 100644 index af10935a..00000000 --- a/languages/cprogs/getpass1.c +++ /dev/null @@ -1,68 +0,0 @@ -#include -#include -#include -#include -#include - -static int gp_save_term(int fd, struct termios *tios) -{ - return tcgetattr(fd, tios); -} - -static int gp_load_term(int fd, struct termios *tios) -{ - return tcsetattr(fd, TCSAFLUSH, tios); -} - -static void gp_set_password_flags(struct termios *tios) -{ - tios->c_lflag &= ~ECHO; /* disable echo */ - tios->c_lflag &= ~ISIG; /* ignore signals */ -} - -/* Get a password of max len-1 chars and store it in dest. - * The string is anyway nul terminated, the echo disabled. */ -int palla_getpass(char *dest, size_t len) -{ - unsigned int i; /* character index inside pass */ - int ttyfd = fileno(stdin); - struct termios orig, new; - - /* sanity check */ - if (!len || !dest) - return -1; - - /* Save the old status */ - if (gp_save_term(ttyfd, &orig) == -1) - return -1; - new = orig; /* copy it in the new */ - gp_set_password_flags(&new); /* set the right flags */ - if (gp_load_term(ttyfd, &new) == -1) /* load the new term config */ - return -1; - - /* Now we are in "password mode", get the input */ - i = 0; - while(i < (len-1)) { - char c; - if (read(ttyfd, &c, 1) <= 0) - break; - if (c == '\n') - break; - dest[i] = c; - i++; - } - dest[i] = '\0'; /* add the nul term */ - if (gp_load_term(ttyfd, &orig) == -1) /* restore the old term */ - return -1; /* sorry, the term is left unsane */ - return i; -} - -int main(void) -{ - char dest[10]; - printf("password: "); - fflush(stdout); - palla_getpass(dest, 10); - printf("'%s'\n", dest); - return 0; -} diff --git a/languages/cprogs/glat17.c b/languages/cprogs/glat17.c deleted file mode 100644 index de5f0cfc..00000000 --- a/languages/cprogs/glat17.c +++ /dev/null @@ -1,40 +0,0 @@ -#include -#include -unsigned long long int countones(unsigned long long int); -int main(void) -{ - unsigned long long int i,cn; - - for(i = 1; i<=(ULLONG_MAX - 1); ++i) - { - cn = countones(i); - if( i == cn) - { - printf("%d \n",i); - fflush(stdout); - } - } - - return 0; -} - -unsigned long long int countones(unsigned long long int i) -{ - static unsigned long long int count = 0; - int digit; - - while((i/10) >= 1) - { - digit = i % 10; - - if(digit == 1) - count++; - i /= 10; - } - if( i == 1) - count++; - - return count; -} - - diff --git a/languages/cprogs/htoi.c b/languages/cprogs/htoi.c deleted file mode 100644 index 4af636a3..00000000 --- a/languages/cprogs/htoi.c +++ /dev/null @@ -1,70 +0,0 @@ -#include -#define MAXLINE 100 - -#define YES 1 -#define NO 0 - -int getline(char line[],int maxline); -int htoi(char s[]); - -int main(void) -{ - char line[MAXLINE]; - int value; - - getline(line,MAXLINE); - value=htoi(line); - - printf("The value of %s is %d",line,value); - - return 0; -} - -int getline(char s[],int lim) -{ - int c,i; - - for(i=0;i='0' && s[i] <='9') - hexdigit= s[i] - '0'; - else if(s[i] >='a' && s[i] <='f') - hexdigit= s[i] -'a' + 10; - else if(s[i] >='A' && s[i] <='F') - hexdigit= s[i] -'A' + 10; - else - inhex = NO; - - if(inhex == YES) - n = 16 * n + hexdigit; - } - return n; -} - - diff --git a/languages/cprogs/leap.c b/languages/cprogs/leap.c deleted file mode 100644 index b1526433..00000000 --- a/languages/cprogs/leap.c +++ /dev/null @@ -1,15 +0,0 @@ -/* Program for the logic of leap year */ - -#include -#define YEAR 3000 - -int main(void) -{ - if( ((YEAR % 4 == 0) && (YEAR % 100 != 0)) || (YEAR % 400 == 0) ) - printf("The Year is a Leap Year"); - else - printf("The Year is Not a Leap Year"); - - return 0; -} - diff --git a/languages/cprogs/likefind.c b/languages/cprogs/likefind.c deleted file mode 100644 index a03fb451..00000000 --- a/languages/cprogs/likefind.c +++ /dev/null @@ -1,66 +0,0 @@ -#include -#include -#define MAXLINE 1000 - -int getline(char *line,int max); - -/* find: print lines that match pattern from the 1st arg - ---------------------------- - find -nx pattern - ---------------------------- -*/ - -int main(int argc,char *argv[]) -{ - char line[MAXLINE]; - long lineno = 0; - int c,except =0,number =0,found =0; - - while(--argc > 0 && (*++argv)[0] == '-') - while(c = *++argv[0]) - switch(c) - { - case 'x': - except =1; - break; - case 'n': - number =1; - break; - default: - printf("find: illegal option %c\n",c); - argc =0; - found = -1; - break; - } - if(argc != 1) - printf("Usage: find -x -n pattern \n"); - else - while(getline(line,MAXLINE) >0) - { - lineno++; - if((strstr(line,*argv)!=NULL) != except) - { - if(number) - printf("%ld:",lineno); - printf("%s",line); - found++; - } - } - return found; -} - -int getline(char *s,int lim) -{ - int c; - char *t=s; - - while(--lim > 0 && (c=getchar())!=EOF && c!='\n') - *s++ =c; - - if(c=='\n') - *s++=c; - *s ='\0'; - - return s -t; -} - diff --git a/languages/cprogs/likegrep.c b/languages/cprogs/likegrep.c deleted file mode 100644 index 3aae9099..00000000 --- a/languages/cprogs/likegrep.c +++ /dev/null @@ -1,42 +0,0 @@ -/* Ex5.6 */ - -#include -#include -#define MAXLINE 1000 - -int getline(char *line,int max); - -/* find: prints lines that match the pattern from the 1st argument */ - -int main(int argc,char *argv[]) -{ - char line[MAXLINE]; - int found = 0; - - if(argc!=2) - printf("Usage:find pattern\n"); - else - while(getline(line,MAXLINE)>0) - if(strstr(line,argv[1]) != NULL) - { - printf("%s",line); - found++; - } - return found; -} - -int getline(char *s,int lim) -{ - int c; - char *t=s; - - while(--lim > 0 && (c=getchar())!=EOF && c!='\n') - *s++=c; - - if(c=='\n') - *s++=c; - *s='\0'; - - return s-t; -} - diff --git a/languages/cprogs/long_extnal.c b/languages/cprogs/long_extnal.c deleted file mode 100644 index 419e1fee..00000000 --- a/languages/cprogs/long_extnal.c +++ /dev/null @@ -1,50 +0,0 @@ -/* Longest Line Program using External Variables*/ - -#include -#define MAXLEN 1000 - -char line[MAXLEN],longest[MAXLEN]; - -int getline(void); -void copy(void); - -int main(void) -{ - int len,max; - max = 0; - while((len=getline())>0) - { - if( len > max) - { - max = len; - copy(); - } - } - if( max > 0) - printf("%s",longest); - - return 0; -} -int getline() -{ - int c,i; - - for(i=0;i -#include - -int main(int argc, char *argv[]) -{ - mkdir("foobar",'644'); -} diff --git a/languages/cprogs/mygetchar.c b/languages/cprogs/mygetchar.c deleted file mode 100644 index 48ccdcde..00000000 --- a/languages/cprogs/mygetchar.c +++ /dev/null @@ -1,20 +0,0 @@ -#include - -int mygetchar(void); - -int main(void) -{ - int c; - c = mygetchar(); - - printf("%c",c); - - return 0; -} - -int mygetchar(void) -{ - char c; - return (read(0,&c,1)==1)?(unsigned char)c:EOF; -} - diff --git a/languages/cprogs/numlinesort.c b/languages/cprogs/numlinesort.c deleted file mode 100644 index fd732641..00000000 --- a/languages/cprogs/numlinesort.c +++ /dev/null @@ -1,166 +0,0 @@ -/* Sorting program, with a provision of sorting lines numerically as well */ -#include -#include -#define MAXLINES 5000 /* maximum number of lines to be sorted */ -char *lineptr[MAXLINES]; /* pointers to text lines */ - -int readlines(char *lineptr[],int nlines); -void writelines(char *lineptr[],int nlines); - -void myqsort(void *lineptr[],int left,int right,int (*comp)(void *,void *)); - -int numcmp(char *,char *); - -/* sort input lines */ - -int main(int argc,char *argv[]) -{ - int nlines; /* number of input lines read */ - int numeric = 0; /* if numeric sort */ - - if( argc > 1 && strcmp(argv[1],"-n") == 0) - numeric = 1; - if( (nlines = readlines(lineptr,MAXLINES)) >= 0) - { - myqsort((void **)lineptr,0,nlines -1,(int (*)(void *,void *))(numeric ? numcmp:strcmp)); - writelines(lineptr,nlines); - return 0; - } - else - { - printf("input too big to sort \n"); - return 1; - } -} - -/* myqsort: sort v[left] .. v[right] into increasing order */ - -void myqsort(void *v[],int left,int right,int (*comp)(void *,void *)) -{ - int i,last; - void swap(void *v[],int,int); - if(left >= right) /* do nothing if array contains fewer than two elements */ - return; - - swap(v,left,(left+right)/2); - last = left; - - for(i = left + 1; i <= right; i++) - if((*comp)(v[i],v[left])<0) - swap(v,++last,i); - - swap(v,left,last); - myqsort(v,left,last-1,comp); - myqsort(v,last+1,right,comp); -} - -#include - -/* numcmp: compare s1 and s2 numerically */ - -int numcmp(char *s1,char *s2) -{ - double v1,v2; - v1 = atof(s1); - v2 = atof(s2); - - if( v1 < v2 ) - return -1; - else if ( v1 > v2) - return 1; - else - return 0; -} - -void swap(void *v[],int i,int j) -{ - void *temp; - temp = v[i]; - v[i] = v[j]; - v[j] = temp; -} - -/* for realines and writelines */ - -#define MAXLEN 1000 - -int getline(char *,int); -char *alloc(int); - -/* readlines: read input line */ - -int readlines(char *lineptr[],int maxlines) -{ - int len,nlines; - char *p,line[MAXLEN]; - - nlines = 0; - - while((len=getline(line,MAXLEN)) > 0) - if(nlines >= maxlines || (p=alloc(len)) == NULL) - return -1; - else - { - line[len-1] = '\0'; /* delete newline */ - strcpy(p,line); - lineptr[nlines++] = p; - } - return nlines; -} - -/* writelines: write output line */ - -void writelines(char *lineptr[],int nlines) -{ - int i; - for(i =0;i < nlines;i++) - printf("%s\n",lineptr[i]); -} - - -/* for *alloc(int) */ - -#define ALLOCSIZE 10000 - -static char allocbuf[ALLOCSIZE]; -static char *allocp = allocbuf; - -char *alloc(int n) -{ - if(allocbuf + ALLOCSIZE - allocp >= n) - { - allocp += n; - return allocp -n; - } - else - return 0; -} - -void afree(char *p) -{ - if(p >= allocbuf && p < allocbuf + ALLOCSIZE) - allocp = p; -} - - - -/* getline: read a line into s and return its length */ - -int getline(char s[],int lim) -{ - int c,i; - - for(i=0;i -/* echo: command line arguments; 1st version */ - -int main(int argc,char *argv[]) -{ - int i; - - for( i = 1 ; i < argc ;i++ ) - printf("%s %s",argv[i],(i < argc -1)? " ": ""); - printf("\n"); - return 0; -} - - diff --git a/languages/cprogs/pgechov2.c b/languages/cprogs/pgechov2.c deleted file mode 100644 index 0c7be6ca..00000000 --- a/languages/cprogs/pgechov2.c +++ /dev/null @@ -1,10 +0,0 @@ -#include -/* echo command-line arguments: 2nd version */ -int main(int argc,char *argv[]) -{ - while(--argc > 0) - printf("%s %s",*++argv,(argc > 1)? " ": ""); - printf("\n"); - return 0; -} - diff --git a/languages/cprogs/pgechov3.c b/languages/cprogs/pgechov3.c deleted file mode 100644 index bb1c53d2..00000000 --- a/languages/cprogs/pgechov3.c +++ /dev/null @@ -1,9 +0,0 @@ -#include -/*echo command - line arguments: 3rd version */ -int main(int argc,char *argv[]) -{ - while( --argc >0) - printf((argc > 1)?"%s ":"%s",*++argv); - printf("\n"); -} - diff --git a/languages/cprogs/prepro1.c b/languages/cprogs/prepro1.c deleted file mode 100644 index d944f2be..00000000 --- a/languages/cprogs/prepro1.c +++ /dev/null @@ -1,14 +0,0 @@ -/* # operator in preprocessor */ -#include - -#define dprint(expr) printf(#expr " = %d \n",expr); - -int main(void) -{ - int x=10,y=5; - - dprint(x/y); - - return 0; -} - diff --git a/languages/cprogs/prepro2.c b/languages/cprogs/prepro2.c deleted file mode 100644 index 79ddd243..00000000 --- a/languages/cprogs/prepro2.c +++ /dev/null @@ -1,14 +0,0 @@ -/* ## preprocessor operator */ - -#include - -#define paste(front,back) front ## back - -int main(void) -{ - int i=paste(10,50); - printf("%d",i); - - return 0; -} - diff --git a/languages/cprogs/printd.c b/languages/cprogs/printd.c deleted file mode 100644 index ae71b154..00000000 --- a/languages/cprogs/printd.c +++ /dev/null @@ -1,30 +0,0 @@ -/* Recursion example; consider printing a number as a character string */ - -#include - -void printd(int n); - -int main(void) -{ - int n; - n = 15000; - - printd(n); - - return 0; -} - -void printd(int n) -{ - if(n < 0) - { - putchar('-'); - n = -n; - } - if(n / 10) - printd(n/10); - - putchar(n%10+'0'); -} - - diff --git a/languages/cprogs/quicksort.c b/languages/cprogs/quicksort.c deleted file mode 100644 index a71a482f..00000000 --- a/languages/cprogs/quicksort.c +++ /dev/null @@ -1,64 +0,0 @@ -/* quicksort: example of recursive sorting - Developed by C.A.R. Hoare in 1962. Given an array,one element is chosen and the others are - partitioned into two subsets - those less than the partition element and those greater than or - equal to it. The same process is then applied recursively to the two subsets. When a subset has fewer than two elements, it does not need any sorting; this stops the recursion */ - -#include - -void qsort(int v[],int left,int right); -void swap(int v[],int i,int j); - -int main(void) -{ - int i,left,right,v[10]={43,53,12,64,15,67,87,10,6,90}; - left=0; - right=9; - - printf("Unsorted Array\n"); - for(i=0;i<=9;++i) - printf(" %d",v[i]); - qsort(v,left,right); - - printf("\nSorted Array\n"); - for(i=0;i<=9;++i) - printf(" %d",v[i]); - - return 0; -} - -void qsort(int v[],int left,int right) -{ - int i,last; - - if(left>=right) - return; - - swap(v,left,(left+right)/2); - - last=left; - - for(i=left+1;i<=right;i++) - if(v[i] < v[left]) - swap(v,++last,i); - swap(v,left,last); - - qsort(v,left,last-1); - - qsort(v,last+1,right); -} - -/* swap: interchange v[i] and v[j] */ - -void swap(int v[],int i,int j) -{ - int temp; - - temp = v[i]; - - v[i] = v[j]; - - v[j] = temp; -} - - - diff --git a/languages/cprogs/rot13.c b/languages/cprogs/rot13.c deleted file mode 100644 index e80a5615..00000000 --- a/languages/cprogs/rot13.c +++ /dev/null @@ -1,38 +0,0 @@ -/* rot13 algorithm. Very Simple and Interesting */ - -#include -#define ROT 13 - -int main(void) -{ - int c,e; - - while((c=getchar())!=EOF) - { - if(c >='A' && c <='Z') - { - if((e = c + ROT) <= 'Z') - putchar(e); - else - { - e = c - ROT; - putchar(e); - } - } - else if(c >='a' && c <='z') - { - if((e= c + ROT) <= 'z') - putchar(e); - else - { - e = c - ROT; - putchar(e); - } - } - else - putchar(c); - } - -return 0; -} - diff --git a/languages/cprogs/sample_template.c b/languages/cprogs/sample_template.c deleted file mode 100644 index 89dda472..00000000 --- a/languages/cprogs/sample_template.c +++ /dev/null @@ -1,5 +0,0 @@ -#include - -int main(int argc, char *argv[]) { - printf("This program needs to be replaced."); -} \ No newline at end of file diff --git a/languages/cprogs/sec_8.3_open_creat.c b/languages/cprogs/sec_8.3_open_creat.c index 759ce34c..96f684ae 100644 --- a/languages/cprogs/sec_8.3_open_creat.c +++ b/languages/cprogs/sec_8.3_open_creat.c @@ -2,7 +2,7 @@ #include #include #include -#include +#include #define PERMS 0666 /* RW for owner, group and others */ diff --git a/languages/cprogs/sec_8_2_read_write.c b/languages/cprogs/sec_8_2_read_write.c index 9d9e7151..42f96345 100644 --- a/languages/cprogs/sec_8_2_read_write.c +++ b/languages/cprogs/sec_8_2_read_write.c @@ -1,8 +1,6 @@ /*copy input to output */ #include -#include - #define BUFSIZ 1024 int main() /* copy input to output */ diff --git a/languages/cprogs/shellsort.c b/languages/cprogs/shellsort.c deleted file mode 100644 index 7356da4d..00000000 --- a/languages/cprogs/shellsort.c +++ /dev/null @@ -1,39 +0,0 @@ -#include -#include - -static void shell_sort(int a[], int size) -{ - int i, j; - int h=1; - do { - h = h * 3 + 1; - }while (h <= size); - do { - h /= 3; - for (i = h; i < size; i++) - { - int v = a[i]; - for (j = i; j >= h && a[j - h] > v; j -= h) - a[j] = a[j -h]; - if (i != j) - a[j] = v; - } - }while (h != 1); -} - -int main(int argc, char *argv[]) -{ - int *a; - int i; - - a = (int *)malloc((argc - 1) * sizeof(int)); - for (i = 0; i < argc - 1; i++) - a[i] = atoi(argv[i+1]); - shell_sort(a, argc); - - for (i = 0; i < argc -1; i++) - printf("%d", a[i]); - printf("\n"); - free(a); - return 0; -} diff --git a/languages/cprogs/sizeof_various.c b/languages/cprogs/sizeof_various.c deleted file mode 100644 index ba9dfb6b..00000000 --- a/languages/cprogs/sizeof_various.c +++ /dev/null @@ -1,12 +0,0 @@ - -#include -int main(int argc, char *argv[]) -{ - int i=10; - char c='a'; - float j=1.0; - printf("The size of int is %zu\n", sizeof i); - printf("The size of char is %zu\n", sizeof c); - printf("The size of float is %zu\n", sizeof j); -} - diff --git a/languages/cprogs/sort.c b/languages/cprogs/sort.c deleted file mode 100644 index 65d70bff..00000000 --- a/languages/cprogs/sort.c +++ /dev/null @@ -1,125 +0,0 @@ -#include -#include - -#define MAXLINES 5000 /* max #lines to be sorted */ - -char *lineptr[MAXLINES]; - -int readlines(char *lineptr[],int nlines); -void writelines(char *lineptr[],int nlines); - -void qsort(char *lineptr[],int left,int right); - -/* sort input lines */ - -int main(void) -{ - int nlines; /* number of input lines read */ - - if((nlines = readlines(lineptr,MAXLINES)) >= 0) - { - qsort(lineptr,0,nlines-1); - writelines(lineptr,nlines); - return 0; - } - else - { - printf("error: input too big to sort \n"); - return 1; - } -} - -#define MAXLEN 1000 /* max length of any input line */ -int getline(char *,int); -char *alloc(int); - -/* readlines: read input lines */ -int readlines(char *lineptr[],int maxlines) -{ - int len,nlines; - char *p,line[MAXLEN]; - - nlines=0; - - while((len=getline(line,MAXLEN)) > 0) - if(nlines >= maxlines || (p=alloc(len)) == NULL) - return -1; - else - { - line[len-1] = '\0'; - strcpy(p,line); - lineptr[nlines++]=p; - } - return nlines; -} - -/* writelines: write output lines */ -void writelines(char *lineptr[],int nlines) -{ - int i; - for(i=0;i= right) - return; - swap(v,left,(left+right)/2); - - last = left; - - for(i=left+1;i<=right;i++) - if(strcmp(v[i],v[left])<0) - swap(v,++last,i); - swap(v,left,last); - qsort(v,left,last-1); - qsort(v,last+1,right); -} - -/* swap: interchange v[i] and v[j] */ - -void swap(char *v[],int i,int j) -{ - char *temp; - - temp=v[i]; - v[i]=v[j]; - v[j]=temp; -} - -#define ALLOCSIZE 10000 /* size of available space */ - -static char allocbuf[ALLOCSIZE]; /* storage for alloc */ -static char *allocp = allocbuf; /* next free position */ - -char *alloc(int n) /* return pointer to n characters */ -{ - if(allocbuf + ALLOCSIZE - allocp >= n) - { - allocp += n; - return allocp -n; - } - else - return 0; -} - -int getline(char *s,int lim) -{ - int c; - char *t=s; - - while(--lim >0 && (c=getchar())!=EOF && c!='\n') - *s++ = c; - if( c == '\n') - *s++ = c; - - *s= '\0'; - - return s-t; -} - diff --git a/languages/cprogs/sortv2.c b/languages/cprogs/sortv2.c deleted file mode 100644 index 11e10323..00000000 --- a/languages/cprogs/sortv2.c +++ /dev/null @@ -1,131 +0,0 @@ -#include -#include - -#define MAXLINES 5000 /* max #lines to be sorted */ - -char *lineptr[MAXLINES]; -char linestor[MAXLINES]; - -int readlines(char *lineptr[],char *linestor,int nlines); -void writelines(char *lineptr[],int nlines); - -void qsort(char *lineptr[],int left,int right); - -/* sort input lines */ - -int main(void) -{ - int nlines; /* number of input lines read */ - - if((nlines = readlines(lineptr,linestor,MAXLINES)) >= 0) - { - qsort(lineptr,0,nlines-1); - writelines(lineptr,nlines); - return 0; - } - else - { - printf("error: input too big to sort \n"); - return 1; - } -} - -#define MAXLEN 1000 /* max length of any input line */ -#define MAXSTOR 5000 - -int getline(char *,int); -char *alloc(int); - -/* readlines: read input lines */ -int readlines(char *lineptr[],char *linestor,int maxlines) -{ - int len,nlines; - char line[MAXLEN]; - char *p = linestor; - char *linestop = linestor + MAXSTOR; - - nlines=0; - - while((len=getline(line,MAXLEN)) > 0) - if(nlines >= maxlines || p+len > linestop) - return -1; - else - { - line[len-1] = '\0'; - strcpy(p,line); - lineptr[nlines++]=p; - p+=len; - } - return nlines; -} - -/* writelines: write output lines */ -void writelines(char *lineptr[],int nlines) -{ - int i; - for(i=0;i= right) - return; - swap(v,left,(left+right)/2); - - last = left; - - for(i=left+1;i<=right;i++) - if(strcmp(v[i],v[left])<0) - swap(v,++last,i); - swap(v,left,last); - qsort(v,left,last-1); - qsort(v,last+1,right); -} - -/* swap: interchange v[i] and v[j] */ - -void swap(char *v[],int i,int j) -{ - char *temp; - - temp=v[i]; - v[i]=v[j]; - v[j]=temp; -} - -#define ALLOCSIZE 10000 /* size of available space */ - -static char allocbuf[ALLOCSIZE]; /* storage for alloc */ -static char *allocp = allocbuf; /* next free position */ - -char *alloc(int n) /* return pointer to n characters */ -{ - if(allocbuf + ALLOCSIZE - allocp >= n) - { - allocp += n; - return allocp -n; - } - else - return 0; -} - -int getline(char *s,int lim) -{ - int c; - char *t=s; - - while(--lim >0 && (c=getchar())!=EOF && c!='\n') - *s++ = c; - if( c == '\n') - *s++ = c; - - *s= '\0'; - - return s-t; -} - diff --git a/languages/cprogs/squeezesc.c b/languages/cprogs/squeezesc.c deleted file mode 100644 index 2bb67e0b..00000000 --- a/languages/cprogs/squeezesc.c +++ /dev/null @@ -1,48 +0,0 @@ -/* function squeeze: deletes all the c from s */ - -#include -#define MAXLINE 1000 - -void squeeze(char s[],int c); -int mgetline(char line[],int maxline); - -int main(void) -{ - char line[MAXLINE]; - int c; - - mgetline(line,MAXLINE); - - putchar('#'); - c=getchar(); - - squeeze(line,c); - - printf("%s",line); - - return 0; -} - -int mgetline(char s[],int lim) -{ - int i,c; - - for(i=0;i -int strindex(char *s,char *t); - -int main(void) -{ - char *s="This is a line"; - char *t="is"; - int ret; - - ret=strindex(s,t); - printf("%d",ret); - - return 0; -} - -int strindex(char *s,char *t) -{ - char *b=s; - char *p,*r; - - for(;*s!='\0';s++) - { - for(p=s,r=t;*r!='\0' && *p==*r;p++,r++) - ; - - if(r>t && *r == '\0') - return s-b; - } - return -1; -} diff --git a/languages/cprogs/system-programming/prog1.c b/languages/cprogs/system-programming/prog1.c deleted file mode 100644 index 773a9599..00000000 --- a/languages/cprogs/system-programming/prog1.c +++ /dev/null @@ -1,15 +0,0 @@ -/** - * - * Program Description: System Programming Demonstration. - * - * Activity 0: http://cs-education.github.io/sys/#/chapter/0/section/0/activity/0 - * - * - * Date: 6/24/18 - **/ - -int write(int, char *, int); - -int main(int argc, char *argv[]) { - write(1, "Hello\n", 6); -} diff --git a/languages/cprogs/system-programming/prog2.c b/languages/cprogs/system-programming/prog2.c deleted file mode 100644 index 97106557..00000000 --- a/languages/cprogs/system-programming/prog2.c +++ /dev/null @@ -1,13 +0,0 @@ -/** - * - * Program Description: write system call - * - * Date: 6/24/18 - **/ - -#include - -int main(int argc, char *argv[]) { - write(1, "Hello\n", 6); - write(1, "World\n", 6); -} diff --git a/languages/cprogs/system-programming/system-programming-exercises.rst b/languages/cprogs/system-programming/system-programming-exercises.rst deleted file mode 100644 index 864d42a6..00000000 --- a/languages/cprogs/system-programming/system-programming-exercises.rst +++ /dev/null @@ -1,4 +0,0 @@ -Programs -======== - -* * http://cs-education.github.io/sys/#/chapter/0/section/0/activity/0 diff --git a/languages/cprogs/test_post.py b/languages/cprogs/test_post.py deleted file mode 100644 index d410442a..00000000 --- a/languages/cprogs/test_post.py +++ /dev/null @@ -1,28 +0,0 @@ -import urllib -import urllib2 -url = 'http://codepad.org' - -#with open('helloworld.c') as fd: -# code = fd.read() - -code = "print" - -values = {'lang' : 'Python', - 'code' : code, - 'submit':'Submit'} -data = urllib.urlencode(values) - -print data - -#response = urllib2.urlopen(url, data) -#the_page = response.geturl() -#print the_page + '/fork' -""" -for href in the_page.split(""): - if "Link:" in href: - ind=href.index('Link:') - found = href[ind+5:] - for i in found.split('">'): - if ' -#define MAXLINE 1000 - -void unescape(char s[],char t[]); -int getline(char line[],int maxlimit); - -int main(void) -{ - char s[MAXLINE],t[MAXLINE]; - - getline(t,MAXLINE); - - unescape(s,t); - - printf("%s",s); - - return 0; -} - -void unescape(char s[],char t[]) -{ - int i,j; - - for(i=j=0;t[i]!='\0';++i) - switch(t[i]) - { - case '\\': - switch(t[++i]) - { - case 'n': - s[j++]='\n'; - break; - case 't': - s[j++]='\t'; - break; - default: - s[j++]='\\'; - s[j++]=t[i]; - break; - } - break; - default: - s[j++]=t[i]; - break; - } - s[j]='\0'; -} - -int getline(char s[],int lim) -{ - int i,c; - - for(i=0;i - -std=c99 for long long int types. - -Program written under -Hardware Name: i686 -Processor: i686 -Hardware Platform:i386 -*/ - -#include -#include - -int main(void) -{ - printf("Minimum value - Singed Char : %d\n",SCHAR_MIN); - printf("Maximum value - Signed Char : %d\n",SCHAR_MAX); - printf("Maximum value - Unsigned Char : %d\n",UCHAR_MAX); - - printf("Minimum value - Signed Short Int : %d\n",SHRT_MIN); - printf("Maximum value - Signed Short Int : %d\n",SHRT_MAX); - printf("Maximum value - Unsigned Short Int : %d\n",USHRT_MAX); - - printf("Minimum value - Signed Int : %d\n",INT_MIN); - printf("Maximum value - Signed Int : %d\n",INT_MAX); - printf("Maximum value - Unsigned Int : %u\n",UINT_MAX); - - printf("Minimum value - Signed long int : %ld\n",LONG_MIN); - printf("Maximum value - Signed long int : %ld\n",LONG_MAX); - printf("Maximum value - Unsigned long int : %lu\n",ULONG_MAX); - - printf("Minimum value - Signed long long int: %lld\n",LLONG_MIN); - printf("Maximum value - Signed long long int: %lld\n",LLONG_MAX); - printf("Maximum value - Unsigned long long int : %llu\n",ULLONG_MAX); - - return 0; -} diff --git a/languages/cprogs/wumpus.c b/languages/cprogs/wumpus.c deleted file mode 100644 index d247286b..00000000 --- a/languages/cprogs/wumpus.c +++ /dev/null @@ -1,315 +0,0 @@ - -/* Hunt the Wumpus Game */ -#include -#include - -/* Program Constants Defined here */ -#define MAPWIDTH 7 -#define MAPHEIGHT 7 -#define NUM_PITS 4 - -/* Function Prototypes Defined here */ - -void initMap(char [MAPWIDTH][MAPHEIGHT]); -void printMap(char [MAPWIDTH][MAPHEIGHT]); -int move(int,int,int,int,char [MAPWIDTH][MAPHEIGHT]); -void smell(int,int,char [MAPWIDTH][MAPHEIGHT]); -int shoot(int,int,int,int,int,char [MAPWIDTH][MAPHEIGHT]); - -int main(void) -{ - int num_arrows = 3; /* Total Number of Arrows */ - char map[MAPWIDTH][MAPHEIGHT]; /* Map of Territory */ - int choice; /* Users Input Command */ - int x,y; /* Current Position of Player */ - int dx,dy; /* Change in Direction */ - int flag; /* Generic Error Flag */ - int action; /* Action 1: -> Move */ - /* Action 2: -> Shoot */ - - int debug = 1; - - /* Intialize Map */ - - srand(time(NULL)); - initMap(map); - - /* Place Player at Random Location */ - /* Make sure you dont place a Player on Wumpus or a in a Pit! */ - - flag = 1; - while(flag == 1) - { - x = (rand() % 5) + 1; - y = (rand() % 5) + 1; - - if(map[x][y] == '.') - { - map[x][y] = '@'; - flag = 0; - } - } - - printf("Welcome to 'Hunt the Wumpus' \n"); - - if(debug) - printMap(map); - - smell(x,y,map); - - /* Keep prompting for user input */ - do - { - printf("Enter a Command: "); - fflush(stdout); - choice = getc(stdin); - printf("\n"); - - /* Clearing stdin manually */ - if(choice != '\n') - while(getchar() != '\n') - ; /* empty statement */ - - switch(choice) - { - /* Movement options */ - case 'n': - dx = 0; - dy = -1; - action = 1; - break; - case 's': - dx = 0; - dy = +1; - action =1; - break; - case 'e': - dx = +1; - dy = 0; - action =1; - break; - case 'w': - dx = -1; - dy = 0; - action =1; - break; - - /* Shoot Options */ - - case 'N': - dx = 0; - dy = -1; - action = 2; - break; - case 'S': - dx = 0; - dy = +1; - action = 2; - break; - case 'E': - dx = +1; - dy = 0; - action = 2; - break; - case 'W': - dx = -1; - dy = 0; - action = 2; - break; - - default: - printf("You cannot do that!\n"); - action = 0; - break; - - } - - /* Move Player */ - - if(action == 1) - { - flag = move(x,y,dx,dy,map); - if(flag == 1) - { - map[x][y] ='.'; - x = x + dx; - y = y + dy; - map[x][y]='@'; - - } - else if(flag == -1) - break; - } - - /* Shoot */ - else if(action == 2) - { - flag = shoot(num_arrows--,x,y,dx,dy,map); - if(flag == -1) - break; - } - - if(debug) - printMap(map); - smell(x,y,map); -}while(choice != 'Q' || choice !='q'); - -printf("Press any key to exit.."); -getchar(); - -return 0; -} - -/* Intialize Map with randomly placed Pits and Randomly placed Wumpus */ - -void initMap(char map[MAPWIDTH][MAPHEIGHT]) -{ - int i,j; - int x,y; - - /* First create a Clean Slate */ - - for(j=0;j 0) - { - printf("You shoot your arrow into the dark...\n"); - - if(map[x][y] == 'W') - { - printf("\a You have slain a Wumpus!\n"); - return -1; - } - else - { - printf("And, you can hear it fall to the ground in the next room \n"); - return 0; - } - } - else - { - printf("You dont have any more arrows!\n"); - return 0; - } -} diff --git a/languages/letusc/.devcontainer.json b/languages/letusc/.devcontainer.json deleted file mode 100644 index 370528ce..00000000 --- a/languages/letusc/.devcontainer.json +++ /dev/null @@ -1,125 +0,0 @@ -{ - "extensions": [ - "/opt/cs50/extensions/cs50-0.0.1.vsix", - "/opt/cs50/extensions/phpliteadmin-0.0.1.vsix", - "/opt/cs50/extensions/workspace-layout-0.0.7.vsix", - "cs50.ddb50", - "cs50.extension-uninstaller", - "ms-python.python", - "ms-vscode.cpptools", - "ms-vscode.hexeditor", - "ms-vsliveshare.vsliveshare-pack", - "tomoki1207.pdf", - "vsls-contrib.gitdoc" - ], - "image": "ghcr.io/cs50/codespace", - "postCreateCommand": "/opt/cs50/bin/postCreateCommand", - "settings": { - "breadcrumbs.enabled": false, - "C_Cpp.autocomplete": "Disabled", - "C_Cpp.codeFolding": "Disabled", - "C_Cpp.dimInactiveRegions": false, - "C_Cpp.enhancedColorization": "Enabled", - "C_Cpp.errorSquiggles": "Disabled", - "editor.autoClosingQuotes": "never", - "editor.colorDecorators": false, - "editor.emptySelectionClipboard": false, - "editor.folding": false, - "editor.foldingHighlight": false, - "editor.hover.enabled": false, - "editor.lightbulb.enabled": false, - "editor.matchBrackets": "near", - "editor.minimap.enabled": false, - "editor.occurrencesHighlight": false, - "editor.parameterHints.enabled": false, - "editor.quickSuggestions": false, - "editor.renderIndentGuides": false, - "editor.renderWhitespace": "selection", - "editor.selectionHighlight": false, - "editor.semanticTokenColorCustomizations": { - "[Default Dark+]": { - "enabled": true, - "rules": { - "type": "#569CD6" - } - }, - "[Default Light+]": { - "enabled": true, - "rules": { - "type": "#0000FF" - } - } - }, - "editor.suggestOnTriggerCharacters": false, - "extensions.ignoreRecommendations": true, - "extension-uninstaller.uninstall": [ - "github.copilot", - "github.copilot-nightly", - "tabnine.tabnine-vscode" - ], - "files.autoSave": "afterDelay", - "files.exclude": { - "**/.*": true - }, - "files.trimTrailingWhitespace": true, - "files.watcherExclude": { - "**/.git/objects/**": true, - "**/.git/subtree-cache/**": true, - "**/node_modules/*/**": true - }, - "git.autofetch": true, /* Disable "Would you like Code to periodically run 'git fetch'?" toast */ - "git.decorations.enabled": false, - "gitdoc.autoPull": "off", - "gitdoc.enabled": true, - "gitdoc.commitMessageFormat": "ddd, MMM D, YYYY, h:mm A Z", - "gitdoc.commitValidationLevel": "none", - "gitdoc.pullOnOpen": false, - "html.suggest.html5": false, - "javascript.suggest.enabled": false, - "javascript.validate.enable": false, /* Disable red squiggles */ - "problems.decorations.enabled": false, - "remote.otherPortsAttributes": { - "onAutoForward": "silent" - }, - "scm.countBadge": "off", - "terminal.integrated.commandsToSkipShell": [ - "workbench.action.toggleSidebarVisibility" - ], - "terminal.integrated.defaultProfile.linux": "bash", - "terminal.integrated.profiles.linux": { - "bash": { - "args": [ - "-l" - ], - "path": "bash" - }, - "JavaScript Debug Terminal": null - }, - "terminal.integrated.persistentSessionReviveProcess": "never", - "terminal.integrated.sendKeybindingsToShell": true, - "terminal.integrated.tabs.description": "${task}${separator}${local}", /* Remove cwdFolder from description */ - "terminal.integrated.tabs.showActiveTerminal": "never", - "window.autoDetectColorScheme": true, - "workbench.colorCustomizations": { - "editor.lineHighlightBorder": "#0000", /* Disable gray border-{bottom,top} on active line */ - "editorError.foreground": "#0000", /* Disable red squiggles */ - "editorWarning.foreground": "#0000", /* Disable yellow squiggles */ - "editorGutter.addedBackground": "#0000", - "editorGutter.deletedBackground": "#0000", - "editorGutter.modifiedBackground": "#0000", /* Disable yellow bars to left of lines modified since last commit */ - "[GitHub Light Default]": { - "terminal.foreground": "#000000" /* Change terminal font color to #000 for GitHub Light Default theme */ - } - }, - "workbench.editor.closeOnFileDelete": true, - "workbench.editor.untitled.hint": "hidden", - "workbench.enableExperiments": false, - "workbench.iconTheme": "vs-minimal", /* Simplify icons */ - "workbench.preferredDarkColorTheme": "Default Dark+", - "workbench.preferredLightColorTheme": "Default Light+", - "workbench.startupEditor": "none", - "workbench.statusBar.visible": false, - "workbench.tips.enabled": false, - "workbench.welcomePage.walkthroughs.openOnInstall": false - } -} diff --git a/languages/python/8queens.py b/languages/python/8queens.py deleted file mode 100644 index e27ee489..00000000 --- a/languages/python/8queens.py +++ /dev/null @@ -1,19 +0,0 @@ -from itertools import permutations - -# What's the difference between permutations and combinations. -# permutations is about arrangements. -# combinations is about choosing. - - -def eight_queens(): - queens = list(range(8)) - for pos in permutations(queens): - # how many times is the if statement below evaluated? - # How does subtracting and addition the position work? - if (8 == len(set(pos[i] + i for i in queens)) - == len(set(pos[i] - i for i in queens))): - print(pos) - - -if __name__ == '__main__': - eight_queens() diff --git a/languages/python/Queue.py b/languages/python/Queue.py deleted file mode 100644 index 93a62931..00000000 --- a/languages/python/Queue.py +++ /dev/null @@ -1,34 +0,0 @@ -""" -Simple implementation of a Queue datastructure in Python. -""" -class Queue: - def __init__(self, items = None): - if items is None: - items = [] - self.__queue = items - - def __repr__(self): - return str(self.__queue) - - def isempty(self): - return len(self.__queue) == 0 - - def enqueue(self, item): - self.__queue.append(item) - - def dequeue(self): - return self.__queue.pop(0) - - def peek(self): - return self.__queue[0] - -if __name__ == '__main__': - q = Queue() - q.enqueue(10) - q.enqueue(20) - q.enqueue(30) - q.enqueue(40) - print(q) - print(q.peek()) - q.dequeue() - print(q) diff --git a/languages/python/README b/languages/python/README deleted file mode 100644 index d74d6425..00000000 --- a/languages/python/README +++ /dev/null @@ -1,29 +0,0 @@ -Categories of Python Programs ------------------------------ - -Try to classify each of the program into any of these categories. -And rename the python program as category_name_program_name_#number.py - -* text_manipulation - - This category demonstrates text manipulation. It reads input and applies - simple text manipulation and provides the output. Many programs fall into this category. -* networking - - This program demonstrates networking and socket calls. Anything to do with servers and clients. -* web - - These deal with websites, webapplications and work on top of networking layer. -* design - - These programs demonstrate software design ascepts. These can be pretty - deep as, "why" it is done so is not obvious, but the program usually - demonstrates how it is done. -* algorithm - - This is an implementation of a well known CS algorithm. -* software_engineering - - This is how software is built in real world. If your software needs to - make money, you will need to take care of these aspects. - - -For e.g, I renamed these programs: - - renamed: context_1.py -> design_context_manager_1.py - renamed: client.py -> networking_socket_client.py - diff --git a/languages/python/algorithm_binary_representation.py b/languages/python/algorithm_binary_representation.py deleted file mode 100644 index c50153bd..00000000 --- a/languages/python/algorithm_binary_representation.py +++ /dev/null @@ -1,117 +0,0 @@ -""" -Program to do binary representation of various interesting ints. -""" - - -def convert_to_binary(n): - binary = [] - while n: - binary.append(str(n % 2)) - n /= 2 - binary.reverse() - return "".join(binary) - - -for i in range(20, 30): - print((i, convert_to_binary(i))) - -hexa_values = ['0', '1', 'A', 'FF', 'DEADBEEF', 'CAFEBABE'] - -for each in hexa_values: - dec = int(each, 16) - print((each, convert_to_binary(dec))) - -""" -Find out if the machine is storing it in the one's complement or two's -complement. -1 is stored as 0000 0001 --1 in 1's complement is 1111 1110 --1 in 2's complement is 1111 1111 -""" - -import struct - -if ord(struct.pack('b', -1)[0]) == 255: - print('twos complement') -else: - print('ones complement') - -for i in range(200, 255): - print((hex(i))) - -for i in range(0, 256): - print((chr(i), i, hex(i))) - -""" -Binary Addition and Subtraction -""" -a = 20 -b = 10 - -a_bin = convert_to_binary(a) -b_bin = convert_to_binary(b) - -if len(a_bin) > len(b_bin): - b_bin = b_bin.rjust(len(a_bin), '0') -elif len(a_bin) < len(b_bin): - a_bin = a_bin.rjust(len(b_bin), '0') - - -def sum_bin(a, b): - rules = {('0', '0'): (0, 0), - ('0', '1'): (1, 0), - ('1', '0'): (1, 0), - ('1', '1'): (0, 1) - } - carry = 0 - sum = 0 - result = "" - for x, y in zip(reversed(a), reversed(b)): - sum = rules[(x, y)][0] - if carry: - sum = rules[(str(sum), str(carry))][0] - result += str(sum) - carry = rules[(x, y)][1] - - if carry: - result += str(1) - - return result[::-1] - - -def sub_bin(a, b): - ones_complement = "" - for c in b: - if c == '0': - ones_complement += '1' - elif c == '1': - ones_complement += '0' - - b = ones_complement - b = sum_bin(b, '1'.rjust(len(b), '0')) - - rules = {('0', '0'): (0, 0), - ('0', '1'): (1, 0), - ('1', '0'): (1, 0), - ('1', '1'): (0, 1) - } - - carry = 0 - sum = 0 - result = "" - for x, y in zip(reversed(a), reversed(b)): - sum = rules[(x, y)][0] - if carry: - sum = rules[(str(sum), str(carry))][0] - result += str(sum) - carry = rules[(x, y)][1] - # unlike addition carry should be discarded. - - return result[::-1] - - -print(('a', a, a_bin)) -print(('b', b, b_bin)) - -print(('a+b ', sum_bin(a_bin, b_bin))) -print(('a-b ', sub_bin(a_bin, b_bin))) diff --git a/languages/python/algorithm_binary_search.py b/languages/python/algorithm_binary_search.py deleted file mode 100644 index 34bb4f40..00000000 --- a/languages/python/algorithm_binary_search.py +++ /dev/null @@ -1,19 +0,0 @@ -import random - -def find_in_sorted(arr, x): - def binsearch(start, end): - if start == end: - return -1 - mid = start + (end - start) // 2 - if x < arr[mid]: - return binsearch(start, mid) - elif x > arr[mid]: - return binsearch(mid+1, end) - else: - return mid - return binsearch(0, len(arr)) - - -ar = sorted(random.sample(list(range(10)),9)) -r = random.randint(0,10) -print((find_in_sorted(ar,r))) diff --git a/languages/python/algorithm_cellauto.py b/languages/python/algorithm_cellauto.py deleted file mode 100644 index 85c76685..00000000 --- a/languages/python/algorithm_cellauto.py +++ /dev/null @@ -1,73 +0,0 @@ -#!/usr/bin/env python -""" - CellularAutomata.py: Wolfram-style cellular automata in Python - - Options: - -h # Use a screen of height # for the simulation - -w # Use a screen of width # for the simulation - -r Use a random initial row (rather than the standard single 1 in the middle) - -R # Use rule # for the simulation - -Requires python-image (PIL package) installed. -Fills up an initial cell and runs a particular rule of Cellular Automata. - -.. image:: https://lh4.googleusercontent.com/_ny1HYbb2lDw/Tazon5TsgXI/AAAAAAAAKgU/ud6v_XhcHB0/s288/bs.png - -*I can't remember the source, if you claim/know, please inform.* - -""" - -import getopt,sys -from random import randint - - -def ca_data(height,width,dorandom,rulenum): - # Create the first row, either randomly, or with a single 1 - if dorandom: - first_row = [randint(0,1) for i in range(width)] - else: - first_row = [0]*width - first_row[width/2] = 1 - results = [first_row] - - # Convert the rule number to a list of outcomes. - rule = [(rulenum/pow(2,i)) % 2 for i in range(8)] - - for i in range(height-1): - data = results[-1] - # Determine the new row based on the old data. We first make an - # integer out of the value of the old row and its two neighbors - # and then use that value to get the outcome from the table we - # computed earlier - new = [rule[4*data[(j-1)%width]+2*data[j]+data[(j+1)%width]] - for j in range(width)] - results.append(new) - return results - -def pil_render(data,height,width,fname="bs.png"): - import Image, ImageDraw - img = Image.new("RGB",(width,height),(255,255,255)) - draw = ImageDraw.Draw(img) - - for y in range(height): - for x in range(width): - if data[y][x]: draw.point((x,y),(0,0,0)) - img.save(fname,"PNG") - return - -def main(): - opts,args = getopt.getopt(sys.argv[1:],'h:w:rR:') - height = 500 - width = 500 - dorandom = 0 - rule = 22 - for key,val in opts: - if key == '-h': height = int(val) - if key == '-w': width = int(val) - if key == '-r': dorandom = 1 - if key == '-R': rule = int(val) - data = ca_data(height,width,dorandom,rule) - pil_render(data,height,width) - return - -if __name__ == '__main__': main() diff --git a/languages/python/algorithm_checking_string_text_or_binary.py b/languages/python/algorithm_checking_string_text_or_binary.py deleted file mode 100644 index fa6b4ef3..00000000 --- a/languages/python/algorithm_checking_string_text_or_binary.py +++ /dev/null @@ -1,23 +0,0 @@ -""" -This program checks if a string is a text or binary. -This snippet is from Python Cookbook. -""" - # ensure / does not truncate -import string -text_characters = "".join(map(chr, list(range(32, 127)))) + "\n\r\t\b" -_null_trans = string.maketrans("","") - -def istext(s, text_characters=text_characters, threshold=0.30): - # if s contains any null, then it is not text: - if '\0' in s: - return False - # An empty string is still a text - if not s: - return True - # Get the substring of s made of non-text characters - t = s.translate(_null_trans, text_characters) - # s is 'text' if less than 30% of its characters are non-text ones: - return len(t)/len(s) <=threshold - -print("Hello, World ", istext("Hello, World")) -print("\xc3\xa4", istext("\xc3\xa4")) diff --git a/languages/python/algorithm_eratosthenes.py b/languages/python/algorithm_eratosthenes.py deleted file mode 100644 index 14d0493a..00000000 --- a/languages/python/algorithm_eratosthenes.py +++ /dev/null @@ -1,15 +0,0 @@ -def eratosthenes(): - D = {} - q = 2 - while True: - p = D.pop(q, None) - if p: - x = p + q - while x in D: - x += p - D[x] = p - else: - D[q*q] = q - yield q - q += 1 - diff --git a/languages/python/algorithm_fact2.py b/languages/python/algorithm_fact2.py deleted file mode 100644 index 8e385ba4..00000000 --- a/languages/python/algorithm_fact2.py +++ /dev/null @@ -1,3 +0,0 @@ -import operator -from functools import reduce -print(reduce(operator.mul, range(1,10))) diff --git a/languages/python/algorithm_fibo.py b/languages/python/algorithm_fibo.py deleted file mode 100644 index ab10593c..00000000 --- a/languages/python/algorithm_fibo.py +++ /dev/null @@ -1,14 +0,0 @@ -def fibo(n): - if n == 0: - return 0 - if n == 1: - return 1 - return (fibo(n-2) + fibo(n-1)) - -print(fibo(0)) -print(fibo(1)) -print(fibo(2)) -print(fibo(3)) -print(fibo(4)) -print(fibo(5)) -print(fibo(6)) diff --git a/languages/python/algorithm_graph.py b/languages/python/algorithm_graph.py deleted file mode 100644 index 50648007..00000000 --- a/languages/python/algorithm_graph.py +++ /dev/null @@ -1,28 +0,0 @@ -""" -Simplest possible graph representation.abs - -In theory, Graph is represented with vertices "V" and edges "E". We use the same notation here. - -Expected Output ---------------- - -['a', 'c', 'b'] -True -True -""" - -class Graph: - def __init__(self , g): - self.g = g - - def V(self): - return list(self.g.keys()) - - def E(self, node1, node2): - return node2 in self.g[node1] - -if __name__ == '__main__': - gobject = Graph({"a":["b","c"],"b":["e","c"],"c":["a","b"]}) - print((gobject.V())) - print((gobject.E("a","c"))) - print((gobject.E("b","e"))) diff --git a/languages/python/algorithm_hanoi.py b/languages/python/algorithm_hanoi.py deleted file mode 100644 index ecf39de3..00000000 --- a/languages/python/algorithm_hanoi.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/usr/bin/python -# Towers of Hanoi program. - -disks = 3 -from_tower = 'A' -to_tower = 'C' -using_tower = 'B' - -def hanoi(n, from_tower, to_tower, using_tower): - if n > 0: - hanoi(n-1, from_tower, using_tower, to_tower) - print('move disk from ', from_tower, ' to ', to_tower) - hanoi(n-1, using_tower, to_tower, from_tower) - -hanoi(disks, from_tower, to_tower, using_tower) diff --git a/languages/python/algorithm_insertion.py b/languages/python/algorithm_insertion.py deleted file mode 100644 index bcef1a2d..00000000 --- a/languages/python/algorithm_insertion.py +++ /dev/null @@ -1,16 +0,0 @@ -import random -list_to_sort = random.sample(list(range(10)),8) - -def insertion_sort(listtosort): - for i in range(1,len(listtosort)): - key = listtosort[i] - j = i - 1 - while ( j > 0) and (key < listtosort[j]): - listtosort[j+1] = listtosort[j] - j -= 1 - listtosort[j] = key - return listtosort - -print(list_to_sort) -print(insertion_sort(list_to_sort)) - diff --git a/languages/python/algorithm_int_to_roman.py b/languages/python/algorithm_int_to_roman.py deleted file mode 100644 index 6988e5f5..00000000 --- a/languages/python/algorithm_int_to_roman.py +++ /dev/null @@ -1,171 +0,0 @@ -# Program which converts the given input integer to roman numeral. -# Limitation: Program converts the integer numbers uptil the value of 1000 -# (Roman Numeral: D) -# Problem: P2.1 - Implement a translator from integers to roman numeral based -# on the syntax directed translation scheme developed in Exercise 2.9 -# Chapter 2 - A Simple One-Pass Compiler. Compilers, Principles, Techniques -# and Tools. - - -roman_dict = {1:'I',5:'V',10:'X',50:'L',100:'C',500:'D',1000:'M'} - -def sep_num(n): - num = [] - if n/100: - hundreds = (n/100) * 100 - num.append(hundreds) - n = n%100 - tens = (n/10) * 10 - if tens: - num.append(tens) - ones = n%10 - if ones: - num.append(ones) - elif n/10: - tens = (n/10) * 10 - num.append(tens) - ones = n%10 - if ones: - num.append(ones) - else: - ones = n - num.append(ones) - return num - -def get_roman(n): - rnos = [] - if n in roman_dict: - rnos.append(n) - return rnos - else: - if 1 < n < 5: - base,factor = 1,1 - rnos.append(base) - result = n - base - while result > 0: - rnos.append(factor) - result = result - factor - if rnos.count(factor) > 3: - for n in rnos[:]: - rnos.remove(n) - indices = list(roman_dict.keys()) - indices.sort() - prev_base = base - base_index = indices.index(base) + 1 - base = indices[base_index] - rnos.append(prev_base) - rnos.append(base) - return rnos - elif 5 < n < 10: - base,factor = 5,1 - rnos.append(base) - result = n - base - while result > 0: - rnos.append(factor) - result = result - factor - if rnos.count(factor) > 3: - for n in rnos[:]: - rnos.remove(n) - indices = list(roman_dict.keys()) - indices.sort() - prev_base_index = indices.index(base) - 1 - prev_base = indices[prev_base_index] - base_index = indices.index(base) + 1 - base = indices[base_index] - rnos.append(prev_base) - rnos.append(base) - return rnos - elif 10 < n <50: - base,factor = 10,10 - rnos.append(base) - result = n - base - while result > 0: - rnos.append(factor) - result = result - factor - if rnos.count(factor) > 3: - for n in rnos[:]: - rnos.remove(n) - indices = list(roman_dict.keys()) - indices.sort() - prev_base = base - base_index = indices.index(base) + 1 - base = indices[base_index] - rnos.append(prev_base) - rnos.append(base) - return rnos - elif 50 < n < 100: - base, factor = 50,10 - rnos.append(base) - result = n - base - while result > 0: - rnos.append(factor) - result = result - factor - if rnos.count(factor) > 3: - for n in rnos[:]: - rnos.remove(n) - indices = list(roman_dict.keys()) - indices.sort() - prev_base_index = indices.index(base) - 1 - prev_base = indices[prev_base_index] - base_index = indices.index(base) + 1 - base = indices[base_index] - rnos.append(prev_base) - rnos.append(base) - return rnos - elif 100 < n < 500: - base, factor = 100, 100 - rnos.append(base) - result = n - base - while result > 0: - rnos.append(factor) - result = result - factor - if rnos.count(factor) > 3: - for n in rnos[:]: - rnos.remove(n) - indices = list(roman_dict.keys()) - indices.sort() - prev_base = base - base_index = indices.index(base) + 1 - base = indices[base_index] - rnos.append(prev_base) - rnos.append(base) - return rnos - elif 500 < n < 1000: - base, factor = 500, 100 - rnos.append(base) - result = n - base - while result > 0: - rnos.append(factor) - result = result - factor - if rnos.count(factor) > 3: - for n in rnos[:]: - rnos.remove(n) - indices = list(roman_dict.keys()) - indices.sort() - prev_base_index = indices.index(base) - 1 - prev_base = indices[prev_base_index] - base_index = indices.index(base) + 1 - base = indices[base_index] - rnos.append(prev_base) - rnos.append(base) - return rnos - - -def main(): - number = int(input("Enter the Integer: ")) - if number > 1000: - print('Sorry, I know uptil 1000 only.') - exit() - if number in roman_dict: - print("Roman: ",roman_dict[number]) - else: - romans = [] - res = sep_num(number) - for each in res: - rvalues = get_roman(each) - for value in rvalues: - romans.append(roman_dict[value]) - print("Roman: ",''.join(romans)) - -if __name__ == '__main__': - main() diff --git a/languages/python/algorithm_locate.py b/languages/python/algorithm_locate.py deleted file mode 100644 index 224626d9..00000000 --- a/languages/python/algorithm_locate.py +++ /dev/null @@ -1,7 +0,0 @@ -import fnmatch -import os - -def locate(pattern, root=os.getcwd()): - for path, dirs, files in os.walk(root): - for filename in [os.path.abspath(os.path.join(path, filename)) for filename in files if fnmatch.fnmatch(filename, pattern)]: - yield filename diff --git a/languages/python/algorithm_maxsort.py b/languages/python/algorithm_maxsort.py deleted file mode 100644 index c5088d73..00000000 --- a/languages/python/algorithm_maxsort.py +++ /dev/null @@ -1,12 +0,0 @@ -def maxsort(A): - size = len(A) -1 - for i in range(0,size): - max_index = 0 - for j in range(0, (size -i)+1): - if A[j] > A[max_index]: - max_index = j - A[size-i], A[max_index] = A[max_index], A[size-i] - -A = [5,4,3,2,1] -maxsort(A) -print(A) diff --git a/languages/python/algorithm_mergesort.py b/languages/python/algorithm_mergesort.py deleted file mode 100644 index eec9e53b..00000000 --- a/languages/python/algorithm_mergesort.py +++ /dev/null @@ -1,40 +0,0 @@ -import random -import math - -def merge(left,right): - result = [] - while left and right: - if left[0] < right[0]: - result.append(left.pop(0)) - else: - result.append(right.pop(0)) - if left: - result.extend(left) - else: - result.extend(right) - return result - -def mergesort(m): - left = [] - right = [] - result = [] - - if len(m) <=1: - return m - middle = len(m)/2 - - left = m[:middle] - right = m[middle:] - - left = mergesort(left) - right = mergesort(right) - - if left[-1] > right[0]: - result = merge(left, right) - else: - result = left + right - return result - -p = random.sample(list(range(10)),8) -print(p) -print(mergesort(p)) diff --git a/languages/python/algorithm_npuzzle.py b/languages/python/algorithm_npuzzle.py deleted file mode 100644 index b946d61c..00000000 --- a/languages/python/algorithm_npuzzle.py +++ /dev/null @@ -1,138 +0,0 @@ -#!/usr/bin/python -# -*- coding: utf-8 -*- -# vim: ts=4 sw=4 et ai ff=unix ft=python nowrap -# -# Program: npuzzle.py -# -# Description: Solves the N-Puzzle Sliding Block Problem. -# -# Usage: python npuzzle.py. -# -# License: GNU GPL Version 2.0. Please refer www.gnu.org. - -import random - - -class State: - - def __init__(self, nsize): - """Initialze the n-puzzle problem, with n-size value, tsize the total nodes and initial the goal state from n. - """ - - self.nsize = nsize - self.tsize = pow(self.nsize, 2) - self.goal = list(range(1, self.tsize)) - self.goal.append(0) - - def printst(self, st): - """Print the list in a Matrix Format.""" - - for (index, value) in enumerate(st): - print(' %s ' % value, end=' ') - if index in [x for x in range(self.nsize - 1, self.tsize, - self.nsize)]: - print() - print() - - def getvalues(self, key): - """Utility function to gather the Free Motions at various key positions in the Matrix.""" - - values = [1, -1, self.nsize, -self.nsize] - valid = [] - for x in values: - if 0 <= key + x < self.tsize: - if x == 1 and key in range(self.nsize - 1, self.tsize, - self.nsize): - continue - if x == -1 and key in range(0, self.tsize, self.nsize): - continue - valid.append(x) - return valid - - def expand(self, st): - """Provide the list of next possible states from current state.""" - - pexpands = {} - for key in range(self.tsize): - pexpands[key] = self.getvalues(key) - pos = st.index(0) - moves = pexpands[pos] - expstates = [] - for mv in moves: - nstate = st[:] - (nstate[pos + mv], nstate[pos]) = (nstate[pos], nstate[pos + - mv]) - expstates.append(nstate) - return expstates - - def one_of_poss(self, st): - """Choose one of the possible states.""" - - exp_sts = self.expand(st) - rand_st = random.choice(exp_sts) - return rand_st - - def start_state(self, seed=1000): - """Determine the Start State of the Problem.""" - - start_st = (self.goal)[:] - for sts in range(seed): - start_st = self.one_of_poss(start_st) - return start_st - - def goal_reached(self, st): - """Check if the Goal Reached or Not.""" - - return st == self.goal - - def manhattan_distance(self, st): - """Calculate the Manhattan Distances of the particular State. - Manhattan distances are calculated as Total number of Horizontal and Vertical moves required by the values in the current state to reach their position in the Goal State. - """ - - mdist = 0 - for node in st: - if node != 0: - gdist = abs(self.goal.index(node) - st.index(node)) - (jumps, steps) = (gdist // self.nsize, gdist % self.nsize) - mdist += jumps + steps - return mdist - - def huristic_next_state(self, st): - """This is the Huristic Function. It determines the next state to follow and uses Mahattan distances method as the huristics. This this determined way, a A* approach for path finding is used. -If more than one path have same manhattan distance, then a random choice of one of them is analyzed and carried forward. If not best path, randomness to providethe other choice is relied upon. No Depth First search is Used.""" - - exp_sts = self.expand(st) - mdists = [] - for st in exp_sts: - mdists.append(self.manhattan_distance(st)) - mdists.sort() - short_path = mdists[0] - if mdists.count(short_path) > 1: - least_paths = [st for st in exp_sts if self.manhattan_distance(st) == short_path] - return random.choice(least_paths) - else: - for st in exp_sts: - if self.manhattan_distance(st) == short_path: - return st - - def solve_it(self, st): - while not self.goal_reached(st): - st = self.huristic_next_state(st) - self.printst(st) - - -if __name__ == '__main__': - print('N-Puzzle Solver!') - print(10 * '-') - state = State(3) - print('The Starting State is:') - start = state.start_state(5) - state.printst(start) - print('The Goal State should be:') - state.printst(state.goal) - print('Here it Goes:') - state.printst(start) - state.solve_it(start) - - diff --git a/languages/python/algorithm_pyex2_multiprocessing.py b/languages/python/algorithm_pyex2_multiprocessing.py deleted file mode 100644 index ceb641c5..00000000 --- a/languages/python/algorithm_pyex2_multiprocessing.py +++ /dev/null @@ -1,9 +0,0 @@ -from multiprocessing import Pool - -def factorial(N, dictionary): - "Compute a Factorial" - -p = Pool(5) -result = p.map(factorial, list(range(1,1000,10))) -for v in result: - print(v) diff --git a/languages/python/algorithm_pyex_multiprocessing.py b/languages/python/algorithm_pyex_multiprocessing.py deleted file mode 100644 index e09f5749..00000000 --- a/languages/python/algorithm_pyex_multiprocessing.py +++ /dev/null @@ -1,29 +0,0 @@ -import time -from multiprocessing import Process, Queue - -def factorial(queue, N): - "Compute a factorial." - # If N is a multiple of 4, this function will take much longer. - if (N % 4) == 0: - time.sleep(0.05 * N/4) - - # Calculate the result - fact = 1 - for i in range(1, N+1): - fact = fact * i - - # Put the result back into the Queue - queue.put(fact) - -if __name__ == '__main__': - queue = Queue() - - N = 5 - - p = Process(target=factorial, args=(queue, N)) - p.start() - p.join() - - result = queue.get() - - print('Factorial', N, '=', result) diff --git a/languages/python/algorithm_quicksort.py b/languages/python/algorithm_quicksort.py deleted file mode 100644 index b354674e..00000000 --- a/languages/python/algorithm_quicksort.py +++ /dev/null @@ -1,59 +0,0 @@ -# Quick sort in Python - -# The basic idea behind Quick Sort is to first find an element Pivot from the array -# Based on pivot element, the array is sorted such that all the elements to the left of pivot are smaller -# than pivot and elements to right of pivot are greater than pivot -# The same process is repeated in the left and right sub array of the pivot. - - -# function to find the partition position -def partition(array, low, high): - - # choose the rightmost element as pivot - pivot = array[high] - - # pointer for greater element - i = low - 1 - - # traverse through all elements - # compare each element with pivot - for j in range(low, high): - if array[j] <= pivot: - # if element smaller than pivot is found - # swap it with the greater element pointed by i - i = i + 1 - - # swapping element at i with element at j - (array[i], array[j]) = (array[j], array[i]) - - # swap the pivot element with the greater element specified by i - (array[i + 1], array[high]) = (array[high], array[i + 1]) - - # return the position from where partition is done - return i + 1 - -def quickSort(array, low, high): - if low < high: - - # find pivot element such that - # element smaller than pivot are on the left - # element greater than pivot are on the right - pi = partition(array, low, high) - - # recursive call on the left of pivot - quickSort(array, low, pi - 1) - - # recursive call on the right of pivot - quickSort(array, pi + 1, high) - - -data = [10, 11, 3, 5, 16, 34, 15] -print("Unsorted Array") -print(data) - -size = len(data) - -quickSort(data, 0, size - 1) - -print('Sorted Array in Ascending Order:') -print(data) diff --git a/languages/python/algorithm_scrmable.py b/languages/python/algorithm_scrmable.py deleted file mode 100644 index cc3245c7..00000000 --- a/languages/python/algorithm_scrmable.py +++ /dev/null @@ -1,65 +0,0 @@ -#!/usr/bin/env python -# Cphryigot: O.R.Senthil Kumaran -# -# Inrpeisd from jwz scrmable: http://www.jwz.org/hacks/scrmable.pl -# -# Tihs pgrarom is fere sortfwae; you can rrtiestiubde it ad/onr mdfioy -# it udenr the tmers of the GNU Graneel Pbuilc Liscene as phlibsued by -# the Fere Sfwartoe Fanouiodtn; eeihtr vierosn 2 of the Liscene, or -# (at your opotin) any leatr vierosn. -# -# Tihs pgrarom is diisertbtud in the hope taht it will be uusfel, -# but WTHOIUT ANY WRAANRTY; whitout eevn the iipemld watrarny of -# MNTIBRAEAHCITLY or FNTIESS FOR A PTULACRIAR PURPSOE. See the -# GNU Graneel Pbuilc Liscene for mroe dalites. -# -# You suolhd have reievced a copy of the GNU Graneel Pbuilc Liscene -# along wtih tihs pgrarom; if not, wtire to the Free Software -# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - -import random -import sys - - -def mxiup(ecah_wrod): - if len(ecah_wrod) <= 2: - return ecah_wrod - else: - nwewrod = ecah_wrod[0] - if ecah_wrod[-1] in ['.', ',', ':', ';', '-', '?', '!']: - inbet = ecah_wrod[1:-2] - for each in random.sample(list(inbet), len(inbet)): - nwewrod += each - nwewrod += ecah_wrod[-2] - else: - inbet = ecah_wrod[1:-1] - for each in random.sample(list(inbet), len(inbet)): - nwewrod += each - nwewrod += ecah_wrod[-1] - return nwewrod - - -def srcambel(line): - mixedwrods = [] - wrods = line.split() - for ecah_wrod in wrods: - mixedwrods.append(mxiup(ecah_wrod)) - for w, m in zip(wrods, mixedwrods): - line = line.replace(w, m) - print(line, end='') - - -def getgraparaph(): - line = sys.stdin.read() - return line - - -def mian(): - try: - line = getgraparaph() - srcambel(line) - except (EOFError, KeyboardInterrupt): - sys.exit(0) - - -mian() diff --git a/languages/python/algorithm_spelling.py b/languages/python/algorithm_spelling.py deleted file mode 100644 index e3e0a522..00000000 --- a/languages/python/algorithm_spelling.py +++ /dev/null @@ -1,30 +0,0 @@ -import re, collections - -def words(text): return re.findall('[a-z]+', text.lower()) - -def train(features): - model = collections.defaultdict(lambda: 1) - for f in features: - model[f] += 1 - return model - -NWORDS = train(words(file('big.txt').read())) - -alphabet = 'abcdefghijklmnopqrstuvwxyz' - -def edits1(word): - splits = [(word[:i], word[i:]) for i in range(len(word) + 1)] - deletes = [a + b[1:] for a, b in splits if b] - transposes = [a + b[1] + b[0] + b[2:] for a, b in splits if len(b)>1] - replaces = [a + c + b[1:] for a, b in splits for c in alphabet if b] - inserts = [a + c + b for a, b in splits for c in alphabet] - return set(deletes + transposes + replaces + inserts) - -def known_edits2(word): - return set(e2 for e1 in edits1(word) for e2 in edits1(e1) if e2 in NWORDS) - -def known(words): return set(w for w in words if w in NWORDS) - -def correct(word): - candidates = known([word]) or known(edits1(word)) or known_edits2(word) or [word] - return max(candidates, key=NWORDS.get) diff --git a/languages/python/algorithm_splitter.py b/languages/python/algorithm_splitter.py deleted file mode 100644 index 59f3a367..00000000 --- a/languages/python/algorithm_splitter.py +++ /dev/null @@ -1,20 +0,0 @@ -from string import ascii_lowercase -from itertools import combinations - -HEADER = "whatever\n" - -def splitter(chunksize, source, outputprefix): - input = open(source) - counter = 0 - for suffix in (''.join(pair) for pair in combinations(ascii_lowercase, 2)): - with open(outputprefix + suffix, 'w') as output: - chunk = input.read(chunksize) - if not chunk.endswith('\n'): - lastln = chunk.rfind('\n') - chunksize = chunksize - lastsize - output.write(HEADER) - output.write(chunk) - if len(chunk) < chunksize: - return - -splitter(15,'data.big','foo') diff --git a/languages/python/algorithm_syllablecount.py b/languages/python/algorithm_syllablecount.py deleted file mode 100644 index 8761e5b2..00000000 --- a/languages/python/algorithm_syllablecount.py +++ /dev/null @@ -1,27 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- -# written by kennenth gonsalves - -import codecs - -def countsyll(instring): - """This function counts the number of characters in a tamil string - This is done by ignoring the vowel additions. If one uses the len - function, the sample string has a length of 17 - but there are actually - only 11 characters""" - s = codecs.utf_8_encode(instring) - print(s) - x = codecs.utf_8_decode(s[0])[0] - print(repr(x)) - syllen = 0 - vowels = ['\u0bbe','\u0bbf','\u0bc0', - '\u0bc1','\u0bc2','\u0bc6', - '\u0bc7','\u0bc8','\u0bca', - '\u0bcb','\u0bcc','\u0bcd',] - for y in x: - if y not in vowels: - syllen += 1 - return syllen - -if __name__=='__main__': - print(countsyll('ஆண்டவரின் துணைவன்')) diff --git a/languages/python/algorithm_toss_coins.py b/languages/python/algorithm_toss_coins.py deleted file mode 100644 index bde42348..00000000 --- a/languages/python/algorithm_toss_coins.py +++ /dev/null @@ -1,20 +0,0 @@ -# Example showing tossing of coins - -import random - -heads = tails = count = 0 -choice = '' - -while choice.lower() != 'q': - count = count + 1 - choice = random.choice(["heads","tails"]) - if choice == "heads": - heads = heads + 1 - else: - tails = tails + 1 - print(choice) - choice = input("Press any key to continue or q to quit") - -print('Total :', count) -print('Heads :', str(heads), ' Percentage ', ((heads * 1.0)/count) * 100) -print('Tails :', str(tails), ' Percentage ', ((tails * 1.0)/count) * 100) diff --git a/languages/python/algorithm_traversal.py b/languages/python/algorithm_traversal.py deleted file mode 100644 index 29508795..00000000 --- a/languages/python/algorithm_traversal.py +++ /dev/null @@ -1,47 +0,0 @@ -from collections import deque - - -def bfs(g, start): - queue, enqueued = deque([(None, start)]), set([start]) - while queue: - parent, n = queue.popleft() - yield parent, n - new = set(g[n]) - enqueued - enqueued |= new - queue.extend([(n, child) for child in new]) - -def dfs(g, start): - stack, enqueued = [(None, start)], set([start]) - while stack: - parent, n = stack.pop() - yield parent, n - new = set(g[n]) - enqueued - enqueued |= new - stack.extend([(n, child) for child in new]) - -def shortest_path(g, start, end): - parents = {} - for parent, child in bfs(g, start): - parents[child] = parent - if child == end: - revpath = [end] - while True: - parent = parents[child] - revpath.append(parent) - if parent == start: - break - child = parent - return list(reversed(revpath)) - return None # or raise appropriate exception - -if __name__ == '__main__': - # a sample graph - graph = {'A': ['B', 'C','E'], - 'B': ['A','C', 'D'], - 'C': ['D'], - 'D': ['C'], - 'E': ['F', 'D'], - 'F': ['C']} - - for node in bfs(graph,'A'): - print(node) diff --git a/languages/python/algorithm_tree2.py b/languages/python/algorithm_tree2.py deleted file mode 100644 index 510fb387..00000000 --- a/languages/python/algorithm_tree2.py +++ /dev/null @@ -1,41 +0,0 @@ -class Node: - def __init__(self, value, left=None, right=None): - self.value = value - self.left = left - self.right = right - -n1 = Node(1) -n2 = Node(2) -n3 = Node(3,n1,n2) -n4 = Node(4) -n5 = Node(5,n4,n3) - -print('Inorder') -def inorder(n): - if n == None: - return - inorder(n.left) - print(n.value) - inorder(n.right) - -inorder(n5) - -print('Preorder') -def preorder(n): - if n == None: - return - print(n.value) - preorder(n.left) - preorder(n.right) - -preorder(n5) - -print('Postorder') -def postorder(n): - if n == None: - return - postorder(n.left) - postorder(n.right) - print(n.value) - -postorder(n5) diff --git a/languages/python/asyncio_examples/aiohttp_client.py b/languages/python/asyncio_examples/aiohttp_client.py deleted file mode 100644 index 3d225c80..00000000 --- a/languages/python/asyncio_examples/aiohttp_client.py +++ /dev/null @@ -1,44 +0,0 @@ -import asyncio - -from contextlib import closing - -import time - -import aiohttp - - -async def fetch_page(session, host, port=8000, wait=0): - url = '{}:{}/{}'.format(host, port, wait) - with aiohttp.Timeout(10): - async with session.get(url) as response: - assert response.status == 200 - return await response.text() - - -def get_multiple_pages(host, waits, port=8000, show_time=True): - tasks = [] - pages = [] - start = time.perf_counter() - - with closing(asyncio.get_event_loop()) as loop: - with aiohttp.ClientSession(loop=loop) as session: - for wait in waits: - tasks.append(fetch_page(session, host, port, wait)) - pages = loop.run_until_complete(asyncio.gather(*tasks)) - - duration = time.perf_counter() - start - sum_waits = sum(waits) - if show_time: - msg = "It took {:4.2f} seconds for a total waiting time of {:4.2f}." - print((msg.format(duration, sum_waits))) - return pages - -if __name__ == '__main__': - def main(): - """Test it.""" - pages = get_multiple_pages(host='http://localhost', - port='8888', - waits=[1, 5, 3, 2]) - for page in pages: - print(page) - main() diff --git a/languages/python/asyncio_examples/asyncio_twisted_similarity.py b/languages/python/asyncio_examples/asyncio_twisted_similarity.py deleted file mode 100644 index de96bbdb..00000000 --- a/languages/python/asyncio_examples/asyncio_twisted_similarity.py +++ /dev/null @@ -1,41 +0,0 @@ -""" -from twisted.internet import defer -from twisted.internet import reactor - -def multiply(x): - result = x * 2 - d = defer.Deferred() - reactor.callLater(1.0, d.callback, result) - return d - -def step1(x): - return multiply(x) - -def step2(result): - print("result: %s", result) - reactor.stop() - -d = deter.Deferred() -d.addCallback(step1) -d.addCallback(step2) -d.callback(5) - -reactor.run() -""" - -import asyncio - -async def multiply(x): - result = x * 2 - await asyncio.sleep(1) - return result - -async def steps(x): - result = await multiply(x) - print(("result: %s" % result)) - - -loop = asyncio.get_event_loop() -coro = steps(5) -loop.run_until_complete(coro) -loop.close() diff --git a/languages/python/asyncio_examples/creating_task.py b/languages/python/asyncio_examples/creating_task.py deleted file mode 100644 index a54ac9fc..00000000 --- a/languages/python/asyncio_examples/creating_task.py +++ /dev/null @@ -1,12 +0,0 @@ -import asyncio - -async def say(what, when): - await asyncio.sleep(when) - print(what) - -loop = asyncio.get_event_loop() -loop.create_task(say('first hello', 2)) -loop.create_task(say('second hello', 1)) - -loop.run_forever() -loop.close() diff --git a/languages/python/asyncio_examples/env.sh b/languages/python/asyncio_examples/env.sh deleted file mode 100644 index 2c37a102..00000000 --- a/languages/python/asyncio_examples/env.sh +++ /dev/null @@ -1,2 +0,0 @@ -#!/usr/bin/env bash -source /Users/senthil/python3.6/py36venv/bin/activate diff --git a/languages/python/asyncio_examples/get_onepage_async.py b/languages/python/asyncio_examples/get_onepage_async.py deleted file mode 100644 index a3ff23e4..00000000 --- a/languages/python/asyncio_examples/get_onepage_async.py +++ /dev/null @@ -1,100 +0,0 @@ -""" -Get a web page asynchronously. -""" - -import asyncio -import random -import time - -from contextlib import closing - -ENCODING = "ISO-8859-1" - - -def get_encoding(header): - """File out encoding.""" - for line in header: - if line.lstrip().startswith("Content-type"): - for entry in line.split(";"): - if entry.strip().startswith('charset'): - return entry.split('=')[1].strip() - return ENCODING - - -async def get_page(host, port, wait=0): - """Get a web-page asynchronously.""" - reader, writer = await asyncio.open_connection(host, port) - writer.write( - b'\r\n'.join([ - 'GET /{} HTTP/1.0'.format(wait).encode(ENCODING), - b'Host: %b' % host.encode(ENCODING), - b'Connection: close', - b'', - b''])) - header = [] - msg_lines = [] - async for raw_line in reader: - line = raw_line.decode(ENCODING).strip() - if not line.strip(): - break - header.append(line) - encoding = get_encoding(header) - async for raw_line in reader: - line = raw_line.decode(encoding).strip() - msg_lines.append(line) - writer.close() - return "\n".join(msg_lines) - - -def get_multiple_pages(host, port, waits, show_time=True): - """Get multiple pages.""" - start = time.perf_counter() - pages = [] - with closing(asyncio.get_event_loop()) as loop: - for wait in waits: - pages.append(loop.run_until_complete(get_page(host, port,wait))) - duration = time.perf_counter() - start - sum_waits = sum(waits) - if show_time: - msg = "It took {:4.2f} seconds for a total waiting time of {:4.2f}." - print((msg.format(duration, sum_waits))) - - return pages - - -def get_multiple_pages2(host, port, waits, show_time=True): - """Get multiple pages.""" - start = time.perf_counter() - pages = [] - tasks = [] - - with closing(asyncio.get_event_loop()) as loop: - for wait in waits: - tasks.append(get_page(host, port, wait)) - pages = loop.run_until_complete(asyncio.gather(*tasks)) - - duration = time.perf_counter() - start - sum_waits = sum(waits) - - if show_time: - msg = "It took {:4.2f} seconds for a total waiting time of {:4.2f}." - print((msg.format(duration, sum_waits))) - - return pages - - -if __name__ == '__main__': - - def main(): - """Test it!""" - if random.choice([True, False]): - pages = get_multiple_pages(host='localhost', port='8888',waits=[1, 5, 3, 2]) - for page in pages: - print(page) - else: - pages = get_multiple_pages2(host='localhost', port='8888',waits=[1, 5, 3, 2]) - for page in pages: - print(page) - - main() - diff --git a/languages/python/asyncio_examples/hello_clock.py b/languages/python/asyncio_examples/hello_clock.py deleted file mode 100644 index 30583289..00000000 --- a/languages/python/asyncio_examples/hello_clock.py +++ /dev/null @@ -1,26 +0,0 @@ -""" -Hello Clock - -Example illustrating how to schedule two coroutines to run concurrently. -They run for ten minutes, during which the first coroutine is scheduled to run every second, while the second is scheduled to run every minute. -""" - -import asyncio - -async def print_every_second(): - """"Print seconds.""" - while True: - for i in range(60): - print((i, 's')) - await asyncio.sleep(1) - -async def print_every_minute(): - """Print Every minute.""" - for i in range(1, 10): - await asyncio.sleep(60) - print((i, "minute")) - -loop = asyncio.get_event_loop() -loop.run_until_complete( - asyncio.gather(print_every_second(), print_every_minute())) -loop.close() diff --git a/languages/python/asyncio_examples/http_client.py b/languages/python/asyncio_examples/http_client.py deleted file mode 100644 index 761e254d..00000000 --- a/languages/python/asyncio_examples/http_client.py +++ /dev/null @@ -1,22 +0,0 @@ -""" -HTTP Client Example -""" - -import asyncio -import aiohttp - - -async def fetch_page(session, url): - with aiohttp.Timeout(10): - async with session.get(url) as response: - assert response.status == 200 - return await response.read() - -loop = asyncio.get_event_loop() - -with aiohttp.ClientSession(loop=loop) as session: - content = loop.run_until_complete( - fetch_page(session, "http://python.org")) - print(content) - -loop.close() diff --git a/languages/python/asyncio_examples/producer.py b/languages/python/asyncio_examples/producer.py deleted file mode 100644 index a7729ca5..00000000 --- a/languages/python/asyncio_examples/producer.py +++ /dev/null @@ -1,35 +0,0 @@ -import asyncio -import random - -async def produce(queue, n): - for x in range(1, n+1): - # produce an item - print(('producing {}/{}'.format(x, n))) - # simulate i/o operation using sleep - await asyncio.sleep(random.random()) - item = str(x) - # put the item in the queue - await queue.put(item) - - -async def consume(queue): - while True: - # wait for an item from the producer - item = await queue.get() - if item is None: - # producer emits None to indicate that it is done - break - - # process the item - - print(("consuming item {}...".format(item))) - # simulate the i/o operation using sleep - await asyncio.sleep(random.random()) - -loop = asyncio.get_event_loop() -queue = asyncio.Queue(loop=loop) -producer_coro = produce(queue, 10) -consumer_coro = consume(queue) - -loop.run_until_complete(asyncio.gather(producer_coro, consumer_coro)) -loop.close() diff --git a/languages/python/asyncio_examples/producer_consumer_task_done.py b/languages/python/asyncio_examples/producer_consumer_task_done.py deleted file mode 100644 index 23f8031a..00000000 --- a/languages/python/asyncio_examples/producer_consumer_task_done.py +++ /dev/null @@ -1,45 +0,0 @@ -""" -A simple producer/consumer example using Queue.task_done and Queue.join -""" - -import asyncio -import random - -async def produce(queue, n): - for x in range(n): - # produce an item - print(('producing {}/{}'.format(x, n))) - # simulate i/o operation using sleep - await asyncio.sleep(random.random()) - item = str(x) - # put the item in the queue - await queue.put(item) - - -async def consume(queue): - while True: - # wait for an item from the producer - item = await queue.get() - - # process the item - print(("consuming {}...".format(item))) - # simulate i/o operation using sleep - await asyncio.sleep(random.random()) - - # notify the queue that the item has been processed. - queue.task_done() - -async def run(n): - queue = asyncio.Queue() - # schedule a consumer - consumer = asyncio.ensure_future(consume(queue)) - # run the producer and wait for completion - await produce(queue, n) - # wait until the consumer has processed all items - await queue.join() - # the consumer is still awaiting for an item, cancel it - consumer.cancel() - -loop = asyncio.get_event_loop() -loop.run_until_complete(run(10)) -loop.close() diff --git a/languages/python/asyncio_examples/run_subprocess.py b/languages/python/asyncio_examples/run_subprocess.py deleted file mode 100644 index f298ba6d..00000000 --- a/languages/python/asyncio_examples/run_subprocess.py +++ /dev/null @@ -1,29 +0,0 @@ -import asyncio - -async def run_command(*args): - # Create a subprocess - process = await asyncio.create_subprocess_exec( - *args, - # stdout must be a pipe to be accessible as process.stdout - stdout=asyncio.subprocess.PIPE) - # Wait for the subprocess to finish - stdout, stderr = await process.communicate() - # return stdout - return stdout.decode().strip() - -loop = asyncio.get_event_loop() - -# Gather uname and date commands - -commands = asyncio.gather( - run_command('uname'), - run_command('date')) - -# Run the commands - -uname, date = loop.run_until_complete(commands) - -# Print a report - -print(('uname: {}, date: {}'.format(uname, date))) -loop.close() diff --git a/languages/python/asyncio_examples/simple_coroutine.py b/languages/python/asyncio_examples/simple_coroutine.py deleted file mode 100644 index 36d52cca..00000000 --- a/languages/python/asyncio_examples/simple_coroutine.py +++ /dev/null @@ -1,10 +0,0 @@ -import asyncio - -async def say(what, when): - await asyncio.sleep(when) - print(what) - - -loop = asyncio.get_event_loop() -loop.run_until_complete(say("Hello, World", 2)) -loop.close() diff --git a/languages/python/asyncio_examples/simple_server.py b/languages/python/asyncio_examples/simple_server.py deleted file mode 100644 index e81fa2bd..00000000 --- a/languages/python/asyncio_examples/simple_server.py +++ /dev/null @@ -1,53 +0,0 @@ -""" -Simple HTTP Server with GET that waits for given seconds. -""" - -from http.server import BaseHTTPRequestHandler, HTTPServer -from socketserver import ThreadingMixIn -import time - -ENCODING = 'utf-8' - - -class ThreadingHTTPServer(ThreadingMixIn, HTTPServer): - """Simple multi-threaded HTTP Server.""" - pass - - -class MyRequestHandler(BaseHTTPRequestHandler): - """Very simple request handler. Only supports GET.""" - - def do_GET(self): - """Respond after seconds given in path. - """ - try: - seconds = float(self.path[1:]) - except ValueError: - seconds = 0.0 - - if seconds < 0: - seconds = 0.0 - - text = "Waited for {:4.2f} seconds.\nThat's all.\n" - msg = text.format(seconds).encode(ENCODING) - time.sleep(seconds) - - self.send_response(200) - self.send_header("Content-type", "text/plain; charset=utf-8") - self.send_header("Content-length", str(len(msg))) - self.end_headers() - self.wfile.write(msg) - - -def run(server_class=ThreadingHTTPServer, - handler_class=MyRequestHandler, - port=8888): - """Run the simple server on a given port.""" - server_address = ('', port) - httpd = server_class(server_address, handler_class) - print(("Serving from port {}...".format(port))) - httpd.serve_forever() - - -if __name__ == '__main__': - run() diff --git a/languages/python/asyncio_examples/stopping_loop.py b/languages/python/asyncio_examples/stopping_loop.py deleted file mode 100644 index f2d914c1..00000000 --- a/languages/python/asyncio_examples/stopping_loop.py +++ /dev/null @@ -1,19 +0,0 @@ -import asyncio - -async def say(what, when): - await asyncio.sleep(when) - print(what) - -async def stop_after(loop, when): - await asyncio.sleep(when) - loop.stop() - -loop = asyncio.get_event_loop() - -loop.create_task(say("first hello", 2)) -loop.create_task(say("second hello", 1)) -loop.create_task(say("third hello", 4)) -loop.create_task(stop_after(loop, 3)) - -loop.run_forever() -loop.close() diff --git a/languages/python/asyncio_examples/subprocess_communicate.py b/languages/python/asyncio_examples/subprocess_communicate.py deleted file mode 100644 index 4f401abf..00000000 --- a/languages/python/asyncio_examples/subprocess_communicate.py +++ /dev/null @@ -1,32 +0,0 @@ -import asyncio - -async def echo(msg): - # Run an echo subprocess - process = await asyncio.create_subprocess_exec( - 'cat', - # stdin must a pipe to be accessible as a process.stdin - stdin=asyncio.subprocess.PIPE, - stdout=asyncio.subprocess.PIPE) - # Write a message - - print(('Writing {!r}...'.format(msg))) - process.stdin.write(msg.encode() + b'\n') - - # Read reply - - data = await process.stdout.readline() - reply = data.decode().strip() - - print(("Received {!r}".format(reply))) - - # Stop the subprocess - - process.terminate() - code = await process.wait() - - print(("Terminated with code {}".format(code))) - - -loop = asyncio.get_event_loop() -loop.run_until_complete(echo('hello!')) -loop.close() diff --git a/languages/python/asyncio_examples/sync_client.py b/languages/python/asyncio_examples/sync_client.py deleted file mode 100644 index ea72510b..00000000 --- a/languages/python/asyncio_examples/sync_client.py +++ /dev/null @@ -1,57 +0,0 @@ -""" -Synchronous client to retrieve web pages. -""" - -from urllib.request import urlopen -import time - -ENCODING = 'ISO-8859-1' - - -def get_encoding(http_response): - """Find out encoding.""" - content_type = http_response.getheader("Content-type") - for entry in content_type.split(";"): - if entry.strip().startswith('charset'): - return entry.split('=')[1].strip() - return ENCODING - - -def get_page(host, port, wait=0): - """Get one page suppling 'wait' time. - - The path will be build with 'host:port/wait' - """ - full_url = '{}:{}/{}'.format(host, port, wait) - with urlopen(full_url) as http_response: - html = http_response.read().decode(get_encoding(http_response)) - return html - - -def get_multiple_pages(host, port, waits, show_time=True): - """Get multiple pages.""" - - start = time.perf_counter() - pages = [get_page(host, port, wait) for wait in waits] - duration = time.perf_counter() - start - sum_waits = sum(waits) - - if show_time: - msg = "It took {:4.2f} seconds for a total waiting time of {:4.2f}." - print((msg.format(duration, sum_waits))) - - return pages - -if __name__ == '__main__': - - def main(): - """Test it.""" - pages = get_multiple_pages( - host='http://localhost', - port='8888', - waits=[1, 5, 3, 2]) - for page in pages: - print(page) - - main() - diff --git a/languages/python/asyncio_examples/tcp_echo_client.py b/languages/python/asyncio_examples/tcp_echo_client.py deleted file mode 100644 index c99f2ef9..00000000 --- a/languages/python/asyncio_examples/tcp_echo_client.py +++ /dev/null @@ -1,20 +0,0 @@ -import asyncio - -async def tcp_echo_client(message, loop): - reader, writer = await asyncio.open_connection( - '127.0.0.1', - 8888, - loop=loop) - print(("Send: %r" % message)) - writer.write(message.encode()) - - data = await reader.read(100) - print(("Received: %r" % data.decode())) - - print("Close the socket.") - writer.close() - -message = "hello, world!" -loop = asyncio.get_event_loop() -loop.run_until_complete(tcp_echo_client(message, loop)) -loop.close() diff --git a/languages/python/asyncio_examples/tcp_echo_server.py b/languages/python/asyncio_examples/tcp_echo_server.py deleted file mode 100644 index e0e0f52f..00000000 --- a/languages/python/asyncio_examples/tcp_echo_server.py +++ /dev/null @@ -1,31 +0,0 @@ -import asyncio - -async def handle_echo(reader, writer): - data = await reader.read(100) - message = data.decode() - addr = writer.get_extra_info('peername') - print(("Received %r from %r" % (message, addr))) - - print(("Send: %r" % message)) - writer.write(data) - await writer.drain() - - print("Close the client socket") - writer.close() - -loop = asyncio.get_event_loop() -coro = asyncio.start_server(handle_echo, '127.0.0.1', 8888, loop=loop) -server = loop.run_until_complete(coro) - -# Serve requests until Control+C is pressed -print(("Serving on {}".format(server.sockets[0].getsockname()))) - -try: - loop.run_forever() -except KeyboardInterrupt: - pass - -# close the server -server.close() -loop.run_until_complete(server.wait_closed()) -loop.close() diff --git a/languages/python/asyncio_examples/threads_example.py b/languages/python/asyncio_examples/threads_example.py deleted file mode 100644 index 2ee8048d..00000000 --- a/languages/python/asyncio_examples/threads_example.py +++ /dev/null @@ -1,14 +0,0 @@ -import asyncio - - -def compute_pi(digits): - # implementation - return 3.14 - -async def main(loop): - digits = await loop.run_in_executor(None, compute_pi, 20000) - print(("pi: %s" % digits)) - -loop = asyncio.get_event_loop() -loop.run_until_complete(main(loop)) -loop.close() diff --git a/languages/python/bs.png b/languages/python/bs.png deleted file mode 100644 index b5645343..00000000 Binary files a/languages/python/bs.png and /dev/null differ diff --git a/languages/python/coding_made_simple/max_rect_area.py b/languages/python/coding_made_simple/max_rect_area.py deleted file mode 100644 index 631ab1ec..00000000 --- a/languages/python/coding_made_simple/max_rect_area.py +++ /dev/null @@ -1,52 +0,0 @@ -""" -Title: Maximum Rectangular Area in Histogram -Video link: https://youtu.be/ZmnqCZp9bBs - -Java code: https://github.com/mission-peace/interview/blob/master/src/com/interview/stackqueue/MaximumHistogram.java - -""" - -class MaximumHistogram: - - def maxHistogram(self, _input): - stack = [] - max_area = 0 - area = 0 - i = 0 - while i < len(_input): - if len(stack) == 0 or stack[-1] <= _input[i]: - stack.append(i) - i += 1 - else: - top = stack.pop(-1) - - if len(stack) == 0: - area = _input[top] * i - else: - area = _input[top] * (i - stack[-1] - 1) - - max_area = max(area, max_area) - - while stack: - top = stack.pop(-1) - - if len(stack) == 0: - area = _input[top] * i - else: - area = _input[top] * (i - stack[-1] - 1) - - max_area = max(area, max_area) - - return max_area - - -if __name__ == "__main__": - _input = [2,2,2,6,1,5,4,2,2,2,2] - mh = MaximumHistogram() - print((mh.maxHistogram(_input))) - assert mh.maxHistogram(_input) == 12, "Algorithm did not specify the correct result." - - - - - diff --git a/languages/python/design_args_kwargs.py b/languages/python/design_args_kwargs.py deleted file mode 100644 index 2b69697e..00000000 --- a/languages/python/design_args_kwargs.py +++ /dev/null @@ -1,41 +0,0 @@ -def fun1(arg): - print(arg) - -def fun2(arg,arg2): - print(arg, arg2) - -def fun3(arg, *arg2): - print(arg, arg2) - -def fun4(*arg): - print(arg) - -def fun5(**kw): - print(kw) - -def fun6(*arg, **kw): - print(arg) - -def fun7(a, *arg, **kw): - print(a) - print(arg) - print(kw) - -def fun8(*arg, **kw): - print("***args", arg) - fun7(*arg, **kw) - -def fun9(a, b, *args, **kw): - fun8(a, b, *args, **kw) - -fun1(10) -fun2(10,20) -fun3(10,20,30) -fun3(10) -fun4(10,20,30,40) -fun5(a=10,b=20) -fun6(10,20,40) -fun7(10, 20, 30, k=40) -fun7(10, k=10) -fun8(10, 20, 30, k=40) -fun9(10, 20, 30, k=40) diff --git a/languages/python/design_ast_example1.py b/languages/python/design_ast_example1.py deleted file mode 100644 index b6f84759..00000000 --- a/languages/python/design_ast_example1.py +++ /dev/null @@ -1,18 +0,0 @@ -#!/usr/bin/python -#$Id$ - -""" -This program is directly executing it a Abstract Syntax Tree Level. -This is just doing xy*3. -""" -import ast - -node = ast.Expression(ast.BinOp( - ast.Str('xy'), - ast.Mult(), - ast.Num(3))) - -fixed = ast.fix_missing_locations(node) - -codeobj = compile(fixed, '', 'eval') -print(eval(codeobj)) diff --git a/languages/python/design_atexit_1.py b/languages/python/design_atexit_1.py deleted file mode 100644 index e12807cc..00000000 --- a/languages/python/design_atexit_1.py +++ /dev/null @@ -1,15 +0,0 @@ -import atexit - -def foo(): - print("foo") - -class SomeClass(object): - - def __init__(self): - self.a = 10 - self.b = 20 - atexit.register(foo) - -obj = SomeClass() -print(obj.a) -print(obj.b) diff --git a/languages/python/design_caseinsensitivedict.py b/languages/python/design_caseinsensitivedict.py deleted file mode 100644 index f2bab0a0..00000000 --- a/languages/python/design_caseinsensitivedict.py +++ /dev/null @@ -1,48 +0,0 @@ -#!/usr/bin/python -# $Id$ - -""" -Case Insenstive Dictionary Lookup. Dictionary keys are case sensitive. However -you might want some facilities to do a case-insenstive dictiionary lookup at -times. This provides the facility for the same. -""" - -class CaseInsensitiveDict(dict): - def __init__(self, *args, **kwargs): - self._keystore = {} - d = dict(*args, **kwargs) - for k in list(d.keys()): - self._keystore[self._get_lower(k)] = k - return super(CaseInsensitiveDict,self).__init__(*args,**kwargs) - - def __setitem__(self, k, v): - self._keystore[self._get_lower(k)] = k - return super(CaseInsensitiveDict, self).__setitem__(k, v) - - def __getitem__(self, k): - return super(CaseInsensitiveDict, - self).__getitem__(self._keystore[self._get_lower(k)]) - @staticmethod - def _get_lower(k): - if isinstance(k,str): - return k.lower() - else: - return k - -def test(): - obj = CaseInsensitiveDict([('name','senthil')]) - print(obj) - obj['Sname']='kumaran' - obj['spam'] ='eggs' - obj['SPAM']='ham' - print(list(obj.items())) - obj1 = dict(fname='FIRST') - obj.update(obj1) - print(obj) - print(list(obj.keys())) - print(list(obj.items())) - print(obj['NAME']) - print(obj['SNAME']) - -if __name__ == '__main__': - test() diff --git a/languages/python/design_closure1.py b/languages/python/design_closure1.py deleted file mode 100644 index 352a8fe4..00000000 --- a/languages/python/design_closure1.py +++ /dev/null @@ -1,17 +0,0 @@ -""" -A Simple Example of closure in python -A closure is function which returns another function. For example, the -``constant`` function here returns, ``_inner`` function. At the top level you -passed the value and calling the inner function from within, it is not required -to send the value. -""" -def constant(value): - def sq(x): - return x*x - - def _inner(): - return sq(value) - return _inner - -x = constant(5) -print((x())) diff --git a/languages/python/design_closure_example1.py b/languages/python/design_closure_example1.py deleted file mode 100644 index 46ea13c4..00000000 --- a/languages/python/design_closure_example1.py +++ /dev/null @@ -1,8 +0,0 @@ -class Constant(): - def __init__(self, value): - self._value = value - - def __call__(self): - return self._value -y = Constant(5) -print((y())) diff --git a/languages/python/design_context_2.py b/languages/python/design_context_2.py deleted file mode 100644 index e179677f..00000000 --- a/languages/python/design_context_2.py +++ /dev/null @@ -1,8 +0,0 @@ -from contextlib import contextmanager - -@contextmanager -def somefun(): - yield "something" - -with somefun() as f: - print(f) diff --git a/languages/python/design_contextmanager.py b/languages/python/design_contextmanager.py deleted file mode 100644 index 2658f07a..00000000 --- a/languages/python/design_contextmanager.py +++ /dev/null @@ -1,25 +0,0 @@ -""" -This is a simple example of a context manager. The context manager is -implemented by a decorator provided by the contextlib module. - -You will see that tag will yield after the first print statement and as it a -contextmanager, it is resumed after the __exit__ call, which is called by -default when the with statement falls out of scope and in that case, the next -print statement is called. - -This outputs: -

- foo -

-""" - -from contextlib import contextmanager - -@contextmanager -def tag(name): - print("<%s>" % name) - yield - print("" % name) - -with tag("h1"): - print("foo") diff --git a/languages/python/design_contextmanager_ex.py b/languages/python/design_contextmanager_ex.py deleted file mode 100644 index 4839ee8a..00000000 --- a/languages/python/design_contextmanager_ex.py +++ /dev/null @@ -1,13 +0,0 @@ -from contextlib import contextmanager - -@contextmanager -def opened(filename, mode="r"): - f = open(filename, mode) - try: - yield f - finally: - f.close() - -with opened("toss_coins.py") as f: - for line in f: - print(line.strip()) diff --git a/languages/python/design_decorator3.py b/languages/python/design_decorator3.py deleted file mode 100644 index 91418489..00000000 --- a/languages/python/design_decorator3.py +++ /dev/null @@ -1,15 +0,0 @@ -#!/usr/bin/python - -def my_decorator(fun): - def wrapper(*args): - print("Before Invocation") - fun(*args) - print("After Invocation") - return wrapper - -@my_decorator -def hello_world(x): - print("Hello, World") - print(x) - -hello_world(10) diff --git a/languages/python/design_ex_iterable27.py b/languages/python/design_ex_iterable27.py deleted file mode 100644 index 69784440..00000000 --- a/languages/python/design_ex_iterable27.py +++ /dev/null @@ -1,21 +0,0 @@ -#!/usr/bin/python - -class IterableObject(object): - """A Simple example of object iteration in Python.""" - def __init__(self): - self.obj_data = [] - - def __iter__(self): - for data_item in self.obj_data: - yield data_item - - -class Something(IterableObject): - def __init__(self): - self.obj_data = ["one", "two", "three", "four", "five"] - - -if __name__ == '__main__': - something = Something() - for i in something: - print (i) diff --git a/languages/python/design_func_args.py b/languages/python/design_func_args.py deleted file mode 100644 index 8def964d..00000000 --- a/languages/python/design_func_args.py +++ /dev/null @@ -1,25 +0,0 @@ -def fun1(arg): - print(arg) - -def fun2(arg,arg2): - print(arg, arg2) - -def fun3(arg, *arg2): - print(arg, arg2) - -def fun4(*arg): - print(arg) - -def fun5(**kw): - print(kw) - -def fun6(*arg, **kw): - print(arg) - - -fun1(10) -fun2(10,20) -fun3(10,20,30) -fun4(10,20,30,40) -fun5(a=10,b=20) -fun6(10,20,40) diff --git a/languages/python/design_generator.py b/languages/python/design_generator.py deleted file mode 100644 index cbf21eb7..00000000 --- a/languages/python/design_generator.py +++ /dev/null @@ -1,12 +0,0 @@ -def mygen(): - """Yield 5 until something else is passed back via send()""" - a = 5 - while True: - f = yield(a) #yield a and possibly get f in return - if f is not None: a = f #store the new value - -g = mygen() -print(next(g)) -print(next(g)) -g.send(7) -print(next(g)) diff --git a/languages/python/design_getattribute_example1.py b/languages/python/design_getattribute_example1.py deleted file mode 100644 index 0af49f49..00000000 --- a/languages/python/design_getattribute_example1.py +++ /dev/null @@ -1,22 +0,0 @@ - -# Override access to one variable in a class, but return all others normally - -class D(object): - def __init__(self): - self.test = 20 - self.test2 = 40 - def __getattribute__(self, name): - if name == 'test': - return 0 - else: - return self.__dict__[name] - -# The above wont work. -# This will give -# RuntimeError: maximum recursion depth exceeded in cmp -# Look at getattribute_example2.py for correct solution. - -obj1 = D() -print(obj1.test) -print(obj1.test2) - diff --git a/languages/python/design_getattribute_example2.py b/languages/python/design_getattribute_example2.py deleted file mode 100644 index 08a93d0f..00000000 --- a/languages/python/design_getattribute_example2.py +++ /dev/null @@ -1,17 +0,0 @@ - -# Override access to one variable in a class, but return all others normally -# http://stackoverflow.com/a/371833/18852 - -class D(object): - def __init__(self): - self.test = 20 - self.test2 = 40 - def __getattribute__(self, name): - if name == 'test': - return 0 - else: - return object.__getattribute__(self, name) - -obj1 = D() -print(obj1.test) -print(obj1.test2) diff --git a/languages/python/design_hextobin.py b/languages/python/design_hextobin.py deleted file mode 100644 index be187ca0..00000000 --- a/languages/python/design_hextobin.py +++ /dev/null @@ -1,4 +0,0 @@ -from functools import partial - -hexbin = partial(int, base=16) -print((bin(hexbin("FFFF")))) \ No newline at end of file diff --git a/languages/python/design_inheritance.py b/languages/python/design_inheritance.py deleted file mode 100644 index b97db7ae..00000000 --- a/languages/python/design_inheritance.py +++ /dev/null @@ -1,13 +0,0 @@ -class A(object): - def __init__(self): - print("A is called.") - -class B(object): - def __init__(self): - print("B is called.") - -class C(A, B): - def __init__(self): - super(C, self).__init__() - -c = C() diff --git a/languages/python/design_iterator_ex2.py b/languages/python/design_iterator_ex2.py deleted file mode 100644 index 85a1e188..00000000 --- a/languages/python/design_iterator_ex2.py +++ /dev/null @@ -1,12 +0,0 @@ -dict1 = {'a':1,'b':2,'c':3} - -sequence= dict1 - -it = iter(sequence) -while True: - try: - value = next(it) - except StopIteration: - break - print(value) - diff --git a/languages/python/design_object_size.py b/languages/python/design_object_size.py deleted file mode 100644 index 380f5a4a..00000000 --- a/languages/python/design_object_size.py +++ /dev/null @@ -1,12 +0,0 @@ -import pickle -import sys - -obj = list(range(10000)) - -def GetMemoryUsage(ob): - s = pickle.dumps(ob) - memUsed = sys.getpymemalloced() - ob2 = pickle.loads(s) - return sys.getpymemalloced() - memUsed - -print(GetMemoryUsage(obj)) diff --git a/languages/python/design_python3_meta_ex1.py b/languages/python/design_python3_meta_ex1.py deleted file mode 100644 index 4b247ed8..00000000 --- a/languages/python/design_python3_meta_ex1.py +++ /dev/null @@ -1,18 +0,0 @@ -class mymeta(type): - def __new__(cls, name, bases, dict): - print(("Creating name:", name)) - print(("Base Classes:", bases)) - print(("Class Body:", dict)) - # create the actual class object - return type.__new__(cls, name, bases, dict) - -class Rectangle(object, metaclass=mymeta): - def __init__(self, width, height): - self.width = width - self.height = height - - def area(self): - return self.width * self.height - - def perimeter(self): - return 2*self.width + 2* self.height diff --git a/languages/python/design_python_objects_type.py b/languages/python/design_python_objects_type.py deleted file mode 100644 index 54c14742..00000000 --- a/languages/python/design_python_objects_type.py +++ /dev/null @@ -1,38 +0,0 @@ -print('issubclass(type,object) ', issubclass(type,object)) -print('issubclass(object,type) ', issubclass(object,type)) -print('isinstance(type,object) ', isinstance(type,object)) -print('isinstance(object,type) ', isinstance(object,type)) -print('-------------------------') -try: - print(issubclass(True,object)) -except TypeError: - print('issubclass(True,object) does not make sense. Object is not class.') -try: - print(issubclass(1,object)) -except TypeError: - print('issubclass(1,object) does not make sense. Object is not class') -try: - print(issubclass('c',object)) -except TypeError: - print("issubclass('c',object) does not make sense. Object is not class") -print('-------------------------') -try: - print(issubclass(True,type)) -except TypeError: - print('issubclass(True,type) does not make sense. type is not class.') -try: - print(issubclass(1,type)) -except TypeError: - print('issubclass(1,type) does not make sense. type is not class') -try: - print(issubclass('c',type)) -except TypeError: - print("issubclass('c',type) does not make sense. type is not class") -print('-------------------------') -print('isinstance(True,object) ', isinstance(True,object)) -print('isinstance(1,object) ', isinstance(True,object)) -print('isinstance("c",object) ', isinstance(True,object)) -print('-------------------------') -print('isinstance(True,type) ', isinstance(True,type)) -print('isinstance(1,type) ', isinstance(True,type)) -print('isinstance("c",type) ', isinstance(True,type)) diff --git a/languages/python/design_restricter_class.py b/languages/python/design_restricter_class.py deleted file mode 100644 index 9a228206..00000000 --- a/languages/python/design_restricter_class.py +++ /dev/null @@ -1,20 +0,0 @@ -class RestrictingWrapper(object): - def __init__(self, obj, to_block): - self._obj = obj - self._to_block = to_block - - def __getattr__(self, name): - if name in self._to_block: - raise AttributeError(name) - return getattr(self._obj, name) - -class Foo(object): - def __init__(self, x, y, z): - self.x, self.y, self.z = x, y, z - -f1 = Foo(1, 2, 3) -print(f1.x, f1.y, f1.z) - -f2 = RestrictingWrapper(f1, "z") -print(f2.x, f2.y) -print(f2.z) diff --git a/languages/python/design_simple_closure.py b/languages/python/design_simple_closure.py deleted file mode 100644 index a9ab690d..00000000 --- a/languages/python/design_simple_closure.py +++ /dev/null @@ -1,13 +0,0 @@ -""" -A Simple Example of closure in python -A closure is function which returns another function. For example, the -``constant`` function here returns, ``_inner`` function. At the top level you -passed the value and calling the inner function from within, it is not required -to send the value. -""" -def constant(value): - def _inner(): - return value - return _inner -x = constant(5) -print((x())) diff --git a/languages/python/design_slice_ellipses.py b/languages/python/design_slice_ellipses.py deleted file mode 100644 index b0651933..00000000 --- a/languages/python/design_slice_ellipses.py +++ /dev/null @@ -1,5 +0,0 @@ -class C(object): - def __getitem__(self, item): - return item - -print(C()[1:2, ..., 3]) diff --git a/languages/python/design_sorted_loop.py b/languages/python/design_sorted_loop.py deleted file mode 100644 index 812e1e20..00000000 --- a/languages/python/design_sorted_loop.py +++ /dev/null @@ -1,8 +0,0 @@ -import random -import time -start = time.time() -r = random.sample(list(range(10)), 5) -for x in range(1000): - for i in sorted(r): - pass -print(time.time() - start) diff --git a/languages/python/design_stackinspection.py b/languages/python/design_stackinspection.py deleted file mode 100644 index b2587083..00000000 --- a/languages/python/design_stackinspection.py +++ /dev/null @@ -1,6 +0,0 @@ -import sys -def foo(): - """blah""" - print(sys._getframe().f_back.f_locals[sys._getframe().f_code.co_name].__doc__) - -foo() diff --git a/languages/python/design_struct_example.py b/languages/python/design_struct_example.py deleted file mode 100644 index 0b4ba565..00000000 --- a/languages/python/design_struct_example.py +++ /dev/null @@ -1,29 +0,0 @@ -#!/usr/bin/python -""" -$Id$ - -Purpose: - Demonstrate the way the struct module works. - -Description: - One can access substrings of a string in a arbitrary manner while using the - struct module. This is mostly useful when dealing with byte level - programming required in embedded systems or while using sockets. - -Source: - Python cookbook perhaps. -""" -import struct -theline = "The quick brown fox jumped over the lazy dog." -# Get a 5-byte string, skip 3, get two 8-byte string, then all the rest: -baseformat = '5s 3x 8s 8s' -# by how many bytes does theline exceed the length implied by this -# base-format ( 24 bytes in this, but struct.calcsize is general) -numremain = len(theline) - struct.calcsize(baseformat) -# complete the format with the appropriate 's' field, then unpack -format = '%s %ds' % (baseformat, numremain) -l, s1, s2, t = struct.unpack(format, theline) -print(l) -print(s1) -print(s2) -print(t) diff --git a/languages/python/design_total_ordering.py b/languages/python/design_total_ordering.py deleted file mode 100644 index 8d7489e3..00000000 --- a/languages/python/design_total_ordering.py +++ /dev/null @@ -1,33 +0,0 @@ -from functools import total_ordering - -""" - -http://en.wikipedia.org/wiki/Total_order - -For pair of items from a set, (that's the total) -if a <= b and b <= c then a <= c (part of the order) -if a <= b and b <= a then a compares the same as b, a == b, (the -other part of the order) - -""" - -@total_ordering -class Student: - def __init__(self, lastname, firstname): - self.firstname = firstname - self.lastname = lastname - def __eq__(self, other): - return ((self.lastname.lower(), self.firstname.lower()) == - (other.lastname.lower(), other.firstname.lower())) - def __lt__(self, other): - return ((self.lastname.lower(), self.firstname.lower()) < - (other.lastname.lower(), other.firstname.lower())) - - -student1 = Student("Bond","James") -student2 = Student("Haddock","Captain") - -# Where are these coming from? -print((student2 > student1)) # True -print((student2 >= student2)) # True -print((student2 != student1)) # True diff --git a/languages/python/design_traceit.py b/languages/python/design_traceit.py deleted file mode 100644 index 0de7e26f..00000000 --- a/languages/python/design_traceit.py +++ /dev/null @@ -1,15 +0,0 @@ -import sys -import linecache -import random - -def traceit(frame, event, arg): - if event == "line": - lineno = frame.f_lineno - filename = frame.f_globals["__file__"] - if (filename.endswith(".pyc") or - filename.endswith(".pyo")): - filename = filename[:-1] - name = frame.f_globals["__name__"] - line = linecache.getline(filename, lineno) - print("%s:%s: %s" % (name, lineno, line.rstrip())) - return traceit diff --git a/languages/python/fbcup1.py b/languages/python/fbcup1.py deleted file mode 100644 index 9fbc417a..00000000 --- a/languages/python/fbcup1.py +++ /dev/null @@ -1,34 +0,0 @@ -import string -from collections import Counter -from collections import defaultdict - -words = set(string.ascii_uppercase) -vowels = set(['A','E','I','O','U']) -consonants = words - vowels - - -T = int(input()) -for tc in range(T): - reverse_dict = defaultdict(list) - num_vowels = 0 - num_consonants = 0 - tcn = tc + 1 - word = input() - chars = set(word) - if len(chars) == 1: - print(f"Case #{tcn}:", 0) - continue - for c in chars: - if c in vowels: - num_vowels += 1 - else: - num_consonants += 1 - print(f"consonants: {num_consonants}, vowels: {num_vowels}") - word_counter = Counter(word) - for w, c in word_counter.items(): - reverse_dict[c].append(w) - sorted_keys = sorted(reverse_dict.keys(), reverse=True) - # pick the one that you are not changing. - print(reverse_dict) - print(sorted_keys) - diff --git a/languages/python/files_count_lines_large_file.py b/languages/python/files_count_lines_large_file.py deleted file mode 100644 index acb44336..00000000 --- a/languages/python/files_count_lines_large_file.py +++ /dev/null @@ -1,19 +0,0 @@ -# files_count_lines_large_file.py - 30-08-2015 08:13 - -CHUNK_SIZE = 8192 * 1024 - -def count_lines(file_path): - count = 0 - with open(file_path, 'rb') as fh: - while True: - buffer = fh.read(CHUNK_SIZE) - if not buffer: - break - count += buffer.count('\n') - return count - -def main(): - print((count_lines('./files_count_lines_large_file.py'))) - -if __name__ == '__main__': - main() diff --git a/languages/python/files_processing_every_word.py b/languages/python/files_processing_every_word.py deleted file mode 100644 index 335bad9e..00000000 --- a/languages/python/files_processing_every_word.py +++ /dev/null @@ -1,18 +0,0 @@ -import re - -WORD_REGEX = re.compile(r"[\w'-]+") - -def do_something_with_word(word): - print(word) - -def words_in_file(file_name): - with open(file_name) as fh: - for line in fh: - for word in WORD_REGEX.finditer(line): - do_something_with_word(word.group(0)) - -def main(): - words_in_file('./files_processing_every_word.py') - -if __name__ == '__main__': - main() \ No newline at end of file diff --git a/languages/python/files_random_access_input_output.py b/languages/python/files_random_access_input_output.py deleted file mode 100644 index 240d65ce..00000000 --- a/languages/python/files_random_access_input_output.py +++ /dev/null @@ -1,16 +0,0 @@ -def seek_and_read(file_name, buf_size, byte_number): - with open(file_name) as f: - f.seek(byte_number) - buf = f.read(buf_size) - return buf - -def main(): - buf_size = 48 - byte_number = 6 - print(seek_and_read( - './files_random_access_input_output.py', - buf_size, - byte_number)) - -if __name__ == '__main__': - main() diff --git a/languages/python/files_read_specific_line.py b/languages/python/files_read_specific_line.py deleted file mode 100644 index 978a5004..00000000 --- a/languages/python/files_read_specific_line.py +++ /dev/null @@ -1,15 +0,0 @@ -import linecache - - -def get_line_from_a_file(file_path, line_number): - return linecache.getline(file_path, line_number) - - -def main(): - file_path = './files_read_specific_line.py' - desired_line_number = 10 - print(get_line_from_a_file(file_path, desired_line_number)) - - -if __name__ == '__main__': - main() diff --git a/languages/python/files_reading_zipfile.py b/languages/python/files_reading_zipfile.py deleted file mode 100644 index 0dc68c70..00000000 --- a/languages/python/files_reading_zipfile.py +++ /dev/null @@ -1,17 +0,0 @@ - - -import zipfile - -def read_zip(filename): - with zipfile.ZipFile(filename, 'r') as z: - for zip_filename in z.namelist(): - print("File: {0}".format(zip_filename)) - _bytes = z.read(zip_filename) - print("has {0} bytes".format(len(_bytes))) - -def main(): - filename = 'sample.zip' - read_zip(filename) - -if __name__ == '__main__': - main() diff --git a/languages/python/font.ttf b/languages/python/font.ttf deleted file mode 100644 index 9c691234..00000000 Binary files a/languages/python/font.ttf and /dev/null differ diff --git a/languages/python/index.txt b/languages/python/index.txt deleted file mode 100644 index 786b684f..00000000 --- a/languages/python/index.txt +++ /dev/null @@ -1,9 +0,0 @@ -restindex - crumb: python-programs - format: rest - encoding: utf-8 - output-encoding: None -/restindex - -Python programs ---------------- diff --git a/languages/python/input.txt b/languages/python/input.txt deleted file mode 100644 index 8298ec00..00000000 --- a/languages/python/input.txt +++ /dev/null @@ -1,4 +0,0 @@ -In a language familiar to you, if you keep the first and the last character of -each word in the sentence, your can easily read the sentence. - -This is one of my earliest program that seems to have survived and still gives joy! diff --git a/languages/python/input.txt~ b/languages/python/input.txt~ deleted file mode 100644 index 470a874b..00000000 --- a/languages/python/input.txt~ +++ /dev/null @@ -1 +0,0 @@ -This is one of my earliest program that seems to have survived and still gives joy! diff --git a/languages/python/min_cost_path.py b/languages/python/min_cost_path.py deleted file mode 100644 index 6bdd4a2a..00000000 --- a/languages/python/min_cost_path.py +++ /dev/null @@ -1,42 +0,0 @@ -# min_cost_path.py - 26-04-2020 09:11 - -from typing import List - -# Video: https://www.youtube.com/watch?v=lBRtnuxg-gU - - -class Solution: - - def minPathSum(self, grid: List[List[int]]) -> int: - m = len(grid) - n = len(grid[0]) - T = [[0] * n for _ in range(m)] - # First left top corner cost is same. - T[0][0] = grid[0][0] - - # First row in T - for first_row_idx in range(1, n): - T[0][first_row_idx] = T[0][first_row_idx-1] + grid[0][first_row_idx] - - # First col in T - for first_col_idx in range(1, m): - T[first_col_idx][0] = T[first_col_idx-1][0] + grid[first_col_idx][0] - - # Fill in the rest of the 2D matrix for T. - for i in range(1, m): - for j in range(1, n): - T[i][j] = grid[i][j] + min(T[i-1][j], # top - T[i][j-1]) # left - - # value to reach the right most end - return T[-1][-1] - - -if __name__ == '__main__': - s = Solution() - mat = [ - [1, 3, 1], - [1, 5, 1], - [4, 2, 1] - ] - print((s.minPathSum(mat))) diff --git a/languages/python/networking_allifaces.py b/languages/python/networking_allifaces.py deleted file mode 100644 index f05bfb7d..00000000 --- a/languages/python/networking_allifaces.py +++ /dev/null @@ -1,45 +0,0 @@ -#:w/usr/bin/python -# $Id$ -""" -List Network Interfaces - -**Purpose**: This program provides list of network interfaces available on -your machine. - -**Description**: man netdevice provides the following information about -SIOCGIFCONF which is used to retrieve the interfaces information. - -SIOCGIFCONF - -Return a list of interface (transport layer) addresses. This currently means -only addresses of the AF_INET (IPv4) family for compatibility. The user passes -a ifconf structure as argument to the ioctl. It contains a pointer to an array -of ifreq structures in ifc_req and its length in bytes in ifc_len. The kernel -fills the ifreqs with all current L3 interface addresses that are running: -ifr_name contains the interface name (eth0:1 etc.), ifr_addr the address. The -kernel returns with the actual length in ifc_len. If ifc_len is equal to the -original length the buffer probably has overflowed and you should retry with a -bigger buffer to get all addresses. When no error occurs the ioctl returns 0; -otherwise -1. Overflow is not an error. - -""" - -import socket -import fcntl -import struct -import array - -def all_interfaces(): - max_possible = 128 # arbitrary. raise if needed. - bytes = max_possible * 32 - s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) - names = array.array('B', '\0' * bytes) - outbytes = struct.unpack('iL', fcntl.ioctl( - s.fileno(), - 0x8912, # SIOCGIFCONF - struct.pack('iL', bytes, names.buffer_info()[0]) - ))[0] - namestr = names.tostring() - return [namestr[i:i+32].split('\0', 1)[0] for i in range(0, outbytes, 32)] - -print(all_interfaces()) diff --git a/languages/python/networking_allipaddress.py b/languages/python/networking_allipaddress.py deleted file mode 100644 index 32726d66..00000000 --- a/languages/python/networking_allipaddress.py +++ /dev/null @@ -1,44 +0,0 @@ -#!/usr/bin/python -# $Id$ - -""" -**Purpose**: The program gets all the ipaddress assigned to all the interfaces -in your machine. - -**Description**: Get all the interfaces using SIOCGIFCONF ioctl call and then -use SIOCGIFADDR to get its address. - -man networking says that SIOCGIFADDR Get interface address for -protocol family. - -""" - -import socket -import fcntl -import struct -import array - -def all_interfaces(): - max_possible = 128 # arbitrary. raise if needed. - bytes = max_possible * 32 - s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) - names = array.array('B', '\0' * bytes) - outbytes = struct.unpack('iL', fcntl.ioctl( - s.fileno(), - 0x8912, # SIOCGIFCONF - struct.pack('iL', bytes, names.buffer_info()[0]) - ))[0] - namestr = names.tostring() - return [namestr[i:i+32].split('\0', 1)[0] for i in range(0, outbytes, 32)] - -def get_ip_address(ifname): - s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) - return socket.inet_ntoa(fcntl.ioctl( - s.fileno(), - 0x8915, # SIOCGIFADDR - struct.pack('256s', ifname[:15]) - )[20:24]) - -for each in all_interfaces(): - if each: - print(get_ip_address(each)) diff --git a/languages/python/networking_bug_gethostbyname.py b/languages/python/networking_bug_gethostbyname.py deleted file mode 100644 index 736b708b..00000000 --- a/languages/python/networking_bug_gethostbyname.py +++ /dev/null @@ -1,32 +0,0 @@ -#!/usr/bin/python -#$Id$ -""" -Generate a random domain name and see if it actually exists by doing a -gethostbyname call. -""" - -from socket import * -import sys - -def test(name): - print("enter test, gethostbyname(%r)" % name) - print("You can press CTRL-C") - try: - try: - gethostbyname(name) - except: - print("inner try") - E = sys.exc_info()[0] - print(type(E), repr(E), E is KeyboardInterrupt) - raise - except: - print("outer try") - E = sys.exc_info()[0] - print(type(E), repr(E), E is KeyboardInterrupt) - print("exit test") - -import random -letters = list("typingsomeuselessword") -random.shuffle(letters) -name = ".".join(letters[:5]) + ".com" -test(name) diff --git a/languages/python/networking_email1.py b/languages/python/networking_email1.py deleted file mode 100755 index 4a261b28..00000000 --- a/languages/python/networking_email1.py +++ /dev/null @@ -1,24 +0,0 @@ -# Import smtplib for the actual sending function -import smtplib - -# Import the email modules we'll need -from email.mime.text import MIMEText - -# Open a plain text file for reading. For this example, assume that -# the text file contains only ASCII characters. -fp = open('content.txt', 'rb') -# Create a text/plain message -msg = MIMEText(fp.read()) -fp.close() - -me = 'orsenthil@gmail.com' -you = 'senthil@uthcode.com' -msg['Subject'] = 'Hello' -msg['From'] = me -msg['To'] = you - -# Send the message via our own SMTP server, but don't include the -# envelope header. -s = smtplib.SMTP('smtp.gmail.com') -s.sendmail(me, [you], msg.as_string()) -s.quit() diff --git a/languages/python/networking_email2.py b/languages/python/networking_email2.py deleted file mode 100644 index a0fd8d4c..00000000 --- a/languages/python/networking_email2.py +++ /dev/null @@ -1,17 +0,0 @@ -import smtplib -import getpass - -fromaddr = 'orsenthil@gmail.com' -toaddrs = 'senthil@uthcode.com' -msg = 'There was a terrible error that occured and I wanted you to know!' - -# Credentials (if needed) -username = 'orsenthil' -password = getpass.getpass() - -# The actual mail send -server = smtplib.SMTP('smtp.gmail.com:587') -server.starttls() -server.login(username,password) -server.sendmail(fromaddr, toaddrs, msg) -server.quit() diff --git a/languages/python/networking_email3.py b/languages/python/networking_email3.py deleted file mode 100644 index 67b96684..00000000 --- a/languages/python/networking_email3.py +++ /dev/null @@ -1,50 +0,0 @@ -import smtplib - -from email.MIMEMultipart import MIMEMultipart -from email.MIMEBase import MIMEBase -from email.MIMEText import MIMEText -from email import Encoders -import os - -me = 'Name ' - -username = '' -password = 'password' -textfile = 'message.txt' -attachment = 'picture.png' - - -def send_email(name, to_email): - you = to_email - msg = MIMEMultipart() - - msg['From'] = me - msg['To'] = you - msg['Subject'] = 'Subject' - - fp = open(textfile, 'rb') - contents = fp.read() - contents = contents.format(friend=name) - msg.attach(MIMEText(contents)) - fp.close() - - email_attachment = MIMEBase('application', 'octet-stream') - email_attachment.set_payload(open(attachment, 'rb').read()) - Encoders.encode_base64(email_attachment) - email_attachment.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(attachment)) - - msg.attach(email_attachment) - - server = smtplib.SMTP('smtp.gmail.com:587') - server.ehlo() - server.starttls() - server.ehlo() - server.login(username, password) - server.sendmail(me, [you], msg.as_string()) - server.close() - - -if __name__ == '__main__': - name = "recipient name" - email = "recipient email" - send_email(name, email) diff --git a/languages/python/networking_email4.py b/languages/python/networking_email4.py deleted file mode 100644 index 90a0457e..00000000 --- a/languages/python/networking_email4.py +++ /dev/null @@ -1,56 +0,0 @@ -""" -Python3 script to send email via gmail. - -Pre-requisite: https://www.google.com/settings/security/lesssecureapps -""" -import os -import smtplib -from email.mime.multipart import MIMEMultipart -from email.mime.text import MIMEText - -_DEFAULT_FROM_ADDRESS = "" -_DEFAULT_FROM_PASSWORD = "" -_DEFAULT_TO_ADDRESS = "" - - -FROM_ADDRESS = os.environ.get("FROM_ADDRESS", _DEFAULT_FROM_ADDRESS) -FROM_PASSWORD = os.environ.get("FROM_PASSWORD", _DEFAULT_FROM_PASSWORD) -TO_ADDRESS = os.environ.get("TO_ADDRESS", _DEFAULT_TO_ADDRESS) -MAIL_SERVER = "smtp.gmail.com" -MAIL_PORT = 587 - - -def create_message(subject="", body="") -> MIMEMultipart: - msg = MIMEMultipart() - msg["From"] = FROM_ADDRESS - msg["To"] = TO_ADDRESS - msg["Subject"] = subject - msg.attach(MIMEText(body, 'plain')) - return msg - - -def send_mail(msg: MIMEMultipart): - server = smtplib.SMTP(MAIL_SERVER, MAIL_PORT) - server.ehlo() - server.starttls() - server.login(FROM_ADDRESS, FROM_PASSWORD) - text = msg.as_string() - server.sendmail(FROM_ADDRESS, [TO_ADDRESS], text) - server.quit() - - -SUBJECT = "Game" - -MESSAGE = """ -Hello There! - -Let's play a game. - -Cheers! -""" - -if __name__ == '__main__': - subject = SUBJECT - body = MESSAGE - msg = create_message(subject, body) - send_mail(msg) diff --git a/languages/python/networking_fetchrfc.py b/languages/python/networking_fetchrfc.py deleted file mode 100644 index 1fdd1bba..00000000 --- a/languages/python/networking_fetchrfc.py +++ /dev/null @@ -1,19 +0,0 @@ -#!/usr/bin/python -import sys -import optparse -import urllib.request, urllib.parse, urllib.error - -RFC_BASE = 'http://www.ietf.org/rfc/rfc' - -parser = optparse.OptionParser() -parser.add_option('-r','--rfc', - dest='rfc_name', - ) -options, remainder = parser.parse_args() - -RFC_NAME = options.rfc_name + '.txt' - -RFC = RFC_BASE + RFC_NAME - -urllib.request.urlretrieve(RFC,filename=RFC_NAME) -print('Here you have:', RFC_NAME) diff --git a/languages/python/networking_socket_client.py b/languages/python/networking_socket_client.py deleted file mode 100644 index be035c83..00000000 --- a/languages/python/networking_socket_client.py +++ /dev/null @@ -1,20 +0,0 @@ -""" -This is a simple socket client. It connects to a host and port and creates a -fileobject using makefile and prints the content of it. -I don't remember when or why I wrote this. -""" - -import socket -import sys - -def main(): - s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - host = sys.argv[1] - port = int(sys.argv[2]) - s.connect((host, port)) - flo = s.makefile('r',0) - for l in flo: - print(l) - -if __name__ == '__main__': - main() diff --git a/languages/python/networking_socket_example1.py b/languages/python/networking_socket_example1.py deleted file mode 100644 index 2f2bdcca..00000000 --- a/languages/python/networking_socket_example1.py +++ /dev/null @@ -1,16 +0,0 @@ -import socket -from urllib.parse import urlparse - -for url in [ 'http://www.python.org', - 'https://www.mybank.com', - 'ftp://prep.ai.mit.edu', - 'gopher://gopher.micro.umn.edu', - 'smtp://mail.example.com', - 'imap://mail.example.com', - 'imaps://mail.example.com', - 'pop3://pop.example.com', - 'pop3s://pop.example.com', - ]: - parsed_url = urlparse(url) - port = socket.getservbyname(parsed_url.scheme) - print('%6s : %s' % (parsed_url.scheme, port)) diff --git a/languages/python/networking_socket_example2.py b/languages/python/networking_socket_example2.py deleted file mode 100644 index 0edd3029..00000000 --- a/languages/python/networking_socket_example2.py +++ /dev/null @@ -1,17 +0,0 @@ -import socket - -def get_constants(prefix): - """Create a dictionary mapping socket module constants to their names.""" - return dict( (getattr(socket, n), n) - for n in dir(socket) - if n.startswith(prefix) - ) - -protocols = get_constants('IPPROTO_') - -for name in [ 'icmp', 'udp', 'tcp' ]: - proto_num = socket.getprotobyname(name) - print(proto_num) - const_name = protocols[proto_num] - print('%4s -> %2d (socket.%-12s = %2d)' % \ - (name, proto_num, const_name, getattr(socket, const_name))) diff --git a/languages/python/networking_socket_example3.py b/languages/python/networking_socket_example3.py deleted file mode 100644 index ec48e08a..00000000 --- a/languages/python/networking_socket_example3.py +++ /dev/null @@ -1,31 +0,0 @@ -import socket - -def get_constants(prefix): - """Create a dictionary mapping socket module constants to their names.""" - return dict( (getattr(socket, n), n) - for n in dir(socket) - if n.startswith(prefix) - ) - -families = get_constants('AF_') -print(families) -types = get_constants('SOCK_') -print(types) -protocols = get_constants('IPPROTO_') -print(protocols) - -for response in socket.getaddrinfo('endhiroid.blogspot.com', 'http', - socket.AF_INET, # family - socket.SOCK_STREAM, # socktype - socket.IPPROTO_TCP, # protocol - socket.AI_CANONNAME, # flags - ): - # Unpack the response tuple - family, socktype, proto, canonname, sockaddr = response - - print('Family :', families[family]) - print('Type :', types[socktype]) - print('Protocol :', protocols[proto]) - print('Canonical name:', canonname) - print('Socket address:', sockaddr) - print() diff --git a/languages/python/networking_socket_example4.py b/languages/python/networking_socket_example4.py deleted file mode 100644 index 6d801f4b..00000000 --- a/languages/python/networking_socket_example4.py +++ /dev/null @@ -1,22 +0,0 @@ -import socket -import os - -parent, child = socket.socketpair() - -pid = os.fork() - -if pid: - print('in parent, sending message') - child.close() - parent.sendall('ping') - response = parent.recv(1024) - print('response from child:', response) - parent.close() - -else: - print('in child, waiting for message') - parent.close() - message = child.recv(1024) - print('message from parent:', message) - child.sendall('pong') - child.close() diff --git a/languages/python/networking_twisted1.py b/languages/python/networking_twisted1.py deleted file mode 100644 index 59f150cd..00000000 --- a/languages/python/networking_twisted1.py +++ /dev/null @@ -1,11 +0,0 @@ -from twisted.internet import task -from twisted.internet import reactor - -def runEverySecond(): - print("a second has passed") - -l = task.LoopingCall(runEverySecond) -l.start(1.0) # call every second - -# l.stop() will stop the looping calls -reactor.run() diff --git a/languages/python/networking_twisted2.py b/languages/python/networking_twisted2.py deleted file mode 100644 index bdb13277..00000000 --- a/languages/python/networking_twisted2.py +++ /dev/null @@ -1,18 +0,0 @@ -""" -How is the out value passed to the function1? - -utils.getProcessOutput function is returning a deffered object. -You attach a callback function to the deferred object. -When the defered is ready with the result, the callback function is called with -it. That is what is happening here. - -""" - -from twisted.internet import utils, reactor - -def function1(out): - print(out) - reactor.stop() -output = utils.getProcessOutput('ls') -output.addCallback(function1) -reactor.run() diff --git a/languages/python/networking_twisted3.py b/languages/python/networking_twisted3.py deleted file mode 100644 index c9586409..00000000 --- a/languages/python/networking_twisted3.py +++ /dev/null @@ -1,24 +0,0 @@ -# -*- coding: utf8 -*- -import io as StringIO - -from twisted.internet import reactor -from twisted.web.client import getPage -from twisted.python.util import println -from lxml import etree - -def parseHtml(html): - parser = etree.HTMLParser(encoding='utf8') - tree = etree.parse(StringIO.StringIO(html), parser) - return tree - -def extractTitle(tree): - return tree - #titleText = unicode(tree.xpath("//title/text()")[0]) - #return titleText - -d = getPage('http://www.uthcode.com') -d.addCallback(parseHtml) -d.addCallback(extractTitle) -d.addBoth(println) - -reactor.run() diff --git a/languages/python/networking_twisted4.py b/languages/python/networking_twisted4.py deleted file mode 100644 index ecd28813..00000000 --- a/languages/python/networking_twisted4.py +++ /dev/null @@ -1,9 +0,0 @@ -import traceback - -def stack(): - print('The python stack:') - traceback.print_stack() - -from twisted.internet import reactor -reactor.callWhenRunning(stack) -reactor.run() diff --git a/languages/python/networking_twisted5.py b/languages/python/networking_twisted5.py deleted file mode 100644 index eae51d66..00000000 --- a/languages/python/networking_twisted5.py +++ /dev/null @@ -1,21 +0,0 @@ -# Example code which illustrates twisted's outline - -from twisted.internet.protocol import Factory, Protocol -from twisted.internet import reactor - -class QOTD(Protocol): - - def connectionMade(self): - self.transport.write(self.factory.quote+'\r\n') - self.transport.loseConnection() - - -class QOTDFactory(Factory): - - protocol = QOTD - - def __init__(self, quote=None): - self.quote = quote or 'An apple a day keeps the doctor away' - -reactor.listenTCP(8007, QOTDFactory("configurable quote")) -reactor.run() diff --git a/languages/python/networking_twisted_parallel1.py b/languages/python/networking_twisted_parallel1.py deleted file mode 100644 index 9f030474..00000000 --- a/languages/python/networking_twisted_parallel1.py +++ /dev/null @@ -1,21 +0,0 @@ -from twisted.internet import defer, task -from twisted.python import log -from twisted.internet import reactor -from twisted.web import client -from twisted.internet.utils import getProcessValue - -def parallel(iterable, count, callable, *args, **named): - print(args, named) - coop = task.Cooperator() - work = (callable(elem, *args, **named) for elem in iterable) - return defer.DeferredList([coop.coiterate(work) for i in range(count)]) - -def download(xxx_todo_changeme): - (url, fileName) = xxx_todo_changeme - return client.downloadPage(url, file(fileName, 'wb')) - -urls = [(url, str(n)) for (n, url) in enumerate(file('urls.txt'))] -finished = parallel(urls, 50, download) -finished.addErrback(log.err) -finished.addCallback(lambda ign: reactor.stop()) -reactor.run() diff --git a/languages/python/networking_twisted_parallel2.py b/languages/python/networking_twisted_parallel2.py deleted file mode 100644 index 2d964ca4..00000000 --- a/languages/python/networking_twisted_parallel2.py +++ /dev/null @@ -1,22 +0,0 @@ -#!/usr/bin/python2.6 - -from twisted.internet import defer, task -from twisted.python import log -from twisted.internet import reactor -from twisted.web import client -from twisted.internet.utils import getProcessValue - -executable = '/home/senthil/uthcode/python/sometask' - -def parallel(count=None): - coop = task.Cooperator() - work = (getProcessValue(executable) for i in range(10)) - if count: - return defer.DeferredList([coop.coiterate(work) for i in range(count)]) - else: - return coop.coiterate(work) - -finished = parallel() -finished.addErrback(log.err) -finished.addCallback(lambda ign: reactor.stop()) -reactor.run() diff --git a/languages/python/networking_udp1.py b/languages/python/networking_udp1.py deleted file mode 100644 index de1ccb5c..00000000 --- a/languages/python/networking_udp1.py +++ /dev/null @@ -1,20 +0,0 @@ -import socket -import sys - -# Create a TCP/IP socket -sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) - -# Bind the socket to the port -server_address = ('localhost', 10000) -print('starting up on %s port %s' % server_address, file=sys.stderr) -sock.bind(server_address) -while True: - print('\nwaiting to receive message', file=sys.stderr) - data, address = sock.recvfrom(4096) - - print('received %s bytes from %s' % (len(data), address), file=sys.stderr) - print(data, file=sys.stderr) - - if data: - sent = sock.sendto(data, address) - print('sent %s bytes back to %s' % (sent, address), file=sys.stderr) diff --git a/languages/python/networking_udp2.py b/languages/python/networking_udp2.py deleted file mode 100644 index 2ca5f5d8..00000000 --- a/languages/python/networking_udp2.py +++ /dev/null @@ -1,25 +0,0 @@ -import socket -import sys - -# Create a UDP socket -sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) -sock.bind(('',54557)) - -server_address = ('localhost', 10000) -message = 'This is the message. It will be repeated.' - -try: - - # Send data - print('sending "%s"' % message, file=sys.stderr) - sent = sock.sendto(message, server_address) - print(sock.getsockname()[1]) - - # Receive response - print('waiting to receive', file=sys.stderr) - data, server = sock.recvfrom(4096) - print('received "%s"' % data, file=sys.stderr) - -finally: - print('closing socket', file=sys.stderr) - sock.close() diff --git a/languages/python/networking_udp_time.py b/languages/python/networking_udp_time.py deleted file mode 100644 index 2d7f2a24..00000000 --- a/languages/python/networking_udp_time.py +++ /dev/null @@ -1,26 +0,0 @@ -from socket import * -from struct import unpack -from time import ctime, sleep -from sys import argv - -argv = argv[1:] -if len(argv) == 0: - argv = [ 'time-nw.nist.gov' ] - -s = socket(AF_INET, SOCK_DGRAM) -s.settimeout(5.0) - -for server in argv: - print(server, ":", end=' ') - try: - s.sendto('', 0, (server, 37)) - t = int(unpack('!L', s.recv(16)[:4])[0]) - # Convert from 1900/01/01 epoch to 1970/01/01 epoch - t -= 2208988800 - print(ctime(t)) - except timeout: - print("TIMEOUT") - except: - print("ERROR") - -s.close() diff --git a/languages/python/software_engineering_copy_files_unicode.py b/languages/python/software_engineering_copy_files_unicode.py deleted file mode 100644 index eebdf01b..00000000 --- a/languages/python/software_engineering_copy_files_unicode.py +++ /dev/null @@ -1,20 +0,0 @@ -#!/usr/bin/python -# -*- coding: utf-8 -*- -""" -The copyfiles function from source to destination, if the source and -destination was unicode filenames. Remember to declaring the encoding used by -the program if using Python2. -""" - - -import os -import shutil - -def copyfiles(from_dir, to_dir): - files_in_dir = str(from_dir) - files_to_dir = str(to_dir) - for root, dirs, files in files_in_dir: - for curr_file in files: - path_of_curr_file = os.path.join(root, curr_file) - shutil.copy(path_of_curr_file, files_to_dir) - diff --git a/languages/python/software_engineering_createtempfiles.py b/languages/python/software_engineering_createtempfiles.py deleted file mode 100755 index 0034fa1e..00000000 --- a/languages/python/software_engineering_createtempfiles.py +++ /dev/null @@ -1,30 +0,0 @@ -""" -This program creates temporary files with content in them. This serves as -useful utility if you want to fill a directory full of temporary files with -some content. The content is Zen of Python. - -Capturing output with module evaluation by tempeorary redirection of stdout is -shown here. Control the mkstemp call according to your requirements. - -""" -import tempfile -import random -import os -import sys - -num = random.randint(100,1000) - -fhandle = open('zen','w') -old_stdout, sys.stdout = sys.stdout, fhandle -import this -sys.stdout = old_stdout -fhandle.close() -zen = open('zen').read() -os.remove('zen') - -for i in range(num): - fname = tempfile.mkstemp(suffix='.gz',prefix=str(i), dir=os.path.abspath('in'), - text=True)[1] - fhandle = open(fname, 'w') - fhandle.write(zen) - fhandle.close() diff --git a/languages/python/software_engineering_datetime_counter.py b/languages/python/software_engineering_datetime_counter.py deleted file mode 100644 index 962ff0fa..00000000 --- a/languages/python/software_engineering_datetime_counter.py +++ /dev/null @@ -1,10 +0,0 @@ -import datetime - -def withtimestamp(): - format = "%Y-%m-%d-%H-%M-%S" - return datetime.datetime.now().strftime(format=format) - -if __name__ == "__main__": - print(withtimestamp()) - - diff --git a/languages/python/software_engineering_doctest_example.py b/languages/python/software_engineering_doctest_example.py deleted file mode 100644 index d1c6da4a..00000000 --- a/languages/python/software_engineering_doctest_example.py +++ /dev/null @@ -1,60 +0,0 @@ -""" -This is the "example" module. - -The example module supplies one function, factorial(). For example, - ->>> factorial(5) -120 -""" - -def factorial(n): - """Return the factorial of n, an exact integer >= 0. - - If the result is small enough to fit it an int, return an int. - Else return a long. - - >>> [factorial(n) for n in range(6)] - [1, 1, 2, 6, 24, 120] - >>> [factorial(long(n)) for n in range(6)] - [1, 1, 2, 6, 24, 120] - >>> factorial(30) - 265252859812191058636308480000000L - >>> factorial(30L) - 265252859812191058636308480000000L - >>> factorial(-1) - Traceback (most recent call last): - ... - ValueError: n must be >= 0 - - Factorials of floats are OK, but the float must be an exact integer: - >>> factorial(30.1) - Traceback (most recent call last): - ... - ValueError: n must be exact integer - >>> factorial(30.0) - 265252859812191058636308480000000L - - It must also not be ridiculously large: - >>> factorial(1e100) - Traceback (most recent call last): - ... - OverflowError: n too large - """ - - import math - if not n >= 0: - raise ValueError("n must be >= 0") - if math.floor(n) != n: - raise ValueError("n must be exact integer") - if n+1 == n: # catch a value like 1e300 - raise OverflowError("n too large") - result = 1 - factor = 2 - while factor <= n: - result *= factor - factor += 1 - return result - -if __name__ == '__main__': - import doctest - doctest.testmod() diff --git a/languages/python/software_engineering_encoding_unicode_xml_html.py b/languages/python/software_engineering_encoding_unicode_xml_html.py deleted file mode 100644 index ba61908b..00000000 --- a/languages/python/software_engineering_encoding_unicode_xml_html.py +++ /dev/null @@ -1,53 +0,0 @@ -# From Python Cookbook. Recipe 1.23 - Encoding Unicode Data for XML and HTML. - -# Problem: Want to encode Unicode text for output in HTML, or some other XML -# application, using a limited but popular encoding such as ASCII or latin-1 - -def encode_for_xml(unicode_data, encoding='ascii'): - return unicode_data.encode(encoding, 'xmlcharrefreplace') - -# If you prefer to use HTML's symbolic entity references instead. For this you -# need to define and register a customized encoding error handler. - -import codecs -from html.entities import codepoint2name - -def html_replace(exc): - if isinstance(exc, (UnicodeEncodeError, UnicodeTranslateError)): - s = [ '&%s;' % codepoint2name[ord(c)] for c in - exc.object[exc.start:exc.end]] - return ''.join(s),exc.end - else: - raise TypeError("can't handle %s" % exc.__name__) - -codecs.register_error('html_replace',html_replace) - - -def encode_for_html(unicode_data, encoding='ascii'): - return unicode_data.encode(encoding, 'html_replace') - - -if __name__ == '__main__': - # demo - data = '''\ - - - Encoding Test - - -

accented characters: -

    -
  • \xe0 (a + grave) -
  • \xe7 (c + cedilla) -
  • \xe9 (e + acute) -
-

symbols: -

  • \xa3 (British pound) -
  • \u20ac (Euro) -
  • \u221e (Infinity) - - - - ''' - #print encode_for_xml(data) - print(encode_for_html(data)) diff --git a/languages/python/software_engineering_exceptions_testing.py b/languages/python/software_engineering_exceptions_testing.py deleted file mode 100644 index cca656a3..00000000 --- a/languages/python/software_engineering_exceptions_testing.py +++ /dev/null @@ -1,12 +0,0 @@ -from urllib.error import URLError, HTTPError -from io import StringIO - -print(isinstance(URLError("foo"), HTTPError)) -print(isinstance(HTTPError("foo", "bar", "baz", "zap", StringIO()), URLError)) - -try: - raise HTTPError("foo", "bar", "baz", "zap", StringIO()) -except URLError: - print("caught this exception") -else: - print("this exception escaped.") \ No newline at end of file diff --git a/languages/python/software_engineering_fcntl_1.py b/languages/python/software_engineering_fcntl_1.py deleted file mode 100644 index 3cc68c2c..00000000 --- a/languages/python/software_engineering_fcntl_1.py +++ /dev/null @@ -1,21 +0,0 @@ -import fcntl -import time, os - -FILE = "counter.txt" - -if not os.path.exists(FILE): - # Create the counter file if it does not exist. - file = open(FILE,'w') - file.write('0') - file.close() - -for i in range(20): - # Increment the counter - file = open(FILE,"r+") - fcntl.flock(file.fileno(), fcntl.LOCK_EX) - counter = int(file.readline()) + 1 - file.seek(0) - file.write(str(counter)) - file.close() - print(os.getpid(), '=>' , counter) - time.sleep(0.1) diff --git a/languages/python/software_engineering_fctrl2.py b/languages/python/software_engineering_fctrl2.py deleted file mode 100644 index 535c4968..00000000 --- a/languages/python/software_engineering_fctrl2.py +++ /dev/null @@ -1,16 +0,0 @@ -memo = {} - -def fact(n): - if n in memo: - return memo[n] - if n == 0: - return 1 - else: - ans = n * fact(n-1) - memo[n] = ans - return ans - -t = int(input()) -for i in range(t): - n = int(input()) - print(fact(n)) diff --git a/languages/python/software_engineering_fortune_card.py b/languages/python/software_engineering_fortune_card.py deleted file mode 100644 index f372b62a..00000000 --- a/languages/python/software_engineering_fortune_card.py +++ /dev/null @@ -1,21 +0,0 @@ -import textwrap -import subprocess -from PIL import Image, ImageFont, ImageDraw -import glob, os -im = Image.new("CMYK",(800,400)) - -p = subprocess.Popen(['fortune','-s'], - stdout = subprocess.PIPE, - stderr = subprocess.PIPE) -proc_stdout, proc_stderr = p.communicate() -text = proc_stdout - -chosenfont = ImageFont.truetype('font.ttf',50) -draw = ImageDraw.Draw(im) -x , y = 10, 10 -words_in_text = textwrap.wrap(text, 40) -for word in words_in_text: - draw.text((x,y), word, font=chosenfont) -# x = x + 20 - y = y + 40 -im.save('fortune.jpg') diff --git a/languages/python/software_engineering_htmlformatter.py b/languages/python/software_engineering_htmlformatter.py deleted file mode 100644 index 3a7eb7f3..00000000 --- a/languages/python/software_engineering_htmlformatter.py +++ /dev/null @@ -1,99 +0,0 @@ -# written by Eric -# http://studiozero.proboards.com/index.cgi?board=opensrc&action=display&thread=10666 - -import sys - -if sys.version.startswith('3'): - from html.parser import HTMLParser -else: - from html.parser import HTMLParser - -class HTMLFormatter(HTMLParser): - """Formats HTML""" - - def __init__(self): - HTMLParser.__init__(self) - self.tabbed = 0 - self.formatted = [] - - def append(self, data): - self.formatted.append(str(data)) - - def _write_tabs(self): - self.append('\t'*self.tabbed) - - def _format_attrs(self, attrs): - fattrs = "" - for a,v in attrs: - fattrs = fattrs + " " + a + '="' + v.replace('"', '\\"') + '"' - return fattrs - - def _format_tag(self, tag, ttype='start', ats=None): - ftag = '<' - if ttype == 'end': - ftag = ftag + '/' - ftag = ftag + tag - if ats != None and len(ats): - ftag = ftag + self._format_attrs(ats) - if ttype == 'self': - ftag = ftag + ' /' - ftag = ftag + '>' - return ftag - - def handle_starttag(self, tag, attrs): - self._write_tabs() - self.tabbed = self.tabbed + 1 - self.append(self._format_tag(tag, ats=attrs) + '\n') - - def handle_endtag(self, tag): - self.tabbed = self.tabbed - 1 - self._write_tabs() - self.append(self._format_tag(tag, ttype='end') + '\n') - - def handle_startendtag(self, tag, attrs): - self._write_tabs() - self.append(self._format_tag(tag, ttype='self', ats=attrs) + '\n') - - def handle_data(self, data): - data = data.strip() - if(len(data)): - self._write_tabs() - self.append(data + '\n') - - def handle_charref(self, name): - self.append('&#'+name+';') - - def handle_entityref(self, name): - self.append('&'+name+';') - - def handle_comment(self, data): - data = '' - self._write_tabs(); - self.append(data + '\n') - - def handle_decl(self, decl): - self._write_tabs() - self.append('') - - def handle_pi(self, data): - self._write_tabs() - self.append('') - - def render(self): - return "".join(self.formatted) - -if __name__ == "__main__": - import sys - if len(sys.argv) == 3: - try: - n = HTMLFormatter() - f = open(sys.argv[1], 'r') - n.feed(f.read()) - f.close() - f = open(sys.argv[2], 'w') - f.write(n.render()) - f.close() - except IOError: - print(("Failed opening or writing to files '{0}', '{1}'".format(sys.argv[1], sys.argv[2]))) - else: - print("Wrong number of arguments") diff --git a/languages/python/software_engineering_htmlwriter.py b/languages/python/software_engineering_htmlwriter.py deleted file mode 100644 index 64d3b171..00000000 --- a/languages/python/software_engineering_htmlwriter.py +++ /dev/null @@ -1,97 +0,0 @@ -""" -This program is free software; you can redistribute it and/or modify it -under the terms of the GNU General Public License as published by the -Free Software Foundation; either version 2 of the License, or (at your -option) any later version. See . - -This program is distributed in the hope that it will be useful, but -WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License -for more details. -""" - -class TreeNode(list): - def __init__(self, tag, wrapper_node=None, **kwds): - super(TreeNode, self).__init__() - self._wrap = wrapper_node - self._tag = tag - self._attrs = kwds - - def _render_attrs(self): - if self._attrs: - return ' ' + ' '.join('%s="%s"' % attr for attr in self._attrs.items()) - else: - return '' - - def _render(self, depth=0): - depthStr = " " * (depth * 4) - result = [depthStr + '<%s%s>' % (self._tag, self._render_attrs())] - for content in self: - try: - content = content._render(depth=depth+1) - except AttributeError: - content = str(content) - if self._wrap: - result.append(self._wrap(content)._render(depth=depth+1)) - else: - result.append(content) - result.append(depthStr + '' % self._tag) - return '\n'.join(result) - - def __str__(self): - return self._render() - -class Document(TreeNode): - def __init__(self, title): - super(Document, self).__init__('body') - self._title = title - - def _render(self, depth=0): - html = TreeNode('html', lang='en') - head = TreeNode('head') - titleNode = TreeNode('title') - titleNode.append(self._title) - head.append(titleNode) - html.append(head) - body = super(Document, self)._render(depth+1) - html.append(body) - return html._render(depth=depth) - -def _create_tag(tag, wrapper_node=None, use_list=False): - def _tag(content=None, *args, **kwds): - t = TreeNode(tag=tag, wrapper_node=wrapper_node, *args, **kwds) - if content: - if use_list: - t.extend(content) - else: - t.append(content) - return t - return _tag - -Paragraph = _create_tag('p') -Heading = _create_tag('h1') -Subheading = _create_tag('h2') -Row = _create_tag('tr', wrapper_node=_create_tag('td'), use_list=True) -HeadingRow = _create_tag('tr', wrapper_node=_create_tag('th'), use_list=True) -Table = _create_tag('table') - - - -if __name__ == '__main__': - # A simple example that creates a basic HTML document - # and outputs it to file.html - - doc = Document("Hello World") - doc.append(Heading("This is a heading")) - doc.append(Subheading("This is a subheading")) - doc.append(Paragraph("This is a paragraph")) - t = Table(cellpadding="10", border="1") - t.append(HeadingRow(["Col1", "Col2", "Col3"])) - t.append(Row(["Column1", "Column2", "Column3"])) - doc.append(t) - print(doc) -## f=open('file.html', 'w') -## f.write(doc) -## f.close() - - diff --git a/languages/python/software_engineering_ideone_post.py b/languages/python/software_engineering_ideone_post.py deleted file mode 100644 index a7ae51c2..00000000 --- a/languages/python/software_engineering_ideone_post.py +++ /dev/null @@ -1,4 +0,0 @@ -import os -from ideone import Ideone -i = Ideone(os.getenv('IDEUSER'), os.getenv('IDEPASS')) -print(i.create_submission('print(42)', language_name='python',run=False)) diff --git a/languages/python/software_engineering_logging1.py b/languages/python/software_engineering_logging1.py deleted file mode 100644 index 593b3fb3..00000000 --- a/languages/python/software_engineering_logging1.py +++ /dev/null @@ -1,4 +0,0 @@ -import logging -FILENAME = 'logfile.txt' -logging.basicConfig(filename=FILENAME, level=logging.DEBUG, filemode='w') -logging.debug("This message will go into the logfile") diff --git a/languages/python/software_engineering_logging2.py b/languages/python/software_engineering_logging2.py deleted file mode 100644 index c7023900..00000000 --- a/languages/python/software_engineering_logging2.py +++ /dev/null @@ -1,21 +0,0 @@ -import glob -import logging -import logging.handlers - -mylogger = logging.getLogger("toolserver") -mylogger.setLevel(logging.DEBUG) - -FILENAME = "log2.txt" - -handler = logging.handlers.RotatingFileHandler(FILENAME, - maxBytes=20, - backupCount=5) -mylogger.addHandler(handler) - -for i in range(20): - mylogger.debug(i) - -files = glob.glob("%s.*" % FILENAME) - -for f in files: - print(f) diff --git a/languages/python/software_engineering_logging3.py b/languages/python/software_engineering_logging3.py deleted file mode 100644 index 5c93f218..00000000 --- a/languages/python/software_engineering_logging3.py +++ /dev/null @@ -1,20 +0,0 @@ -import logging -import sys - -LEVELS = {'debug': logging.DEBUG, - 'info': logging.INFO, - 'warning': logging.WARNING, - 'error': logging.ERROR, - 'critical': logging.CRITICAL - } - -if len(sys.argv) > 1: - log_level = sys.argv[1] - level = LEVELS.get(log_level, logging.NOTSET) - logging.basicConfig(level=level) - - logging.debug('This is a debug message') - logging.info('This is a info message') - logging.warning('This is a warning message.') - logging.error('This is a error message.') - logging.critical('This is a critical message.') diff --git a/languages/python/software_engineering_logging4.py b/languages/python/software_engineering_logging4.py deleted file mode 100644 index a18bdd3e..00000000 --- a/languages/python/software_engineering_logging4.py +++ /dev/null @@ -1,10 +0,0 @@ -import logging - -logger1 = logging.getLogger('package1.module1') -logger2 = logging.getLogger('package1.module2') - -logging.basicConfig(level=logging.WARNING) - -logger1.warning('This is a warning message') -logger2.warning('This is a another warning message') - diff --git a/languages/python/software_engineering_logging5.py b/languages/python/software_engineering_logging5.py deleted file mode 100644 index b77c2927..00000000 --- a/languages/python/software_engineering_logging5.py +++ /dev/null @@ -1,18 +0,0 @@ -import logging - -logger = logging.getLogger("simple_example") -logger.setLevel(logging.DEBUG) - -ch = logging.StreamHandler() -ch.setLevel(logging.DEBUG) - -formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s") -ch.setFormatter(formatter) - -logger.addHandler(ch) - -logger.debug("This is a debug message") -logger.info("This is a info message") -logger.warning("This is a warning message") -logger.error("This is a error message") -logger.critical("This is a critical message.") diff --git a/languages/python/software_engineering_multiprocessing_1.py b/languages/python/software_engineering_multiprocessing_1.py deleted file mode 100644 index cc8b0411..00000000 --- a/languages/python/software_engineering_multiprocessing_1.py +++ /dev/null @@ -1,13 +0,0 @@ -import multiprocessing -import subprocess - -def calculate(value): - return value * 10 - -if __name__ == '__main__': - pool = multiprocessing.Pool(None) - tasks = list(range(10000)) - results = [] - r = pool.map_async(calculate, tasks, callback=results.append) - r.wait() # Wait on the results - print(results) diff --git a/languages/python/software_engineering_os_exec1.py b/languages/python/software_engineering_os_exec1.py deleted file mode 100644 index f8b657e6..00000000 --- a/languages/python/software_engineering_os_exec1.py +++ /dev/null @@ -1,3 +0,0 @@ -import os -output = os.execl("/bin/date") -print(output) diff --git a/languages/python/software_engineering_provide_warnings.py b/languages/python/software_engineering_provide_warnings.py deleted file mode 100644 index 83f6d792..00000000 --- a/languages/python/software_engineering_provide_warnings.py +++ /dev/null @@ -1,16 +0,0 @@ -from functools import wraps -from warnings import warn - -def add_warning(func, oldname): - @wraps(func) - def _wrapped(*args, **kwds): - warn('Deprecated function %s being called' % oldname) - return func(*args, **kwds) - return _wrapped - -def test(a=2, b=4): - print(a + b) - -old_test = add_warning(test, 'old_test') - -old_test(123) diff --git a/languages/python/software_engineering_ptags.py b/languages/python/software_engineering_ptags.py deleted file mode 100644 index ac013560..00000000 --- a/languages/python/software_engineering_ptags.py +++ /dev/null @@ -1,53 +0,0 @@ -#! /usr/bin/env python - -# ptags -# -# Create a tags file for Python programs, usable with vi. -# Tagged are: -# - functions (even inside other defs or classes) -# - classes -# - filenames -# Warns about files it cannot open. -# No warnings about duplicate tags. - -import sys, re, os - -tags = [] # Modified global variable! - -def main(): - args = sys.argv[1:] - for filename in args: - treat_file(filename) - if tags: - fp = open('tags', 'w') - tags.sort() - for s in tags: fp.write(s) - - -expr = '^[ \t]*(def|class)[ \t]+([a-zA-Z0-9_]+)[ \t]*[:\(]' -matcher = re.compile(expr) - -def treat_file(filename): - try: - fp = open(filename, 'r') - except: - sys.stderr.write('Cannot open %s\n' % filename) - return - base = os.path.basename(filename) - if base[-3:] == '.py': - base = base[:-3] - s = base + '\t' + filename + '\t' + '1\n' - tags.append(s) - while 1: - line = fp.readline() - if not line: - break - m = matcher.match(line) - if m: - content = m.group(0) - name = m.group(2) - s = name + '\t' + filename + '\t/^' + content + '/\n' - tags.append(s) - -if __name__ == '__main__': - main() diff --git a/languages/python/software_engineering_run_under_strace.py b/languages/python/software_engineering_run_under_strace.py deleted file mode 100644 index bd2fefed..00000000 --- a/languages/python/software_engineering_run_under_strace.py +++ /dev/null @@ -1,2 +0,0 @@ -import subprocess -subprocess.Popen("ls") diff --git a/languages/python/software_engineering_runningtime.py b/languages/python/software_engineering_runningtime.py deleted file mode 100644 index e30621d2..00000000 --- a/languages/python/software_engineering_runningtime.py +++ /dev/null @@ -1,15 +0,0 @@ -""" -Book: The Essentials of Computer Architecture. -Chapter: 4 -Problem: Write a Computer Program that measures the difference in execution -times between the integer addition and integer division. Execute the operation -100,000 times and compare the difference in the running time. -""" -import timeit -t1 = timeit.Timer("4+2") -m1 = (100000 * t1.timeit(100000) / 100000) -print('Integer Addition takes: %f usecs/loop' % m1) -t2 = timeit.Timer("4/2") -m2 = (100000 * t2.timeit(100000) / 100000) -print('Integer Division takes: %f usecs/loop' % m2) -print('The difference is %s usecs' % (m2-m1)) diff --git a/languages/python/software_engineering_runningtime_intaddition.py b/languages/python/software_engineering_runningtime_intaddition.py deleted file mode 100644 index eaeefdcb..00000000 --- a/languages/python/software_engineering_runningtime_intaddition.py +++ /dev/null @@ -1,38 +0,0 @@ -""" -Book: The Essentials of Computer Architecture. -Chapter: 4 -Problem: Write a Computer Program that measures the difference in execution -times between the integer addition and integer division. Execute the operation -100,000 times and compare the difference in the running time. - -Extend the Program to compare between 16 bit, 32 bit and 64 bit integer -addition. - -Tip: Python 2.7 has bit_length() for int objects. - -Interesting Observation: - For 16 bit ints, the operations take more time than 32 bit numbers. - -""" -import timeit - -for bits in [16,32,64]: - num1 = pow(2,bits) - - # Integer Addition - - print('Integer Addition between %d bit numbers' % (bits)) - num2 = num1 + 2 - stmt = "%d +%d" % (num2, num1) - t = timeit.Timer(stmt) - m = (100000 * t.timeit(100000) / 100000) - print('%f usecs/loop' % (m)) - - # Integer Division now. - - print('Integer Division between %d bit numbers' % (bits)) - num2 = 2 * num1 - stmt = "%d/%d" % (num2, num1) - t = timeit.Timer(stmt) - m = (100000 * t.timeit(100000) / 100000) - print('%f usecs/loop' % (m)) diff --git a/languages/python/software_engineering_runningtime_intvsfloat.py b/languages/python/software_engineering_runningtime_intvsfloat.py deleted file mode 100644 index 9c7631e0..00000000 --- a/languages/python/software_engineering_runningtime_intvsfloat.py +++ /dev/null @@ -1,28 +0,0 @@ -""" -Book: The Essentials of Computer Architecture. -Chapter: 4 -Problem: Write a Computer Program that measures the difference in execution -times between the integer division and floating point division. Execute the operation -100,000 times and compare the difference in the running time. - -Interesting Observation: - * Integer Division is taking more time. - -""" - -import timeit -num1 = pow(2,64) -num2 = num1 * 2 -stmt = "%d/%d" % (num2,num1) -print('Test:', stmt) -t1 = timeit.Timer(stmt) -m1 = (100000 * t1.timeit(100000) / 100000) -print('Integer Division takes: %f usecs/loop' % m1) - -num2 = num1 * 2.0 -stmt = "%f/%f" % (num2, num1) -print('Test:', stmt) -t2 = timeit.Timer(stmt) -m2 = (100000 * t2.timeit(100000) / 100000) -print('Floating point Division takes: %f usecs/loop' % m2) -print('The difference is %s usecs' % (m2-m1)) diff --git a/languages/python/software_engineering_simple_subprocess.py b/languages/python/software_engineering_simple_subprocess.py deleted file mode 100644 index 0a21cab8..00000000 --- a/languages/python/software_engineering_simple_subprocess.py +++ /dev/null @@ -1,6 +0,0 @@ -import subprocess -proc = subprocess.Popen(['./simple'], stdout=subprocess.PIPE, - stderr=subprocess.PIPE) -out,err = proc.communicate() -print(out) -print(err) diff --git a/languages/python/software_engineering_simple_threading1.py b/languages/python/software_engineering_simple_threading1.py deleted file mode 100644 index 4f5b861d..00000000 --- a/languages/python/software_engineering_simple_threading1.py +++ /dev/null @@ -1,15 +0,0 @@ -import threading -import urllib.request, urllib.parse, urllib.error - -class MultiUrl(threading.Thread): - def __init__(self, url): - threading.Thread.__init__(self) - self.url = url - def run(self): - urllib.request.urlopen(self.url).read() - -background = MultiUrl('http://slashdot.org') -background.start() -print('main continues') -background.join() -print('main is done.') diff --git a/languages/python/software_engineering_sqlite3.py b/languages/python/software_engineering_sqlite3.py deleted file mode 100755 index f14534c5..00000000 --- a/languages/python/software_engineering_sqlite3.py +++ /dev/null @@ -1,132 +0,0 @@ -from collections import namedtuple -import sqlite3 - -# make a basic Link class -Link = namedtuple('Link', ['id', 'submitter_id', 'submitted_time', 'votes', - 'title', 'url']) - -# list of Links to work with -links = [ - Link(0, 60398, 1334014208.0, 109, - "C overtakes Java as the No. 1 programming language in the TIOBE index.", - "http://pixelstech.net/article/index.php?id=1333969280"), - Link(1, 60254, 1333962645.0, 891, - "This explains why technical books are all ridiculously thick and overpriced", - "http://prog21.dadgum.com/65.html"), - Link(23, 62945, 1333894106.0, 351, - "Learn Haskell Fast and Hard", - "http://yannesposito.com/Scratch/en/blog/Haskell-the-Hard-Way/"), - Link(2, 6084, 1333996166.0, 81, - "Announcing Yesod 1.0- a robust, developer friendly, high performance web framework for Haskell", - "http://www.yesodweb.com/blog/2012/04/announcing-yesod-1-0"), - Link(3, 30305, 1333968061.0, 270, - "TIL about the Lisp Curse", - "http://www.winestockwebdesign.com/Essays/Lisp_Curse.html"), - Link(4, 59008, 1334016506.0, 19, - "The Downfall of Imperative Programming. Functional Programming and the Multicore Revolution", - "http://fpcomplete.com/the-downfall-of-imperative-programming/"), - Link(5, 8712, 1333993676.0, 26, - "Open Source - Twitter Stock Market Game - ", - "http://www.twitstreet.com/"), - Link(6, 48626, 1333975127.0, 63, - "First look: Qt 5 makes JavaScript a first-class citizen for app development", - "http://arstechnica.com/business/news/2012/04/an-in-depth-look-at-qt-5-making-javascript-a-first-class-citizen-for-native-cross-platform-developme.ars"), - Link(7, 30172, 1334017294.0, 5, - "Benchmark of Dictionary Structures", "http://lh3lh3.users.sourceforge.net/udb.shtml"), - Link(8, 678, 1334014446.0, 7, - "If It's Not on Prod, It Doesn't Count: The Value of Frequent Releases", - "http://bits.shutterstock.com/?p=165"), - Link(9, 29168, 1334006443.0, 18, - "Language proposal: dave", - "http://davelang.github.com/"), - Link(17, 48626, 1334020271.0, 1, - "LispNYC and EmacsNYC meetup Tuesday Night: Large Scale Development with Elisp ", - "http://www.meetup.com/LispNYC/events/47373722/"), - Link(101, 62443, 1334018620.0, 4, - "research!rsc: Zip Files All The Way Down", - "http://research.swtch.com/zip"), - Link(12, 10262, 1334018169.0, 5, - "The Tyranny of the Diff", - "http://michaelfeathers.typepad.com/michael_feathers_blog/2012/04/the-tyranny-of-the-diff.html"), - Link(13, 20831, 1333996529.0, 14, - "Understanding NIO.2 File Channels in Java 7", - "http://java.dzone.com/articles/understanding-nio2-file"), - Link(15, 62443, 1333900877.0, 1244, - "Why vector icons don't work", - "http://www.pushing-pixels.org/2011/11/04/about-those-vector-icons.html"), - Link(14, 30650, 1334013659.0, 3, - "Python - Getting Data Into Graphite - Code Examples", - "http://coreygoldberg.blogspot.com/2012/04/python-getting-data-into-graphite-code.html"), - Link(16, 15330, 1333985877.0, 9, - "Mozilla: The Web as the Platform and The Kilimanjaro Event", - "https://groups.google.com/forum/?fromgroups#!topic/mozilla.dev.planning/Y9v46wFeejA"), - Link(18, 62443, 1333939389.0, 104, - "github is making me feel stupid(er)", - "http://www.serpentine.com/blog/2012/04/08/github-is-making-me-feel-stupider/"), - Link(19, 6937, 1333949857.0, 39, - "BitC Retrospective: The Issues with Type Classes", - "http://www.bitc-lang.org/pipermail/bitc-dev/2012-April/003315.html"), - Link(20, 51067, 1333974585.0, 14, - "Object Oriented C: Class-like Structures", - "http://cecilsunkure.blogspot.com/2012/04/object-oriented-c-class-like-structures.html"), - Link(10, 23944, 1333943632.0, 188, - "The LOVE game framework version 0.8.0 has been released - with GLSL shader support!", - "https://love2d.org/forums/viewtopic.php?f=3&t=8750"), - Link(22, 39191, 1334005674.0, 11, - "An open letter to language designers: Please kill your sacred cows. (megarant)", - "http://joshondesign.com/2012/03/09/open-letter-language-designers"), - Link(21, 3777, 1333996565.0, 2, - "Developers guide to Garage48 hackatron", - "http://martingryner.com/developers-guide-to-garage48-hackatron/"), - Link(24, 48626, 1333934004.0, 17, - "An R programmer looks at Julia", - "http://www.r-bloggers.com/an-r-programmer-looks-at-julia/")] - -# links is a list of Link objects. Links have a handful of properties. For -# example, a Link's number of votes can be accessed by link.votes if "link" is a -# Link. - -# make and populate a table -db = sqlite3.connect(':memory:') -db.execute('create table links ' + - '(id integer, submitter_id integer, submitted_time integer, ' + - 'votes integer, title text, url text)') -for l in links: - db.execute('insert into links values (?, ?, ?, ?, ?, ?)', l) - -# db is an in-memory sqlite database that can respond to sql queries using the -# execute() function. -# -# For example. If you run -# -# c = db.execute("select * from links") -# -# c will be a "cursor" to the results of that query. You can use the fetchmany() -# function on the cursor to convert that cursor into a list of results. These -# results won't be Links; they'll be tuples, but they can be passed turned into -# a Link. -# -# For example, to print all the votes for all of the links, do this: -# -# c = db.execute("select * from links") -# for link_tuple in c: -# link = Link(*link_tuple) -# print link.votes -# -# QUIZ - make the function query() return the number of votes the link with ID = 2 has -def query(): - c = db.execute("select * from links where id==2") - - link = Link(*c.fetchone()) - return link.votes - - -def query2(): - c = db.execute("select * from links where submitter_id = 62443 and votes > 1000") - link = Link(*c.fetchone()) - print(link.id) - for link_tuple in c: - link = Link(*link_tuple) - print(link.id) - -query2() diff --git a/languages/python/software_engineering_stringio.py b/languages/python/software_engineering_stringio.py deleted file mode 100644 index bd39f7e9..00000000 --- a/languages/python/software_engineering_stringio.py +++ /dev/null @@ -1,6 +0,0 @@ -import io -MSG = "That man is depriving a village somewhere of a computer Scientist." - -f = io.StringIO(MSG) -with f: - print((f.read())) diff --git a/languages/python/software_engineering_subprocess1.py b/languages/python/software_engineering_subprocess1.py deleted file mode 100644 index ea13864e..00000000 --- a/languages/python/software_engineering_subprocess1.py +++ /dev/null @@ -1,6 +0,0 @@ -import subprocess - -output_with_shell_true = subprocess.Popen("/bin/date;who;fortune",shell=True).wait() -print('True', output_with_shell_true) -output_with_shell_false = subprocess.Popen("/bin/date;who;fortune",shell=True).wait() -print('False', output_with_shell_false) diff --git a/languages/python/software_engineering_subprocess2.py b/languages/python/software_engineering_subprocess2.py deleted file mode 100644 index 2670a62a..00000000 --- a/languages/python/software_engineering_subprocess2.py +++ /dev/null @@ -1,13 +0,0 @@ -""" -Finding 'class' in every file python file in the directory. -'out' and 'err' are string objects containing the standard output and, -eventually, the error output. - -find -iname *.py|xargs grep class - -""" -from subprocess import Popen, PIPE -find_process = Popen(['find', '-iname', '*.py'], stdout=PIPE) -grep_process = Popen(['xargs', 'grep', 'class'], stdin=find_process.stdout, stdout=PIPE) -out, err = grep_process.communicate() -print(out) diff --git a/languages/python/software_engineering_subprocess3.py b/languages/python/software_engineering_subprocess3.py deleted file mode 100644 index 189604a6..00000000 --- a/languages/python/software_engineering_subprocess3.py +++ /dev/null @@ -1,6 +0,0 @@ -import subprocess -import os -ret_value= subprocess.Popen(['find','-name','*.py']).wait() -print(ret_value) -ret_value = os.system('find -name "*.py"') -print(ret_value) diff --git a/languages/python/software_engineering_subprocess4.py b/languages/python/software_engineering_subprocess4.py deleted file mode 100644 index d35694e0..00000000 --- a/languages/python/software_engineering_subprocess4.py +++ /dev/null @@ -1,5 +0,0 @@ -import subprocess -proc = subprocess.Popen(['date'],stdout=subprocess.PIPE,stderr=subprocess.PIPE) -out,err = proc.communicate() -print(out) -print(err) diff --git a/languages/python/software_engineering_subprocess5.py b/languages/python/software_engineering_subprocess5.py deleted file mode 100644 index 7f6659ef..00000000 --- a/languages/python/software_engineering_subprocess5.py +++ /dev/null @@ -1,14 +0,0 @@ -import subprocess -f = file('data.out','w') -ef = file('error.out','w') -cmd = '/home/senthil/uthcode/python/somebigout' -p = subprocess.Popen(cmd, shell=True, stdout=f, stderr=ef) -errcode = p.wait() -f.close() -ef.close() -if errcode: - with open('error.out') as ef: - pass - #errmess = p.stderr.read() -with open('data.out') as f: - pass diff --git a/languages/python/software_engineering_test_codec01.py b/languages/python/software_engineering_test_codec01.py deleted file mode 100644 index b97f234e..00000000 --- a/languages/python/software_engineering_test_codec01.py +++ /dev/null @@ -1,20 +0,0 @@ -if __name__ == '__main__': - # define our Unicode string - uni = "Hello\u001A\u0BC3\u1451\U0001D10CUnicode" - - # UTF-8 and UTF-16 can fully encode *any* unicode string - - print("UTF-8", repr(uni.encode('utf-8'))) - print("UTF-16", repr(uni.encode('utf-16'))) - - # ASCII can only work with code values from 0-127. Below we tell Python - - print("ASCII ", uni.encode('ascii','replace')) - - # ISO-8859-1 is similar to ASCII - - print("ISO-8859-1 ", uni.encode('iso-8859-1','replace')) - - uni = uni.encode('utf-8') - bstr = str(uni, 'utf-8') - print("Back from UTF-8:", repr(bstr)) diff --git a/languages/python/software_engineering_test_codec02.py b/languages/python/software_engineering_test_codec02.py deleted file mode 100644 index b7786442..00000000 --- a/languages/python/software_engineering_test_codec02.py +++ /dev/null @@ -1,7 +0,0 @@ -a = '\U0001ff00' - -print("Length: ", len(a)) - -print("Chars: ") -for c in a: - print(repr(c)) diff --git a/languages/python/software_engineering_test_codec03.py b/languages/python/software_engineering_test_codec03.py deleted file mode 100644 index 4675c5ad..00000000 --- a/languages/python/software_engineering_test_codec03.py +++ /dev/null @@ -1,10 +0,0 @@ -# {PI} {Sigma} {Omega} as ISO-8859-7 encoded string -b = '\xd0\xd3\xd9' - -# Convert to Unicode ('universal format') -u = str(b, 'iso-8859-7') -print(repr(u)) - -# and back to ISO-8859-7 -c = u.encode('iso-8859-7') -print(repr(c)) diff --git a/languages/python/software_engineering_test_dedent.py b/languages/python/software_engineering_test_dedent.py deleted file mode 100644 index b85050e8..00000000 --- a/languages/python/software_engineering_test_dedent.py +++ /dev/null @@ -1,12 +0,0 @@ -from textwrap import dedent - -def test(): - # end first line with \ to avoid the empty line! - s = '''\ - hello - world - ''' - print(s) - print(repr(s)) # prints ' hello\n world\n ' - print(repr(dedent(s))) # prints 'hello\n world\n' -test() diff --git a/languages/python/software_engineering_threading2.py b/languages/python/software_engineering_threading2.py deleted file mode 100644 index 6d8c6377..00000000 --- a/languages/python/software_engineering_threading2.py +++ /dev/null @@ -1,16 +0,0 @@ -import threading - -def appstart(): - print('Start your dev_appserver') - # Do operations - -def coveragestart(): - print('Start your coverage') - # Do operations - -t = threading.Thread(name='start', target=appstart) -w = threading.Thread(name='stop', target=coveragestart) -t.start() -w.start() -w.join() # Note that I am joing coveragestart first -t.join() diff --git a/languages/python/software_engineering_time_converter.py b/languages/python/software_engineering_time_converter.py deleted file mode 100644 index ff166b45..00000000 --- a/languages/python/software_engineering_time_converter.py +++ /dev/null @@ -1,3 +0,0 @@ -import time -print(time.time()) -print(time.strftime("%m/%d/%y/%H:%M",time.gmtime(time.time()))) diff --git a/languages/python/software_engineering_tkintertimer.py b/languages/python/software_engineering_tkintertimer.py deleted file mode 100644 index 1bdf854f..00000000 --- a/languages/python/software_engineering_tkintertimer.py +++ /dev/null @@ -1,25 +0,0 @@ -import tkinter -import time - -class App(): - def __init__(self,target): - self.root = tkinter.Tk() - self.label = tkinter.Label(text="") - self.label.pack() - self.update_clock() - self.root.mainloop() - - def update_clock(self): - now = time.strftime("%H:%M:%S") - self.label.configure(text=now) - self.root.after(1000, self.update_clock) - -HH = 23 -MM = 30 - -now = time.localtime(time.time()) -hour = 23 -minutes = 30 -target = time.mktime((year,mon,mday,hour,minutes,sec,wday,yday,isdst)) - -app=App(target) diff --git a/languages/python/software_engineering_twitter_phidget.py b/languages/python/software_engineering_twitter_phidget.py deleted file mode 100644 index cb1125bd..00000000 --- a/languages/python/software_engineering_twitter_phidget.py +++ /dev/null @@ -1,164 +0,0 @@ -#!/usr/bin/env python - -# Author: O.R.Senthil Kumaran -# Credits: Example Python Snipppet from the Phidget Library. -# Adapted from TextLCD-simple.py by 'Adam Stelmack'. - - -from ctypes import * -import sys -from time import sleep - -#Phidget specific imports -from Phidgets.Phidget import PhidgetID -from Phidgets.PhidgetException import PhidgetErrorCodes, PhidgetException -from Phidgets.Events.Events import AttachEventArgs, DetachEventArgs, ErrorEventArgs -from Phidgets.Devices.TextLCD import TextLCD, TextLCD_ScreenSize - -# for twitter - -import tweetstream -import json -import urllib.request, urllib.error, urllib.parse -import re - -USER= "username" -PASSWORD = "yourpassword" -SEARCHTERM = "royalwedding" - -stream = tweetstream.TweetStream(USER, PASSWORD) - -#Create an TextLCD object -try: - textLCD = TextLCD() -except RuntimeError as e: - print(("Runtime Exception: %s" % e.details)) - print("Exiting....") - exit(1) - -#Information Display Function -def DisplayDeviceInfo(): - try: - isAttached = textLCD.isAttached() - name = textLCD.getDeviceName() - serialNo = textLCD.getSerialNum() - version = textLCD.getDeviceVersion() - rowCount = textLCD.getRowCount() - columnCount = textLCD.getColumnCount() - except PhidgetException as e: - print(("Phidget Exception %i: %s" % (e.code, e.details))) - return 1 - print("|------------|----------------------------------|--------------|------------|") - print("|- Attached -|- Type -|- Serial No. -|- Version -|") - print("|------------|----------------------------------|--------------|------------|") - print(("|- %8s -|- %30s -|- %10d -|- %8d -|" % (isAttached, name, serialNo, version))) - print("|------------|----------------------------------|--------------|------------|") - print(("Number of Rows: %i -- Number of Columns: %i" % (rowCount, columnCount))) - -#Event Handler Callback Functions -def TextLCDAttached(e): - attached = e.device - print(("TextLCD %i Attached!" % (attached.getSerialNum()))) - -def TextLCDDetached(e): - detached = e.device - print(("TextLCD %i Detached!" % (detached.getSerialNum()))) - -def TextLCDError(e): - source = e.device - print(("TextLCD %i: Phidget Error %i: %s" % (source.getSerialNum(), e.eCode, e.description))) - -#Main Program Code -try: - textLCD.setOnAttachHandler(TextLCDAttached) - textLCD.setOnDetachHandler(TextLCDDetached) - textLCD.setOnErrorhandler(TextLCDError) -except PhidgetException as e: - print(("Phidget Exception %i: %s" % (e.code, e.details))) - print("Exiting....") - exit(1) - -print("Opening phidget object....") - -try: - textLCD.openPhidget() -except PhidgetException as e: - print(("Phidget Exception %i: %s" % (e.code, e.details))) - print("Exiting....") - exit(1) - -print("Waiting for attach....") - -try: - textLCD.waitForAttach(10000) -except PhidgetException as e: - print(("Phidget Exception %i: %s" % (e.code, e.details))) - try: - textLCD.closePhidget() - except PhidgetException as e: - print(("Phidget Exception %i: %s" % (e.code, e.details))) - print("Exiting....") - exit(1) - print("Exiting....") - exit(1) -else: - DisplayDeviceInfo() - -display_tweet = [] - -try: - if textLCD.getDeviceID()==PhidgetID.PHIDID_TEXTLCD_ADAPTER: - textLCD.setScreenIndex(0) - textLCD.setScreenSize(TextLCD_ScreenSize.PHIDGET_TEXTLCD_SCREEN_2x8) - - for tweet in stream: - if 'text' in tweet: - text = tweet['text'] - if type(text) == str: - if SEARCHTERM in text.lower(): - display_tweet.append(text) - if display_tweet: - item = display_tweet.pop() - - textLCD.setBacklight(True) - print(item) - row1 = item[:20] - row2 = item[20:40] - print("Writing to first row....") - textLCD.setDisplayString(0, row1) - print("Writing to second row....") - textLCD.setDisplayString(1, row2) - sleep(2) - - print("Turn on cursor....") - textLCD.setCursor(True) - sleep(2) - - print("Turn on cursor blink....") - textLCD.setCursor(False) - textLCD.setCursorBlink(True) - sleep(2) - - print("No Tweets") - textLCD.setBacklight(False) - textLCD.setCursorBlink(True) - textLCD.setDisplayString(0, "") - textLCD.setDisplayString(1, "") - if len(display_tweet) > 100: - break - -except PhidgetException as e: - print(("Phidget Exception %i: %s" % (e.code, e.details))) - print("Exiting....") - exit(1) - -textLCD.setDisplayString(0, "") -textLCD.setDisplayString(1, "") -textLCD.setBacklight(False) - -try: - textLCD.closePhidget() -except PhidgetException as e: - print(("Phidget Exception %i: %s" % (e.code, e.details))) - print("Exiting....") - exit(1) diff --git a/languages/python/software_engineering_xmlrpcclient.py b/languages/python/software_engineering_xmlrpcclient.py deleted file mode 100644 index 96eb298a..00000000 --- a/languages/python/software_engineering_xmlrpcclient.py +++ /dev/null @@ -1,21 +0,0 @@ -import xmlrpc.client -proxy = xmlrpc.client.ServerProxy('http://localhost:9000') - -# Call expliciting registered function - -print('dir():',proxy.dir('/')) -try: - print('list_contents():', proxy.list_contents('/')) -except: - print('You should use a registered name.') - -# Call the standard functions registered with server -print('BEFORE:', 'EXAMPLE' in proxy.dir.list('/tmp')) -print('CREATE:', proxy.dir.create('/tmp/EXAMPLE')) -print('SHOULD EXIST:', 'EXAMPLE' in proxy.dir.list('/tmp')) -print('REMOVE:', proxy.dir.remove('/tmp/EXAMPLE')) -print('AFTER', 'EXAMPLE' in proxy.dir.list('/tmp')) - - -# Call the function (handler) which has space -print(getattr(proxy,'my func')(5,5)) diff --git a/languages/python/software_engineering_xmlrpcserver.py b/languages/python/software_engineering_xmlrpcserver.py deleted file mode 100644 index dcf50ba5..00000000 --- a/languages/python/software_engineering_xmlrpcserver.py +++ /dev/null @@ -1,41 +0,0 @@ -from xmlrpc.server import SimpleXMLRPCServer -import logging -import os - -# Set up logging -logging.basicConfig(level=logging.DEBUG) - -server = SimpleXMLRPCServer(('localhost',9000),logRequests=True, - allow_none=True) - -# Expose a function - -def list_contents(dir_name): - logging.debug('list_contents(%s)', dir_name) - return os.listdir(dir_name) - -server.register_function(list_contents,'dir') - -# Register the Standard os functions - -server.register_function(os.listdir,'dir.list') -server.register_function(os.mkdir,'dir.create') -server.register_function(os.rmdir,'dir.remove') - - -# Expose a function - -def my_func(a, b): - return a * b - -# my func handler has space in between not -# a valid function name, but still it can be called. - -server.register_function(my_func,'my func') - -try: - print('Use Control-C to exit') - server.serve_forever() -except KeyboardInterrupt: - print('Exiting!') - diff --git a/languages/python/text_manipulation_argparse1.py b/languages/python/text_manipulation_argparse1.py deleted file mode 100755 index 8ba77094..00000000 --- a/languages/python/text_manipulation_argparse1.py +++ /dev/null @@ -1,15 +0,0 @@ -import argparse -import filecmp - -if __name__ == '__main__': - parser = argparse.ArgumentParser(description="Directory comparison") - parser.add_argument("--recurse", "-r", action="store_true", default=False) - parser.add_argument('dirs', nargs=2) - options = parser.parse_args() - - dd = filecmp.dircmp(options.dirs[0], options.dirs[1]) - - if options.recurse: - dd.report_full_closure() - else: - dd.report() diff --git a/languages/python/trie.py b/languages/python/trie.py deleted file mode 100644 index 797f8649..00000000 --- a/languages/python/trie.py +++ /dev/null @@ -1,59 +0,0 @@ -""" -Simple Trie Implementation -""" - -import json - -_end_marker = "*" - -def add_word(trie, word): - word_trie = trie - - for ch in word: - if ch in word_trie: - word_trie = word_trie[ch] - else: - word_trie[ch] = {} - word_trie = word_trie[ch] - - word_trie[_end_marker] = _end_marker - - return word_trie - -def make_trie(*words): - trie = dict() - - for word in words: - add_word(trie, word) - - return trie - -def is_word(trie, word): - word_trie = trie - for ch in word: - if ch in word_trie: - word_trie = word_trie[ch] - else: - return False - return _end_marker in word_trie - -def is_prefix(trie, word): - word_trie = trie - for ch in word: - if ch in word_trie: - word_trie = word_trie[ch] - else: - return False - - return True - -def print_trie(trie): - print(json.dumps(trie, sort_keys=True, indent=2)) - -trie = make_trie("hi", "hello", "help") - -print_trie(trie) - -print(is_word(trie, "hello")) -print(is_word(trie, "he")) -print(is_prefix(trie, "he")) \ No newline at end of file diff --git a/languages/python/web_cgi_ex.py b/languages/python/web_cgi_ex.py deleted file mode 100755 index 57900a89..00000000 --- a/languages/python/web_cgi_ex.py +++ /dev/null @@ -1,30 +0,0 @@ -#!/usr/local/bin/python -# $Id$ - -""" -An Example CGI Program in Python. - -Important modules are cgitb - cgitraceback for traceback details when something -fails. - -You will have to setup your environment properly for this to work. -""" - -import os -import time - -import cgitb -cgitb.enable() - -print("Content-Type: text/html") -print() - -print("") -print("

    Python CGI Example

    ") -filecontents = os.listdir(os.getcwd()) -print("

    You can use all Python functions:

    ") -print("

    Like this one shows you the directory contents

    ") -print(filecontents) -print("

    The current time is %s

    " % time.ctime()) -print("") - diff --git a/languages/python/web_cookielib_example.py b/languages/python/web_cookielib_example.py deleted file mode 100644 index 3401f92a..00000000 --- a/languages/python/web_cookielib_example.py +++ /dev/null @@ -1,16 +0,0 @@ -import http.cookiejar, urllib.request, urllib.error, urllib.parse - -cj = http.cookiejar.CookieJar() -opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj)) - -req = urllib.request.Request('https://www.idcourts.us/repository/start.do') -res = opener.open(req) -print(cj) -for c in cj: - cookie_str = "%s = %s" % (c.name, c.value) -print(cookie_str) - -req = urllib.request.Request('https://www.idcourts.us/repository/partySearch.do') -req.add_header("Cookie",cookie_str) -opener.open(req) -print(cj) diff --git a/languages/python/web_crawl.py b/languages/python/web_crawl.py deleted file mode 100644 index f3acacc6..00000000 --- a/languages/python/web_crawl.py +++ /dev/null @@ -1,123 +0,0 @@ -import urllib.request, urllib.error, urllib.parse -import urllib.request, urllib.parse, urllib.error -import urllib.parse -import sys -import re -import optparse - -try: - from BeautifulSoup import BeautifulSoup -except ImportError: - print("Pre-requsite not met - BeautifulSoup library") - sys.exit(-1) - -try: - import Image -except ImportError: - print("Pre-requisite not met - Python Imaging library") - sys.exit(-1) - -URL = 'http://www.indochino.com/' - -parsed_url = urllib.parse.urlparse(URL) # for default -global_url = [] -visited_url = [] - -def getimages(page): - images = [] - try: - soup = BeautifulSoup(urllib.request.urlopen(page)) - for image in soup.findAll("img"): - img = image["src"] - if img.split('.')[-1] in ('jpg','png','jpeg','gif'): - parsed_img = urllib.parse.urlparse(img) - if not parsed_img.scheme: - img = urllib.parse.urljoin(URL,parsed_img.path) - images.append(img) - except (IOError, KeyError, IndexError): - pass - return images - -def guess_product_page(page): - try: - soup = BeautifulSoup(urllib.request.urlopen(page)) - except (IOError,KeyError): - return False - american_currency = soup.findAll(text=re.compile('\$\d+(\.\d{2})?')) - other_indicators = soup.findAll(text=['discount','free', 'product details','shipping']) - if len(american_currency) > 2 or len(other_indicators) > 2: - return True - else: - return False - -def childrenfun(node): - if isinstance(node, list): - return iter(node) - else: - links = [] - try: - soup = BeautifulSoup(urllib.request.urlopen(node)) - for l in soup.findAll("a"): - l = l["href"] - parsed = urllib.parse.urlparse(l) - if (parsed.scheme and (parsed.scheme in ('http','https')) and (parsed.netloc in parsed_url.netloc)): - link = urllib.parse.urlunparse((parsed.scheme,parsed.netloc,parsed.path,'','','')) - if not link in global_url: - global_url.append(link) - links.append(link) - except (IOError, KeyError): - pass - return links - -def breadth_first(tree,children=childrenfun): - """Traverse the nodes of a tree in breadth-first order. - The first argument should be the tree root; children - should be a function taking as argument a tree node and - returning an iterator of the node's children. - """ - yield tree - last = tree - for node in breadth_first(tree,children): - for child in children(node): - yield child - last = child - if last == node: - return - -if __name__ == '__main__': - option_parser = optparse.OptionParser() - option_parser.add_option('-x','--height',dest='height',default=100,type="int") - option_parser.add_option('-y','--width', dest='width', default=100,type="int") - option_parser.add_option('-g',dest='guess',action='store_true',default=False) - - (options, args) = option_parser.parse_args() - - if len(args) == 0: - node = URL - else: - node = args[0] - try: - parsed_url = urllib.parse.urlparse(node) - except ValueError: - print('Invalid URL', node) - sys.exit(-1) - - for n in breadth_first(node): - if n not in visited_url: - visited_url.append(n) - print('URL %s' % n, end=' ') - if options.guess: - product_page = guess_product_page(n) - if product_page: - print('is a Product Page') - else: - print('is not a Product Page') - for img in getimages(n): - tmp_loc, hdrs = urllib.request.urlretrieve(img) - try: - im = Image.open(tmp_loc) - width, height = im.size - if width >= options.height and height >= options.width: - print('%d %d %s' % (width, height, img)) - except Exception as exc: - print('Did not check size: %s' % img) diff --git a/languages/python/web_crawl2.py b/languages/python/web_crawl2.py deleted file mode 100644 index 4a59a15b..00000000 --- a/languages/python/web_crawl2.py +++ /dev/null @@ -1,23 +0,0 @@ -# -*- coding: utf8 -*- -import io as StringIO - -from twisted.internet import reactor -from twisted.web.client import getPage -from twisted.python.util import println -from lxml import etree - -def parseHtml(html): - parser = etree.HTMLParser(encoding='utf8') - tree = etree.parse(StringIO.StringIO(html), parser) - return tree - -def extractTitle(tree): - titleText = str(tree.xpath("//title/text()")[0]) - return titleText - -d = getPage('http://www.google.com') -d.addCallback(parseHtml) -d.addCallback(extractTitle) -d.addBoth(println) - -reactor.run() diff --git a/languages/python/web_http_auth_header_code.py b/languages/python/web_http_auth_header_code.py deleted file mode 100644 index 67d350bd..00000000 --- a/languages/python/web_http_auth_header_code.py +++ /dev/null @@ -1,19 +0,0 @@ -import urllib.request, urllib.error, urllib.parse - -if __name__ == '__main__': - theurl = "http://mail.google.com/mail/#inbox" - req = urllib.request.Request(theurl) - try: - handle = urllib.request.urlopen(req) - print('here') - except IOError as e: - if hasattr(e, 'code'): - if e.code != 401: - print('Its some other error!') - print(e.code) - else: - print(e.headers) - print(e.headers['www-authenticate']) - - print(handle.read()) - diff --git a/languages/python/web_httplib_example_1.py b/languages/python/web_httplib_example_1.py deleted file mode 100644 index abe86587..00000000 --- a/languages/python/web_httplib_example_1.py +++ /dev/null @@ -1,42 +0,0 @@ -import http.client - -USER_AGENT = "httplib-example-1.py" - -class Error: - # Indicates an HTTP Error - def __init__(self, url, errcode, errmsg, headers): - self.url = url - self.errcode = errcode - self.headers = headers - - def __repr__(self): - return ( - "" % - (self.url, self.errcode, self.errmsg) - ) - -class Server: - def __init__(self, host): - self.host = host - def fetch(self, path): - http = http.client.HTTP(self.host) - - # Write header - http.putheader("GET",path) - http.putheader("User-Agent", USER_AGENT) - http.putheader("Host", self.host) - http.putheader("Accept", "*/*") - http.endheaders() - - # get response - errcode, errmsg, headers = http.getreply() - - if errcode != 200: - raise Error(errcode, errmsg, headers) - - f = http.getfile() - return f.read() - -if __name__ == '__main__': - server = Server("www.pythonware.com") - print(server.fetch("/index.htm")) diff --git a/languages/python/web_httplib_example_2.py b/languages/python/web_httplib_example_2.py deleted file mode 100644 index 29014680..00000000 --- a/languages/python/web_httplib_example_2.py +++ /dev/null @@ -1,9 +0,0 @@ -import http.client -import pudb -pudb.set_trace() -conn = http.client.HTTPConnection("www.python.org") -conn.request("GET","/index.html") -res = conn.getresponse() -print(res.getheaders()) -print(res.getheader('server')) -print(res.getheader('space','mine')) diff --git a/languages/python/web_httplib_example_3.py b/languages/python/web_httplib_example_3.py deleted file mode 100644 index 03712b02..00000000 --- a/languages/python/web_httplib_example_3.py +++ /dev/null @@ -1,7 +0,0 @@ -import http.client -conn = http.client.HTTPConnection("www.python.org") -conn.request("GET","/index.html") -res = conn.getresponse() -print((res.getheaders())) -print((res.getheader('server'))) -print((res.getheader('space','mine'))) diff --git a/languages/python/web_httplib_head.py b/languages/python/web_httplib_head.py deleted file mode 100644 index 569d8e5f..00000000 --- a/languages/python/web_httplib_head.py +++ /dev/null @@ -1,6 +0,0 @@ -import http.client -conn = http.client.HTTPConnection("www.google.com") -conn.request("HEAD","/index.html") -res = conn.getresponse() -for header,value in res.getheaders(): - print(header, value) diff --git a/languages/python/web_scan_web.py b/languages/python/web_scan_web.py deleted file mode 100644 index b20d457f..00000000 --- a/languages/python/web_scan_web.py +++ /dev/null @@ -1,13 +0,0 @@ -import re -import urllib.request, urllib.parse, urllib.error - -regex = re.compile(r'href="([^"]+)"') - -def matcher(url, max=10): - """Print the first several URL references in the given URL""" - data = urllib.request.urlopen(url).read() - hits = regex.findall(data) - for hit in hits[:max]: - print(urllib.basejoin(url,hit)) - -matcher("http://uthcode.sarovar.org") diff --git a/languages/python/web_server.py b/languages/python/web_server.py deleted file mode 100644 index c587fd34..00000000 --- a/languages/python/web_server.py +++ /dev/null @@ -1,17 +0,0 @@ -import socket -import sys - -def main(): - ls = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - port = int(sys.argv[1]) - ls.bind(('',port)) - ls.listen(1) - (conn, addr) = ls.accept() - while 1: - l = input() - conn.send(1) - - -if __name__ == '__main__': - main() - diff --git a/languages/python/web_simple_http_processor.py b/languages/python/web_simple_http_processor.py deleted file mode 100644 index f0450426..00000000 --- a/languages/python/web_simple_http_processor.py +++ /dev/null @@ -1,56 +0,0 @@ -import sys -import urllib.request, urllib.error, urllib.parse -import http.cookiejar - -class HTTPMyDebugProcessor(urllib2.AbstractHTTPHandler): - """Track HTTP Requests and responses with this custom handlers. Be sure to - add it your build_opener call, or use: handler_order = 900 """ - def __init__(self, httpout = sys.stdout): - self.httpout = httpout - def http_request(self, request): - if __debug__: - host, full_url = request.get_host(), request.get_full_url() - url_path = full_url[full_url.find(host) + len(host):] - self.httpout.write("%s\n" % request.get_full_url()) - self.httpout.write("\n") - self.httpout.write("%s %s\n" % (request.get_method(), url_path)) - - for header in request.header_items(): - self.httpout.write("%s: %s\n" % header[:]) - - self.httpout.write("\n") - - return request - - def http_response(self, request, response): - if __debug__: - code, msg, hdrs = response.code, response.msg, response.info() - self.httpout.write("HTTP/1.x %s %s\n" % (code, msg)) - self.httpout.write(str(hdrs)) - - return response - - https_request = http_request - https_response = http_response - -# Example -cjar = http.cookiejar.LWPCookieJar() -opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cjar),HTTPMyDebugProcessor(),) -#opener = urllib2.build_opener(HTTPMyDebugProcessor(),) -urllib.request.install_opener(opener) -##response = urllib2.urlopen("http://www.google.com") -#response = urllib2.urlopen("https://www.idcourts.us/repository/start.do") -#response = urllib2.urlopen("https://www.idcourts.us/repository/searchParty.do") -req = urllib.request.Request('http://www.microsoft.com/windows/windows-7/default.aspx') -#req = urllib2.Request('https://www.idcourts.us/repository/start.do') -res = opener.open(req) - -print(cjar) -for c in cjar: - cookie_str = "%s=%s" % (c.name, c.value) -print(cookie_str) - -req = urllib.request.Request('http://www.microsoft.com/windows/windows-xp/default.aspx') -#req.add_header("Cookie",cookie_str) -opener.open(req) -print(cjar) diff --git a/languages/python/web_urllib1.py b/languages/python/web_urllib1.py deleted file mode 100644 index b39e9c1b..00000000 --- a/languages/python/web_urllib1.py +++ /dev/null @@ -1,2 +0,0 @@ -import urllib.request, urllib.parse, urllib.error -urllib.request.urlopen('http://www.google.com') diff --git a/languages/python/web_urllib2_1.py b/languages/python/web_urllib2_1.py deleted file mode 100644 index 472e1a7b..00000000 --- a/languages/python/web_urllib2_1.py +++ /dev/null @@ -1,4 +0,0 @@ -import urllib.request, urllib.error, urllib.parse -o = urllib.request.urlopen('http://www.google.com') -print(o) -print(type(o)) diff --git a/languages/python/web_urllib2_add_data.py b/languages/python/web_urllib2_add_data.py deleted file mode 100644 index d0433a24..00000000 --- a/languages/python/web_urllib2_add_data.py +++ /dev/null @@ -1,14 +0,0 @@ -import urllib.request, urllib.error, urllib.parse - -URL = 'http://localhost/allowed.html' - -ah = urllib.request.HTTPDigestAuthHandler() -ah.add_password('Realm','http://localhost/','senthil','kumaran') -urllib.request.install_opener(urllib.request.build_opener(ah)) -r = urllib.request.Request(URL) -r.add_data("1") -obj = urllib.request.urlopen(r) -print(obj.read()) -r.add_data("10") -obj = urllib.request.urlopen(r) -print(obj.read()) diff --git a/languages/python/web_urllib2_auth_ex1.py b/languages/python/web_urllib2_auth_ex1.py deleted file mode 100644 index 017d3267..00000000 --- a/languages/python/web_urllib2_auth_ex1.py +++ /dev/null @@ -1,6 +0,0 @@ -import urllib.request, urllib.error, urllib.parse -authinfo = urllib.request.HTTPBasicAuthHandler() -opener = urllib.request.build_opener(authinfo) -urllib.request.install_opener(opener) -f = urllib.request.urlopen('http://mail.google.com/a/spasticssocietyofkarnataka.org/#inbox') -print(f.info()) diff --git a/languages/python/web_urllib2_basic1.py b/languages/python/web_urllib2_basic1.py deleted file mode 100644 index 65f25b1d..00000000 --- a/languages/python/web_urllib2_basic1.py +++ /dev/null @@ -1,11 +0,0 @@ -import urllib.request, urllib.error, urllib.parse - -URL = 'http://localhost/basic.html' -passwd = '550charpass50charpass50charpass50charpass50charpass0charpass' -#passwd = 'senthil' -ah = urllib.request.HTTPBasicAuthHandler() -ah.add_password('Realm','http://localhost/basic.html','senthil',passwd) -urllib.request.install_opener(urllib.request.build_opener(ah)) -r = urllib.request.Request(URL) -obj = urllib.request.urlopen(r) -print(obj.read()) diff --git a/languages/python/web_urllib2_basic2.py b/languages/python/web_urllib2_basic2.py deleted file mode 100644 index 5e9746fc..00000000 --- a/languages/python/web_urllib2_basic2.py +++ /dev/null @@ -1,79 +0,0 @@ -import urllib.request, urllib.error, urllib.parse - -URL = 'http://localhost/basic.html' - -ah = urllib.request.HTTPBasicAuthHandler() -ah.add_password('Realm','http://localhost/','username','veryverylongpassword') -urllib.request.install_opener(urllib.request.build_opener(ah)) -r = urllib.request.Request(URL) -obj = urllib.request.urlopen(r) -print(obj.read()) - -print('*********************************************************') -import urllib.request, urllib.error, urllib.parse -import sys -import re -import base64 -from urllib.parse import urlparse - -theurl = 'http://localhost/basic.html' -# if you want to run this example you'll need to supply -# a protected page with your username and password - -username = 'username' -password = 'veryverylongpassword' # a very bad password - -req = urllib.request.Request(theurl) -try: - handle = urllib.request.urlopen(req) -except IOError as e: - # here we *want* to fail - pass -else: - # If we don't fail then the page isn't protected - print("This page isn't protected by authentication.") - sys.exit(1) - -if not hasattr(e, 'code') or e.code != 401: - # we got an error - but not a 401 error - print("This page isn't protected by authentication.") - print('But we failed for another reason.') - sys.exit(1) - -authline = e.headers['www-authenticate'] -# this gets the www-authenticate line from the headers -# which has the authentication scheme and realm in it - - -authobj = re.compile( - r'''(?:\s*www-authenticate\s*:)?\s*(\w*)\s+realm=['"]([^'"]+)['"]''', - re.IGNORECASE) -# this regular expression is used to extract scheme and realm -matchobj = authobj.match(authline) - -if not matchobj: - # if the authline isn't matched by the regular expression - # then something is wrong - print('The authentication header is badly formed.') - print(authline) - sys.exit(1) - -scheme = matchobj.group(1) -realm = matchobj.group(2) -# here we've extracted the scheme -# and the realm from the header -if scheme.lower() != 'basic': - print('This example only works with BASIC authentication.') - sys.exit(1) - -base64string = base64.encodestring( - '%s:%s' % (username, password))[:-1] -authheader = "Basic %s" % base64string -req.add_header("Authorization", authheader) -try: - handle = urllib.request.urlopen(req) -except IOError as e: - # here we shouldn't fail if the username/password is right - print("It looks like the username or password is wrong.") - sys.exit(1) -thepage = handle.read() diff --git a/languages/python/web_urllib2_basic3.py b/languages/python/web_urllib2_basic3.py deleted file mode 100644 index b2bcde89..00000000 --- a/languages/python/web_urllib2_basic3.py +++ /dev/null @@ -1,14 +0,0 @@ -import urllib.request, urllib.error, urllib.parse -import base64 - -URL = 'http://localhost/basic.html' -passwd = '550charpass50charpass50charpass50charpass50charpass0charpass' -#passwd = 'senthil' -request = urllib.request.Request(URL) -#base64.MAXBINSIZE=1000000 -base64string = base64.b64encode('%s:%s' %('senthil',passwd))[:-1] -#base64string = base64.encodestring('%s:%s' %('senthil',passwd))[:-1] -request.add_header('WWW-Authenticate', 'Basic realm=Realm') -request.add_header("Authorization","Basic %s" % base64string) -obj = urllib.request.urlopen(request) -print(obj.read()) diff --git a/languages/python/web_urllib2_basic_digest1.py b/languages/python/web_urllib2_basic_digest1.py deleted file mode 100644 index 9f5b8842..00000000 --- a/languages/python/web_urllib2_basic_digest1.py +++ /dev/null @@ -1,16 +0,0 @@ -import urllib.request, urllib.error, urllib.parse - -basic_handler = urllib.request.HTTPBasicAuthHandler() -basic_handler.add_password('Realm','http://localhost/','senthil','senthil') - -digest_handler = urllib.request.HTTPDigestAuthHandler() -digest_handler.add_password('Realm','http://localhost/','senthil','kumaran') -opener = urllib.request.build_opener(basic_handler, digest_handler) -opener = urllib.request.build_opener(digest_handler, basic_handler) -urllib.request.install_opener(opener) - -basic_url = r'http://localhost/basic.html' -digest_url = r'http://localhost/allowed.html' - -print(urllib.request.urlopen(digest_url).read()) -print(urllib.request.urlopen(basic_url).read()) diff --git a/languages/python/web_urllib2_binary_upload.py b/languages/python/web_urllib2_binary_upload.py deleted file mode 100644 index 10bb3fc2..00000000 --- a/languages/python/web_urllib2_binary_upload.py +++ /dev/null @@ -1,93 +0,0 @@ -import itertools -import mimetools -import mimetypes -from io import StringIO -import urllib.request, urllib.parse, urllib.error -import urllib.request, urllib.error, urllib.parse - -class MultiPartForm(object): - """Accumulate the data to be used when posting a form.""" - - def __init__(self): - self.form_fields = [] - self.files = [] - self.boundary = mimetools.choose_boundary() - return - - def get_content_type(self): - return 'multipart/form-data; boundary=%s' % self.boundary - - def add_field(self, name, value): - """Add a simple field to the form data.""" - self.form_fields.append((name, value)) - return - - def add_file(self, fieldname, filename, fileHandle, mimetype=None): - """Add a file to be uploaded.""" - body = fileHandle.read() - if mimetype is None: - mimetype = mimetypes.guess_type(filename)[0] or 'application/octet-stream' - self.files.append((fieldname, filename, mimetype, body)) - return - def __str__(self): - """Return a string representing the form data, including attached files.""" - # Build a list of lists, each containing "lines" of the - # request. Each part is separated by a boundary string. - # Once the list is built, return a string where each - # line is separated by '\r\n'. - parts = [] - part_boundary = '--' + self.boundary - - # Add the form fields - parts.extend( - [ part_boundary, - 'Content-Disposition: form-data; name="%s"' % name, - '', - value, - ] - for name, value in self.form_fields - ) - # Add the files to upload - parts.extend( - [ part_boundary, - 'Content-Disposition: file; name="%s"; filename="%s"' % \ - (field_name, filename), - 'Content-Type: %s' % content_type, - '', - body, - ] - for field_name, filename, content_type, body in self.files - ) - - # Flatten the list and add closing boundary marker, - # then return CR+LF separated data - flattened = list(itertools.chain(*parts)) - flattened.append('--' + self.boundary + '--') - flattened.append('') - return '\r\n'.join(flattened) - -if __name__ == '__main__': - # Create the form with simple fields - form = MultiPartForm() - form.add_field('firstname', 'Doug') - form.add_field('lastname', 'Hellmann') - - # Add a fake file - form.add_file('biography', 'bio.txt', - fileHandle=StringIO('Python developer and blogger.')) - - # Build the request - request = urllib.request.Request('http://localhost:8080/') - request.add_header('User-agent', 'PyMOTW (http://www.doughellmann.com/PyMOTW/)') - body = str(form) - request.add_header('Content-type', form.get_content_type()) - request.add_header('Content-length', len(body)) - request.add_data(body) - - print() - print('OUTGOING DATA:') - print(request.get_data()) - - print() - print('SERVER RESPONSE:') - print(urllib.request.urlopen(request).read()) diff --git a/languages/python/web_urllib2_debug_headers.py b/languages/python/web_urllib2_debug_headers.py deleted file mode 100644 index dce7f293..00000000 --- a/languages/python/web_urllib2_debug_headers.py +++ /dev/null @@ -1,28 +0,0 @@ -import http.cookiejar -import urllib.request, urllib.error, urllib.parse - -cookiejar = http.cookiejar.LWPCookieJar() -http_handler = urllib.request.HTTPHandler(debuglevel=1) -opener = urllib.request.build_opener(http_handler,urllib.request.HTTPCookieProcessor(cookiejar)) -urllib.request.install_opener(opener) -#url = 'https://www.orange.sk/' -url = 'https://www.idcourts.us/repository/start.do' -req = urllib.request.Request(url, None) -cookie = cookiejar[0] -print(cookie.value) -""" -s = opener.open(req) -print cookiejar -url = 'https://www.idcourts.us/repository/partySearch.do' -req = urllib2.Request(url, None) -s = opener.open(req) -print cookiejar -url = 'https://www.idcourts.us/repository/start.do' -req = urllib2.Request(url, None) -s = opener.open(req) -print cookiejar -url = 'https://www.idcourts.us/repository/partySearch.do' -req = urllib2.Request(url, None) -s = opener.open(req) -print cookiejar -""" diff --git a/languages/python/web_urllib2_digest.py b/languages/python/web_urllib2_digest.py deleted file mode 100644 index 7315a71c..00000000 --- a/languages/python/web_urllib2_digest.py +++ /dev/null @@ -1,10 +0,0 @@ -import urllib.request, urllib.error, urllib.parse - -URL = 'http://localhost/allowed.html' - -ah = urllib.request.HTTPDigestAuthHandler() -ah.add_password('Realm','http://localhost/','senthil','kumaran') -urllib.request.install_opener(urllib.request.build_opener(ah)) -r = urllib.request.Request(URL) -obj = urllib.request.urlopen(r) -print(obj.read()) diff --git a/languages/python/web_urllib2_digest2.py b/languages/python/web_urllib2_digest2.py deleted file mode 100644 index 696f696f..00000000 --- a/languages/python/web_urllib2_digest2.py +++ /dev/null @@ -1,12 +0,0 @@ -import urllib.request, urllib.error, urllib.parse -import getpass - -URL = 'http://livejournal.com/users/phoe6/data/rss?auth=digest' - -ah = urllib.request.HTTPDigestAuthHandler() -password = getpass.getpass() -ah.add_password('lj','http://phoe6.livejournal.com/','phoe6',password) -urllib.request.install_opener(urllib.request.build_opener(ah)) -r = urllib.request.Request(URL) -obj = urllib.request.urlopen(r) -print(obj.read()) diff --git a/languages/python/web_urllib2_headers_ex1.py b/languages/python/web_urllib2_headers_ex1.py deleted file mode 100644 index 4e161771..00000000 --- a/languages/python/web_urllib2_headers_ex1.py +++ /dev/null @@ -1,16 +0,0 @@ -import urllib.request, urllib.error, urllib.parse -import urllib.request, urllib.parse, urllib.error - -url = 'http://www.someserver.com/cgi-bin/register.cgi' -user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)' -values = {'name':'Micheal Frood', - 'location':'Northampton', - 'language':'Python' - } -headers = {'User-Agent':user_agent} - -data = urllib.parse.urlencode(values) -req = urllib.request.Request(url, data, headers) -response = urllib.request.urlopen(req) -the_page = response.read() -print(the_page) diff --git a/languages/python/web_urllib2_proxy_auth.py b/languages/python/web_urllib2_proxy_auth.py deleted file mode 100644 index 019af450..00000000 --- a/languages/python/web_urllib2_proxy_auth.py +++ /dev/null @@ -1,11 +0,0 @@ -import urllib.request, urllib.error, urllib.parse - -proxy = urllib.request.ProxyHandler({'http': 'http:// username:password@proxyurl:proxyport', - 'https': 'https://username:password@proxyurl:proxyport'} - ) -auth = urllib.request.HTTPBasicAuthHandler() -opener = urllib.request.build_opener(proxy, auth, urllib.request.HTTPHandler) -urllib.request.install_opener(opener) - -conn = urllib.request.urlopen('http://python.org') -return_str = conn.read() diff --git a/languages/python/web_urllib2_test.py b/languages/python/web_urllib2_test.py deleted file mode 100644 index 97a9aad0..00000000 --- a/languages/python/web_urllib2_test.py +++ /dev/null @@ -1,25 +0,0 @@ -import urllib.request, urllib.error, urllib.parse - - -class FixedPasswordMgr: - def __init__(self, user, password): - self.user = user - self.password = password - - def add_password(self, realm, uri, user, passwd): - pass - - def find_user_password(self, realm, authuri): - print('auth: ' + authuri + ' ' + self.user) - return self.user, self.password - - -authhandler = urllib.request.HTTPDigestAuthHandler(FixedPasswordMgr('phoe6', 'xxxxx')) - -opener = urllib.request.build_opener(authhandler) -urllib.request.install_opener(opener) - -for user in ['shortcipher', 'numberland', 'adrian2084', 'rocketjon', 'si1entdave', 'nightshade37']: - url = 'http://' + user + '.livejournal.com/data/atom?auth=digest' - pagehandle = urllib.request.urlopen(url) - print('ok ' + user) diff --git a/pyproject.toml b/pyproject.toml deleted file mode 100644 index 9fb20b32..00000000 --- a/pyproject.toml +++ /dev/null @@ -1,14 +0,0 @@ -[tool.poetry] -name = "learntosolveit" -version = "0.1.0" -description = "" -authors = ["Senthil Kumaran "] -readme = "README.md" - -[tool.poetry.dependencies] -python = "^3.9" - - -[build-system] -requires = ["poetry-core"] -build-backend = "poetry.core.masonry.api" diff --git a/requirements.txt b/requirements.txt index 32c9a15e..af80e1a8 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,7 +1,4 @@ sphinx -pydata-sphinx-theme -sphinx_bootstrap_theme +sphinx-wagtail-theme sphinx-autobuild breathe -piccolo_theme -sphinx-pdj-theme diff --git a/source/Ads.txt b/source/Ads.txt new file mode 100644 index 00000000..fc885ab1 --- /dev/null +++ b/source/Ads.txt @@ -0,0 +1 @@ +google.com, pub-8197049942123554, DIRECT, f08c47fec0942fa0 \ No newline at end of file diff --git a/source/_static/uthcode-logo-transparent.png b/source/_static/uthcode-logo-transparent.png new file mode 100644 index 00000000..9e3c6402 Binary files /dev/null and b/source/_static/uthcode-logo-transparent.png differ diff --git a/source/_templates/layout.html b/source/_templates/layout.html index 5af62434..774730ce 100644 --- a/source/_templates/layout.html +++ b/source/_templates/layout.html @@ -1,4 +1,10 @@ {% extends "!layout.html" %} + +{% block extrahead %} + +{% endblock %} + {% block content %} {{ super() }} @@ -24,5 +30,7 @@ + + {%- endblock %} diff --git a/source/conf.py b/source/conf.py index 4b55408f..a7f2d269 100644 --- a/source/conf.py +++ b/source/conf.py @@ -11,49 +11,8 @@ # All configuration values have a default; values that are commented out # serve to show the default. -import sys -import os from datetime import date -# At the top. -import sphinx_bootstrap_theme - -# ... - -# Activate the theme. - -import sphinx_pdj_theme -html_theme = 'sphinx_pdj_theme' -html_theme_path = [sphinx_pdj_theme.get_html_theme_path()] - - -#html_theme = 'piccolo_theme' -#html_theme_path = sphinx_bootstrap_theme.get_html_theme_path() - -#html_theme_options = { -# "show_prev_next": True -#} - -#html_theme_options = { -# "source_url": 'https://github.com/uthcode/learntosolveit' -#} - -# If extensions (or modules to document with autodoc) are in another directory, -# add these directories to sys.path here. If the directory is relative to the -# documentation root, use os.path.abspath to make it absolute, like shown here. -#sys.path.append(os.path.abspath('.')) - -# -- General configuration ----------------------------------------------------- - -# Add any Sphinx extension module names here, as strings. They can be extensions -# coming with Sphinx (named 'sphinx.ext.*') or your custom ones. -#extensions = ['sphinx.ext.autodoc', 'sphinx.ext.doctest', -# 'sphinx.ext.todo', 'sphinx.ext.coverage', -# 'sphinx.ext.extlinks', 'sphinx.ext.pngmath', -# 'sphinxcontrib.runcode'] - -extensions = ['sphinx.ext.extlinks'] - # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] @@ -63,124 +22,36 @@ # The encoding of source files. # source_encoding = 'utf-8-sig' -# The master toctree document. master_doc = 'index' # General information about the project. project = u'Learn To Solve It' copyright = f'{date.today().year} Senthil Kumaran' -# The version info for the project you're documenting, acts as replacement for -# |version| and |release|, also used in various other places throughout the -# built documents. -# -# The short X.Y version. version = '2022-01-06' # The full version, including alpha/beta/rc tags. release = '' -# The language for content autogenerated by Sphinx. Refer to documentation -# for a list of supported languages. -#language = None - -# There are two options for replacing |today|: either, you set today to some -# non-false value, then it is used: -#today = '' -# Else, today_fmt is used as the format for a strftime call. today_fmt = '%d %b of %y' # List of documents that shouldn't be included in the build. -#unused_docs = [] +unused_docs = [] # List of directories, relative to source directory, that shouldn't be searched # for source files. exclude_trees = [] -# The reST default role (used for this markup: `text`) to use for all documents. - -#default_role = None - -# If true, '()' will be appended to :func: etc. cross-reference text. -#add_function_parentheses = True - -# If true, the current module name will be prepended to all description -# unit titles (such as .. function::). -#add_module_names = True - -# If true, sectionauthor and moduleauthor directives will be shown in the -# output. They are ignored by default. -#show_authors = False - -# The name of the Pygments (syntax highlighting) style to use. pygments_style = 'friendly' -# A list of ignored prefixes for module index sorting. -#modindex_common_prefix = [] - -# Links for edit - -# :c-suggest-improve:`name.c` -# :c-better-explain:`name.rst` -# :python-suggest-improve:`name.py` -# :python-better-explain:`name.rst` - -extlinks = { - 'c-suggest-improve': ( - 'https://github.com/uthcode/learntosolveit/' - 'edit/master/languages/cprogs/%s', - "Suggest a Code Improvement: "), - 'c-better-explain': ( - 'https://github.com/uthcode/learntosolveit/' - 'edit/master/source/cprogramming/%s', - "Suggest a better explanation for "), - 'python-suggest-improve': ( - "https://github.com/uthcode/learntosolveit/" - "edit/master/languages/python/%s", - "Suggest a Code Improvement:"), - 'python-better-explain': ( - "https://github.com/uthcode/learntosolveit/" - "edit/master/source/python/%s", - "Suggest a better explanation for "), -} - - -# -- Options for HTML output --------------------------------------------------- - -# The theme to use for HTML and HTML Help pages. See the documentation for -# a list of builtin themes. -#sys.path.append(os.path.abspath('_themes')) -#html_theme_path = ['_themes'] -#html_theme = 'flask' - -# Theme options are theme-specific and customize the look and feel of a theme -# further. For a list of options available for each theme, see the -# documentation. -# html_theme_options = {'headerbg':'white','footerbg':'white'} - -# Add any paths that contain custom themes here, relative to this directory. -#html_theme_path = [] - -# The name for this set of Sphinx documents. If None, it defaults to -# " v documentation". html_title = 'Learn To Solve It' # A shorter title for the navigation bar. Default is the same as html_title. html_short_title = 'Learn To Solve It' -# The name of an image file (relative to this directory) to place at the top -# of the sidebar. -# html_logo = '_static/learntosolveit2.png' - -# The name of an image file (within the static path) to use as favicon of the -# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 -# pixels large. -#html_favicon = None - -# Add any paths that contain custom static files (such as style sheets) here, -# relative to this directory. They are copied after the builtin static files, -# so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] +html_extra_path = ["Ads.txt"] + # These paths are either relative to html_static_path # or fully qualified paths (eg. https://...) @@ -191,36 +62,43 @@ # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. html_last_updated_fmt = '%d %b, %y' - -# If true, SmartyPants will be used to convert quotes and dashes to -# typographically correct entities. -#html_use_smartypants = True - -# Custom sidebar templates, maps document names to template names. -#html_sidebars = {'index': ['indexsidebar.html', 'searchbox.html']} -#html_additional_pages = {'index': 'index.html', 'foo' : 'foo.html', 'bar': 'bar.html'} - html_sidebars = {'**': ['logo.html', 'globaltoc.html']} - -# Additional templates that should be rendered to pages, maps page names to -# template names. -#html_additional_pages = {} - # If false, no module index is generated. html_use_modindex = False # If false, no index is generated. html_use_index = False -# If true, the index is split into individual pages for each letter. -#html_split_index = False - # If true, links to the reST sources are added to the pages. -html_show_sourcelink = False +html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. -html_show_sphinx = True +html_show_sphinx = False # Output file base name for HTML help builder. htmlhelp_basename = 'uthcodedoc' + +try: + extensions +except NameError: + extensions = [] + +extensions.append('sphinx_wagtail_theme') +html_theme = 'sphinx_wagtail_theme' + +project = "" +# These are options specifically for the Wagtail Theme. +html_theme_options = dict( + project_name ="Learn To Solve It", + logo = "uthcode.png", + logo_alt = "", + github_url = "https://github.com/uthcode/learntosolveit/blob/master/source/", + logo_height = 59, + logo_url = "/", + logo_width = 45, + header_links = "Computer Science Courses|https://courses.learntosolveit.com/, Anki| https://ankiweb.net/decks, Projects|https://projects.learntosolveit.com/, Just Do Beaver|https://www.justdobeaver.com/", + footer_links = ",".join([ + "Senthil Kumaran|https://senthil.learntosolveit.com/", + ]), +) \ No newline at end of file diff --git a/source/cprogramming/Ex_1.10_TbsBlnkSpaces.rst b/source/cprogramming/Ex_1.10_TbsBlnkSpaces.rst deleted file mode 100644 index 98451917..00000000 --- a/source/cprogramming/Ex_1.10_TbsBlnkSpaces.rst +++ /dev/null @@ -1,35 +0,0 @@ -======================================================= -Exercise 1.10 - Explicit Tabs, Backslash and Backspaces -======================================================= - -Question --------- - -Write a Program to copy its input to its output, replacing each tab by \t,each -backspace by \b, and each backslash by \\. This makes tabs and backspaces -visible in an unambiguous way. - -Solution --------- - -.. literalinclude:: ../../languages/cprogs/Ex_1.10_TbsBlnkSpaces.c - :language: c - :tab-width: 2 - -.. runcode:: ../../languages/cprogs/Ex_1.10_TbsBlnkSpaces.c - :language: c - :codesite: ideone - -Explanation -=========== - -If the program encounters a special character like ``\t`` (tab) or ``\b`` (blank) or -``\\`` (backslash), we explicitly handle that and print a ``\`` , using -putchar('\\') and then the literal character. For rest of the characters we -simply putchar that. - -.. seealso:: - - * :c-suggest-improve:`Ex_1.10_TbsBlnkSpaces.c` - * :c-better-explain:`Ex_1.10_TbsBlnkSpaces.rst` - diff --git a/source/cprogramming/Ex_1.11_test_word_count.rst b/source/cprogramming/Ex_1.11_test_word_count.rst deleted file mode 100644 index 79eebcaf..00000000 --- a/source/cprogramming/Ex_1.11_test_word_count.rst +++ /dev/null @@ -1,45 +0,0 @@ -======================================= -Exercise 1.11 - Test Word count program -======================================= - -Question -======== - -How would you test the word count program? What kinds of input -are most likely to uncover bugs if there are any? - -Program -======= - -.. literalinclude:: ../../languages/cprogs/sec_1.5.4_word_counting.c - :language: c - :tab-width: 4 - -.. runcode:: ../../languages/cprogs/sec_1.5.4_word_counting.c - :language: c - :codesite: ideone - - -Explanation -=========== - -Testing the word count program involves, giving three kinds of inputs. - -1. Valid Inputs. -2. Boundary Condition Inputs. -3. Invalid Inputs. - -For Valid Inputs, it could be any stream of space separate text. It has valid -space, newline and tab characters. For Boundary conditions, a file entirely -consisting of \n, or a file entirely consisting of \t character or a empty file. - -For invalid Inputs, an unclosed file which does not have EOF, which is tricky to -provide can be given to this program. A unicode character file can be given and -see if getchar() handles it properly. We tested it and it works. - - - -.. seealso:: - - * :c-suggest-improve:`sec_1.5.4_word_counting.c` - * :c-better-explain:`Ex_1.11_test_word_count.rst` diff --git a/source/cprogramming/Ex_1.12_word_per_line.rst b/source/cprogramming/Ex_1.12_word_per_line.rst deleted file mode 100644 index 4b5a51ce..00000000 --- a/source/cprogramming/Ex_1.12_word_per_line.rst +++ /dev/null @@ -1,30 +0,0 @@ -================================================= -Exercise 1.12 - Print the input one word per line -================================================= - -Question --------- - - -Write a program that prints its input one word per line. - -Solution --------- - -.. literalinclude:: ../../languages/cprogs/Ex_1.12_word_per_line.c - :language: c - :tab-width: 2 - - -Explanation -=========== - -In this program, we read the one character at a time and check if the character -is a space ' ', we print newline character, '\n' thus going to next line in the -output, otherwise we simply print the character c. - - -.. seealso:: - - * :c-suggest-improve:`Ex_1.12_word_per_line.c` - * :c-better-explain:`Ex_1.12_word_per_line.rst` diff --git a/source/cprogramming/Ex_1.13.2_His_vertical.rst b/source/cprogramming/Ex_1.13.2_His_vertical.rst deleted file mode 100644 index e8c91d05..00000000 --- a/source/cprogramming/Ex_1.13.2_His_vertical.rst +++ /dev/null @@ -1,104 +0,0 @@ -==================================== -Exercise 1.13.2 - Vertical Histogram -==================================== - -Question --------- - - -Write a program to print a histogram of the lengths of words in its input. Draw -the histogram with the bars vertical. - -Solution --------- - -.. literalinclude:: ../../languages/cprogs/Ex_1.13.2_His_vertical.c - :language: c - :tab-width: 2 - - -.. runcode:: ../../languages/cprogs/Ex_1.13.2_His_vertical.c - :language: c - :codesite: ideone - -Explanation -=========== - -The objective of this program is the print a vertical histogram. -For e.g. if the same input as the previous program is given. - -Input **I love C programming** - -The desired output is:: - - * - * - * - * - * - * - * - * * - * * - * * - * * * * - -Printing the vertical histogram is tricky for number of reasons. - -*Printing usually happens from top to botton and left to right.* - -We have to know this limitation when we write the output. In the program, we -predetermine and store maximum number of words in a sentence (MAXNO 25) and -maximum length of the word (MAXWL 25). So, if our input exceeds those, our -above program may give incorrect output. - -Then we go about finding the word length of each word and store it in a WORD -Array. The way we do this is, initialize all the word lengths to 0 first, and -then count each word length using a while loop. Use a variable, nc to count the -number of characters in a word and store it in **WORD[nw]** and if we find a -space character, then we say it is the next word and start counting the length -of the next (by resetting nc back to 0) - -So for the above example input, we will have. - -First step: WORD[0, 0, 0, 0] - -And then we we count the words and store their lengths. - -We would have got: WORD[1,4,1, 11] - -Next we use the WORD array above and we go about printing from left to right. We -we start left, we can see if our left position (j) is <= WORD value in that -position, WORD[j]. This is accomplished in the for loop `if j <= word[j]` if it -is, then we print * otherwise we print space ''. - -Like in the first line above, when j == 11,. we will print ' ' for position 1, -' ' for position 2, and ' ' for position 3 but '*' for position 4. - -So our output will look like:: - - ' '' '' ''*' - ' '' '' ''*' - ' '' '' ''*' - ' '' '' ''*' - -We will keep going for this till we get j == 4 and at that moment, our output -will be:: - - ' ''*''' '*' - -And when j hits 1 (for all one character words like *I* and *C* in the input), -we will have hit the bottom of the histogram:: - - - '*''*''*''*' - -Combing them all, we would have drawn the horizontal histogram like above. - - - -.. seealso:: - - * :c-suggest-improve:`Ex_1.13.2_His_vertical.c` - * :c-better-explain:`Ex_1.13.2_His_vertical.rst` - diff --git a/source/cprogramming/Ex_1.13_His_Horizontal.rst b/source/cprogramming/Ex_1.13_His_Horizontal.rst deleted file mode 100644 index 3ea7501f..00000000 --- a/source/cprogramming/Ex_1.13_His_Horizontal.rst +++ /dev/null @@ -1,47 +0,0 @@ -==================================== -Exercise 1.13 - Horizontal Histogram -==================================== - -Question --------- - - -Write a program to print a histogram of the lengths of words in its input. It is -easy to draw the histogram with the bars horizontal. - -Solution --------- - -.. literalinclude:: ../../languages/cprogs/Ex_1.13_His_Horizontal.c - :language: c - :tab-width: 2 - -.. runcode:: ../../languages/cprogs/Ex_1.13_His_Horizontal.c - :language: c - :codesite: ideone - -Explanation -=========== - -We desire the histogram like the following. - -If the input is **I love C programming** - -The output should be.:: - - * - **** - * - *********** - -The way it is accomplished in the above program, read each character using -getchar, if it is special character like a space, tab or newline, go to next -line by printing `\n` otherwise print a `*` character. - - - -.. seealso:: - - * :c-suggest-improve:`Ex_1.13_His_Horizontal.c` - * :c-better-explain:`Ex_1.13_His_Horizontal.rst` - diff --git a/source/cprogramming/Ex_1.14_Hist_Freq.rst b/source/cprogramming/Ex_1.14_Hist_Freq.rst deleted file mode 100644 index 1111698d..00000000 --- a/source/cprogramming/Ex_1.14_Hist_Freq.rst +++ /dev/null @@ -1,42 +0,0 @@ -==================================================== -Exercise 1.14 - Histogram of Frequency of Characters -==================================================== - -Question --------- - - -Write a program to print a histogram of the frequencies of different characters -in its input. - - -Solution --------- - -.. literalinclude:: ../../languages/cprogs/Ex_1.14_Hist_Freq.c - :language: c - :tab-width: 4 - -.. runcode:: ../../languages/cprogs/Ex_1.14_Hist_Freq.c - :language: c - :codesite: ideone - -Explanation -=========== - -We define a label TNOCHAR 128 for total number of printable characters in ascii -tabel (0 to 127) and we create an array ` int character[TNOCHAR]` to hold the -number of occurances of those characters. As we get each character from the -input, we increment it's count in the character array. - -We print the histogram at the end, by looping through the characters of the -array, printing the character and then printing `*` for number of times that -character had occurred. - - - -.. seealso:: - - * :c-suggest-improve:`Ex_1.14_Hist_Freq.c` - * :c-better-explain:`Ex_1.14_Hist_Freq.rst` - diff --git a/source/cprogramming/Ex_1.15_tempconv.rst b/source/cprogramming/Ex_1.15_tempconv.rst deleted file mode 100644 index 1483c0cb..00000000 --- a/source/cprogramming/Ex_1.15_tempconv.rst +++ /dev/null @@ -1,42 +0,0 @@ -========================================================= -Exercise 1.15 - Temperature Convertor using function call -========================================================= - -Question --------- - - -Rewrite the temperature conversion program of Section 1.2 to use a function for -conversion. - -Solution --------- - -.. literalinclude:: ../../languages/cprogs/Ex_1.15_tempconv.c - :language: c - :tab-width: 2 - -.. runcode:: ../../languages/cprogs/Ex_1.15_tempconv.c - :language: c - :codesite: ideone - -Explanation -=========== - - -In this program we are going to convert a given Fahrenheit temperature to -Celsius or Celsius temperature to Fahrenheit temperature using the formula -C=(5/9)(F-32 ). We retain most of the program from section 1.4. In addition -This program contains functions such as fahrtocelsius and celsiustofhar. The -functions fahrtocelsius and celsiustofhar are used to make the program more -dynamic by giving choices to the users for conversion between 1 - Fahrenheit to -Celsius Conversion 2 - Celsius to Fahrenheit Converion. - - - -.. seealso:: - - * :c-suggest-improve:`Ex_1.15_tempconv.c` - * :c-better-explain:`Ex_1.15_tempconv.rst` - - diff --git a/source/cprogramming/Ex_1.16_LongLine.rst b/source/cprogramming/Ex_1.16_LongLine.rst deleted file mode 100644 index cbd4a41c..00000000 --- a/source/cprogramming/Ex_1.16_LongLine.rst +++ /dev/null @@ -1,44 +0,0 @@ -========================================================= -Exercise 1.16 - Print length of arbitrary long input line -========================================================= - -Question --------- - - -Revise the main routine of the longest-line program so it will correctly print -the length of arbitrary long input lines, and as much as possible of the text. - -Solution --------- - -.. literalinclude:: ../../languages/cprogs/Ex_1.16_LongLine.c - :language: c - :tab-width: 4 - - -.. runcode:: ../../languages/cprogs/Ex_1.16_LongLine.c - :language: c - :codesite: ideone - -Explanation -=========== - -A string in C is a character array which ends in `\0`. getline is a function in -our program, which reads one character at a time using getchar and stores it in -a character array called s[] and it returns the length of the array. - -We keep track of each line and it's length using a variable, `max`. If the -length of the line is greater than `max`, then we copy that line into the -`maxline` using a copy routine. - -At the end of the program, whichever was the longest line that was copied in -maxline array, we just print that. - - - -.. seealso:: - - * :c-suggest-improve:`Ex_1.16_LongLine.c` - * :c-better-explain:`Ex_1.16_LongLine.rst` - diff --git a/source/cprogramming/Ex_1.17_lengt80.rst b/source/cprogramming/Ex_1.17_lengt80.rst deleted file mode 100644 index d14d3ef0..00000000 --- a/source/cprogramming/Ex_1.17_lengt80.rst +++ /dev/null @@ -1,42 +0,0 @@ -========================================================= -Exercise 1.17 - Print lines that are longer than 80 chars -========================================================= - -Question --------- - - -Write a program to print all input lines that are longer than 80 characters. - -Solution --------- - -.. literalinclude:: ../../languages/cprogs/Ex_1.17_lengt80.c - :language: c - :tab-width: 2 - -.. runcode:: ../../languages/cprogs/Ex_1.17_lengt80.c - :language: c - :codesite: ideone - - -Explanation -=========== - -A string in C is a character array which ends in ``\0``. getline is a function in -our program, which reads one character at a time using getchar and stores it in -a character array called s[] and it returns the length of the array. - -When an array is sent as argument to the function, like ``line[MAXLINE]`` is sent -to ``getline`` function, the value is passed by reference, which means that any -changes the function makes will be available to the main program. - -``getline`` returns the length of the line and in our main program, if the length -is greater than 80 characters we print it. - - - -.. seealso:: - - * :c-suggest-improve:`Ex_1.17_lengt80.c` - * :c-better-explain:`Ex_1.17_lengt80.rst` diff --git a/source/cprogramming/Ex_1.18_remtrailbt.rst b/source/cprogramming/Ex_1.18_remtrailbt.rst deleted file mode 100644 index 405fac98..00000000 --- a/source/cprogramming/Ex_1.18_remtrailbt.rst +++ /dev/null @@ -1,39 +0,0 @@ -=============================================== -Exercise 1.18 - Remove trailing blanks and tabs -=============================================== - -Question --------- - - -Write a program to remove trailing blanks and tabs from each line of input, and -to delete entirely blank lines. - -Solution --------- - -.. literalinclude:: ../../languages/cprogs/Ex_1.18_remtrailbt.c - :language: c - :tab-width: 2 - - -.. runcode:: ../../languages/cprogs/Ex_1.18_remtrailbt.c - :language: c - :codesite: ideone - - -Explanation -=========== - -In the removetrail function, we go to the very end of the line and the trace -back to the find the character which is not a space, tab and then replace it -with \0. This eliminates the trailing blanks in a line. For the empty lines -whose length is 0, we simply skip that from output and thus removing it. - - - -.. seealso:: - - * :c-suggest-improve:`Ex_1.18_remtrailbt.c` - * :c-better-explain:`Ex_1.18_remtrailbt.rst` - diff --git a/source/cprogramming/Ex_1.19_reversestr.rst b/source/cprogramming/Ex_1.19_reversestr.rst deleted file mode 100644 index 338a2bf1..00000000 --- a/source/cprogramming/Ex_1.19_reversestr.rst +++ /dev/null @@ -1,57 +0,0 @@ -================================ -Exercise 1.19 - reverse a string -================================ - -Question --------- - - -Write a function reverse(s) that reverses the character string s. Use it to -write a program that reverses its input a line at a time. - -Solution --------- - -.. literalinclude:: ../../languages/cprogs/Ex_1.19_reversestr.c - :language: c - :tab-width: 2 - - -.. runcode:: ../../languages/cprogs/Ex_1.19_reversestr.c - :language: c - :codesite: ideone - -Explanation -=========== - -A string in C is a character array which ends in `\0`. **getline** is a function -in our program, which reads one character at a time using getchar and stores it -in a character array called s[] and it returns the length of the array. We call -the reverse function on our line. In the reverse function, we calculate the -length of the line minus `\0` and `\n` if that is present. This determines the -ultimate printable characters in the line from where we have to reverse. - -We have to two incides, j=0 and i the last printable character and run through -the program of swapping those characters till `j < i`. -This reverses the contents of our string. - -The crux of the program is this:: - - j = 0; - - while(j < i) - { - temp = rline[j]; - rline[j] = rline[i]; - rline[i] = temp; - --i; - ++j; - } - - - -.. seealso:: - - * :c-suggest-improve:`Ex_1.19_reversestr.c` - * :c-better-explain:`Ex_1.19_reversestr.rst` - diff --git a/source/cprogramming/Ex_1.1_exp_helloworld.rst b/source/cprogramming/Ex_1.1_exp_helloworld.rst deleted file mode 100644 index a4f9d695..00000000 --- a/source/cprogramming/Ex_1.1_exp_helloworld.rst +++ /dev/null @@ -1,60 +0,0 @@ -=================================== -Exercise 1.1 - testing hello, world -=================================== - -Question -======== - -Run the `hello, world` program on your system. Experiment with leaving out -parts of the program, to see what error messages you get. - -.. literalinclude:: ../../languages/cprogs/sec_1.1_helloworld.c - :language: c - :tab-width: 4 - -.. runcode:: ../../languages/cprogs/sec_1.1_helloworld.c - :language: c - :codesite: ideone - -Explanation -=========== - -1. Leaving out `#include` - -The program still compiles and it gives the warning stating that it is using a -built-in function printf. - -:: - - helloworld.c:5: warning: incompatible implicit declaration of built-in function ‘printf’ - - -2. Leaving out `int` or `void` or *both* - -The program compiles and runs without any warning. -We know that spaces and indentation is not important, so we can strip them out. - -3. The smallest program that compiles **with warning**, but executes is this. - -:: - - main(){printf("hello,world\n");} - -4. Any part of the string "hello,world\n" can be left out without any error, - just the program output will be different. - -5. Leaving any other part the program will now result in **compilation error.** - -For e.g. After removing **;** in the above program, we got the compilation -error. - -:: - - error: expected `;` before the '}' token - - -.. seealso:: - - * :c-suggest-improve:`sec_1.1_helloworld.c` - * :c-better-explain:`Ex_1.1_exp_helloworld.rst` - diff --git a/source/cprogramming/Ex_1.20_detab.rst b/source/cprogramming/Ex_1.20_detab.rst deleted file mode 100644 index d79fc6b0..00000000 --- a/source/cprogramming/Ex_1.20_detab.rst +++ /dev/null @@ -1,81 +0,0 @@ -================================================ -Exercise 1.20 - detab, replaces tabs with spaces -================================================ - -Question --------- - - -Write a program detab that replaces tabs in the input with the proper number of -blanks to space to the next tab stop. Assume a fixed set of tab stops, say every -n columns. Should n be a variable or a symbolic parameter? - -Solution --------- - -.. literalinclude:: ../../languages/cprogs/Ex_1.20_detab.c - :language: c - :tab-width: 2 - -.. runcode:: ../../languages/cprogs/Ex_1.20_detab.c - :language: c - :codesite: ideone - - -Explanation -=========== - -We declare TABINC as 8 in #define TABINC 8 as the number of spaces which make a -TAB. - -We start counting the pos from 1 for every new line and we increment pos for all -the characters and print the character, which are not tabs. This is -demonstrated by the else statements in our program. - -When we hit a tab \t character, then we need to determine how many spaces we -need to replace the \t with. - -For e.g.:: - - hello | I press a tab and reach | - hello###| It should be substibuted with 3 #, - -The way 3 # is calculated by `TABINC - length of ('hello')` -that is 8 - 5 = 3. - -This explains well, if hello is the starting word. The way to determine the tabs -to spaces later in the line is by keeping track of the number of characters in -the line (that is variable pos in our program.) - -For e.g - -:: - - hello world is great - hello###world###is######great - - -To determine the number of tabs to spaces between **is** and **great** - -We track the pos till **s**, we encounter the tab position at be 19. - -:: - - nb = TABINC - (( pos - 1) % TABINC); - nb = TABINC - ((19 - 1)) % TABINC); - nb = TABINC - (18 % TABINC); - nb = TABINC - (18 % 8); - nb = TABINC - 2; - nb = 8 - 2; - nb = 6 - -Once we determine the nb, we simply print # character to denote a visible space -and increment the position each character. - - - -.. seealso:: - - * :c-suggest-improve:`Ex_1.20_detab.c` - * :c-better-explain:`Ex_1.20_detab.rst` - diff --git a/source/cprogramming/Ex_1.21_entab.rst b/source/cprogramming/Ex_1.21_entab.rst deleted file mode 100644 index 6343624f..00000000 --- a/source/cprogramming/Ex_1.21_entab.rst +++ /dev/null @@ -1,55 +0,0 @@ -================================================ -Exercise 1.21 - entab, replaces spaces with tabs -================================================ - -Question --------- - -Write a program entab that replaces strings of blanks by the minimum number of -tabs and blanks to achieve the same spacing. Use the same tab stops as for -detab. When either a tab or a single blank would suffice to reach a tab stop, -which should be given preference? - - -Solution --------- - -.. literalinclude:: ../../languages/cprogs/Ex_1.21_entab.c - :language: c - :tab-width: 4 - -.. runcode:: ../../languages/cprogs/Ex_1.21_entab.c - :language: c - :codesite: ideone - - -Explanation -=========== - -1. We declare TABINC as 8 in `#define TABINC 8` as the number of spaces which -make a TAB. - -2. We declare two variables **nb** for number of spaces and **nt** for number of -tabs. - -3. We get the current character by calling getchar() and storing it in variable -c and keep track of the position. - -4. As soon as a space character is found, we increment the number of spaces or -number of tabs. We increment the spaces by pos, if the space is not divisible by -TABINC. If the space occurance is divisible by TABINC, we increment the number -of tabs. This step collects the minimum number of tabs and blanks. - -5. In the else part, when non space is found, we first print the all remaining -tabs, then remaining spaces, then print the character. And We reset the position -accordingly. If it is a newline, we reset the pos, if it is a tab character, we -reset it to previous tab character - 1. This step replaces the spaces with -minimum tabs and spaces. - - - -.. seealso:: - - * :c-suggest-improve:`Ex_1.21_entab.c` - * :c-better-explain:`Ex_1.21_entab.rst` - diff --git a/source/cprogramming/Ex_1.22_fold.rst b/source/cprogramming/Ex_1.22_fold.rst deleted file mode 100644 index 6d5f8b6a..00000000 --- a/source/cprogramming/Ex_1.22_fold.rst +++ /dev/null @@ -1,73 +0,0 @@ -=============================== -Exercise 1.22 - fold long lines -=============================== - -Question --------- - - -Write a program to ``fold`` long input lines into two or more shorter lines -after the last non-blank character that occurs before the n-th column of input. -Make sure your program does something ntelligent with very long lines, and if -there are no blanks or tabs before the specified column. - - -Solution --------- - -.. literalinclude:: ../../languages/cprogs/Ex_1.22_fold.c - :language: c - :tab-width: 4 - -.. runcode:: ../../languages/cprogs/Ex_1.22_fold.c - :language: c - :codesite: ideone - -Explanation -=========== - -1. We determine the column to fold in the MAXCOL variable. - -2. Since tab character can occur too and folding a tab character means folding -it in mid-way, we also replace the tabs in the line with spaces. - -3. Every character of the file is filled into a ``line[MAXCOL]`` array and that -line is acted upon by the program. - -4. We start at ``pos=0`` and take each character and place it in ``line[pos]`` and -then we analyze the character to act upon the condition. - -6. If the character is ``\t``. We go and expand the tab character in the -``line[pos]`` and get newposition. So, when line[\t] at pos = 0, it will be now -``line[' ', ' ', ' ',' ',' ',' ',' ',' '] and pos = 8`` - -7. If character is ``\n`` then we print the entire line contents reset the ``pos`` -back to 0. - -8. *otherwise*, we get into our program. - -When we are folding, we should not be folding in between the word. So we have to -track the previous space occuring in a line. The logic follows. - -1. When our position is greater than MAXCOL, then we look for previous blank -space by using ``getblank`` and we get the position of that blank. - -2. We then ``fold``, getblank will return the pos which is not greater than -MAXCOL. So, the print the characters we have in line and then print newline. - -3. We determine the new position based the return value of getblank. If the -return value of getblank was greater than MAXCOL, then our new position is 0, -which is a newline. We will replace the contents of line starting from 0, mark -this as ``i``, and place the folded contents by the last ``for loop`` in the program -and after placing the folded contents we return the new value of ``i``, which is -our updated ``pos``. - -With our new position we continue with the rest of the program. - - - -.. seealso:: - - * :c-suggest-improve:`Ex_1.22_fold.c` - * :c-better-explain:`Ex_1.22_fold.rst` - diff --git a/source/cprogramming/Ex_1.23_remcomments.rst b/source/cprogramming/Ex_1.23_remcomments.rst deleted file mode 100644 index 5e21d3c1..00000000 --- a/source/cprogramming/Ex_1.23_remcomments.rst +++ /dev/null @@ -1,43 +0,0 @@ -================================================ -Exercise 1.23 - Remove comments from a C program -================================================ - -Question --------- - - -Write a program to remove all comments from a C program. Don't forget to handle -quoted strings and character constants properly. C comments don't nest. - - -Solution --------- - -.. literalinclude:: ../../languages/cprogs/Ex_1.23_remcomments.c - :language: c - :tab-width: 4 - -.. runcode:: ../../languages/cprogs/Ex_1.23_remcomments.c - :language: c - :codesite: ideone - -Explanation -=========== - -If two subsequent characters start with `/` and `*`, we say we are in-comment, -If we find two characters which are `/` and `/`, we will print the first -character and start treating the second `/` as the possible start of comment. In -the same manner, if we encouter a single quote or a double quote character, then -we understand we are inside a quoted string, so we putchar everything before we -find the matching character again. Within a quoted string, if we encouter a -special character, then we try to read them literally as two characters and -print them. - -If / is followed by any other character, we simply print them. - - - -.. seealso:: - - * :c-suggest-improve:`Ex_1.23_remcomments.c` - * :c-better-explain:`Ex_1.23_remcomments.rst` diff --git a/source/cprogramming/Ex_1.24_synerrors.rst b/source/cprogramming/Ex_1.24_synerrors.rst deleted file mode 100644 index f7005c77..00000000 --- a/source/cprogramming/Ex_1.24_synerrors.rst +++ /dev/null @@ -1,52 +0,0 @@ -============================================================== -Exercise 1.24 - Check rudimentary Syntax Errors in a C Program -============================================================== - -Question --------- - - -Write a program to check a C program for rudimentary syntax errors like -unmatched parentheses,brackets and braces. Don't forget about quotes, both -single and double, escape sequences, and comments. (This program is hard if you -do it in full generality.) - - -Solution --------- - -.. literalinclude:: ../../languages/cprogs/Ex_1.24_synerrors.c - :language: c - :tab-width: 4 - - -.. runcode:: ../../languages/cprogs/Ex_1.24_synerrors.c - :language: c - :codesite: ideone - - -Explanation -=========== - -We divide the program up into 3 parts. The text of the program when it is in- -comment, in-quote and rest of the program text. We don't to have worry about the -part when we are in-comment or in-quote because we can find non-matching -brankets or braces in those parts. It is only the rest that we care about. - -When a two sequence characters starts with ``/*`` we enter in-comment block and -continue till we end up with ``*/`` - -When a single quote ``'`` or a double quote ``"`` character is found, we do the same -and continue till we find it's match. - -For the rest of the program, when we first match a brace, bracket or -parenthesis, we mark it as -1 and when we find it's match, we negate it back to -0. If these values end up being anythign other than 0, we say that we found a -mismatch. - - - -.. seealso:: - - * :c-suggest-improve:`Ex_1.24_synerrors.c` - * :c-better-explain:`Ex_1.24_synerrors.rst` diff --git a/source/cprogramming/Ex_1.2_exp_printf_c.rst b/source/cprogramming/Ex_1.2_exp_printf_c.rst deleted file mode 100644 index 1320c887..00000000 --- a/source/cprogramming/Ex_1.2_exp_printf_c.rst +++ /dev/null @@ -1,54 +0,0 @@ -===================================== -Exercise 1.2 - Experiment with printf -===================================== - -Question -======== - -Experiment to find out what happens when prints's argument string contains \c, -where c is some character not listed above. - -Solution -======== - -.. literalinclude:: ../../languages/cprogs/Ex_1.2_exp_printf_c.c - :language: c - :tab-width: 4 - - -Explanation -=========== - -For the invalid characters, the compiler will output a warning statement. - -:: - - warning: unknown escape sequence \d - -The other interesting warning statements are mentioned beside in the program. -The rest of the control characters took effect and this is the output from the -program. - -:: - - a:b:c:cd:de:f: g:gh:hi:ij:jk:kl:lm:mn: - o:op:pq:qr: - s:st: u:☃v: w:wx: - y:yz:zA:AB:BC:CD:DE:F:FG:GH:HI:IJ:JK:KL:LM:MN:NO:OP:PQ:QR:RS:ST:RU:☃V:VW:WX:XY:YZ:Z0:1:2:3:4:5:6:7:8:89:9~:~`:`!:!@:@#:#$:$%^:^&:&*:*(:():)_:_-:-+:+{:{[:[}:}]:]|:|:\a::::;:;":"':'<:<,:,>:>.:.?:?/:/ - - -References -========== - -* `Discussion on U Codepoint`_ -* `Valid escape characters`_ - -.. _Discussion on U Codepoint: http://stackoverflow.com/questions/21241224/unicode-codepoint-of-the-format-unnnnnnnn/ -.. _Valid escape characters: http://en.cppreference.com/w/cpp/language/escape - - -.. seealso:: - - * :c-suggest-improve:`Ex_1.2_exp_printf_c.c` - * :c-better-explain:`Ex_1.2_exp_printf_c.rst` - diff --git a/source/cprogramming/Ex_1.3_fahr2celheading.rst b/source/cprogramming/Ex_1.3_fahr2celheading.rst deleted file mode 100644 index daa22809..00000000 --- a/source/cprogramming/Ex_1.3_fahr2celheading.rst +++ /dev/null @@ -1,42 +0,0 @@ -==================================== -Exercise 1.3 - Temperature Convertor -==================================== - -Question --------- - - -Modify the temperature conversion program to print a heading above the table. - - -Solution --------- - -.. literalinclude:: ../../languages/cprogs/Ex_1.3_fahr2celheading.c - :language: c - :tab-width: 4 - -.. runcode:: ../../languages/cprogs/Ex_1.3_fahr2celheading.c - :language: c - :codesite: ideone - - -Explanation -=========== - -In this program we are going to convert a given Fahrenheit temperature to -Celsius temperature using the formula C=(5/9)(F-32) To do this we declare some -variables in the beginning of the program so that they can be used in the later -stages of the program. The variables in this program are: lower,upper,step, -celsius,fahr. The variable lower is assigned the value 0 similarly upper to 300, -step to 20, and fahr to lower. So when the program enters the while loop it -checks whether fahr <= upper is true, if it is true then it assigns the variable -celsius 5 * (fahr - 32) / 9 and then it prints output. - - - -.. seealso:: - - * :c-suggest-improve:`Ex_1.3_fahr2celheading.c` - * :c-better-explain:`Ex_1.3_fahr2celheading.rst` - diff --git a/source/cprogramming/Ex_1.4_cel2fahr.rst b/source/cprogramming/Ex_1.4_cel2fahr.rst deleted file mode 100644 index 81bbb157..00000000 --- a/source/cprogramming/Ex_1.4_cel2fahr.rst +++ /dev/null @@ -1,44 +0,0 @@ -==================================== -Exercise 1.4 - Temperature Convertor -==================================== - -Question --------- - - -Write a program to print the corresponding Celsius to Fahrenheit table. - - -Solution --------- - -.. literalinclude:: ../../languages/cprogs/Ex_1.4_cel2fahr.c - :language: c - :tab-width: 4 - -.. runcode:: ../../languages/cprogs/Ex_1.4_cel2fahr.c - :language: c - :codesite: ideone - - -Explanation -=========== - -In the previous exercise we converted Fahrenheit temperature to Celsius -temperature. In this program we are going to convert a given Celsius temperature -to Fahrenheit temperature using the formula C=(5/9)(F-32) To do this we declare -some variables in the beginning of the program so that they can be used in the -later stages of the program. The variables in this program are: -lower,upper,step, celsius,fahr. The variable lower is assigned the value 0 -similarly upper to 300, step to 20, and Celsius to lower. So when the program -enters the while loop it checks whether celsius <= upper is true if it is true -then it assigns the variable fahr (9.0/5.0) * celsius + 32.0 and then it prints -out put. - - - -.. seealso:: - - * :c-suggest-improve:`Ex_1.4_cel2fahr.c` - * :c-better-explain:`Ex_1.4_cel2fahr.rst` - diff --git a/source/cprogramming/Ex_1.5_reverse.rst b/source/cprogramming/Ex_1.5_reverse.rst deleted file mode 100644 index d9bf55ee..00000000 --- a/source/cprogramming/Ex_1.5_reverse.rst +++ /dev/null @@ -1,44 +0,0 @@ -=============================================== -Exercise 1.5 - Temperature Convertor in Reverse -=============================================== - -Question --------- - - -Modify the temperature conversion program to print the table in reverse order, -that is, from 300 degrees to 0. - -Solution --------- - -.. literalinclude:: ../../languages/cprogs/Ex_1.5_reverse.c - :language: c - :tab-width: 4 - -.. runcode:: ../../languages/cprogs/Ex_1.5_reverse.c - :language: c - :codesite: ideone - - -Explanation -=========== - -In the previous exercise we converted Fahrenheit temperature to Celsius -temperature. In this program we are going to print the table in reverse order, -that is, from 300 degrees to 0. To do this we declare some variables in the -beginning of the program so that they can be used in the later stages of the -program. The variables in this program are: lower,upper,step, celsius,fahr. The -variable lower is assigned the value 0 similarly upper to 300, step to 20, and -Celsius to lower. So when the program enters the while loop it checks whether -celsius <= upper is true if it is true then it assigns the variable fahr -(9.0/5.0) * celsius + 32.0 and then it prints out put. - - - -.. seealso:: - - * :c-suggest-improve:`Ex_1.5_reverse.c` - * :c-better-explain:`Ex_1.5_reverse.rst` - - diff --git a/source/cprogramming/Ex_1.6_verifyeof.rst b/source/cprogramming/Ex_1.6_verifyeof.rst deleted file mode 100644 index 3630e718..00000000 --- a/source/cprogramming/Ex_1.6_verifyeof.rst +++ /dev/null @@ -1,58 +0,0 @@ -====================================== -Exercise 1.6 - Verify the value of EOF -====================================== - -Question --------- - -Verify the expression `getchar() !=EOF` is 0 or 1. - -Solution --------- - -.. literalinclude:: ../../languages/cprogs/Ex_1.6_verifyeof.c - :language: c - :tab-width: 2 - -.. runcode:: ../../languages/cprogs/Ex_1.6_verifyeof.c - :language: c - :codesite: ideone - -Explanation -=========== - -1. This program is similar to the previous one Ex 1.5, wherein after it gets the -input, it prints the value of the expression getchar() != EOF. - -2. For a file with this contents - -:: - - $cat afile - contents - - -3. We compile and run the program. - -:: - - $gcc Ex1.6_verifyeof.c -o eof - $ ./eof < afile - 1 c1 o1 n1 t1 e1 n1 t1 s1 - - 0 - -4. We see that when char is not EOF, it is printing 1 and when it is EOF, 0 is -printed. - - - -.. seealso:: - - * :c-suggest-improve:`Ex_1.6_verifyeof.c` - * :c-better-explain:`Ex_1.6_verifyeof.rst` - - - - - diff --git a/source/cprogramming/Ex_1.7_eofval.rst b/source/cprogramming/Ex_1.7_eofval.rst deleted file mode 100644 index 6e2c9a01..00000000 --- a/source/cprogramming/Ex_1.7_eofval.rst +++ /dev/null @@ -1,33 +0,0 @@ -=========================== -Exercise 1.7 - Value of EOF -=========================== - -Question --------- - -Write a Program to print the value of EOF. - -Solution --------- - -.. literalinclude:: ../../languages/cprogs/Ex_1.7_eofval.c - :language: c - :tab-width: 2 - -.. runcode:: ../../languages/cprogs/Ex_1.7_eofval.c - :language: c - :codesite: ideone - -Explanation -=========== - -1. Since EOF is an integer, we can print it with %d format in the printf. 2. EOF -value is printed as -1. - - - -.. seealso:: - - * :c-suggest-improve:`Ex_1.7_eofval.c` - * :c-better-explain:`Ex_1.7_eofval.rst` - diff --git a/source/cprogramming/Ex_1.8_count_blanks_etc.rst b/source/cprogramming/Ex_1.8_count_blanks_etc.rst deleted file mode 100644 index 86c09702..00000000 --- a/source/cprogramming/Ex_1.8_count_blanks_etc.rst +++ /dev/null @@ -1,42 +0,0 @@ -============================================== -Exercise 1.8 - Count blanks, tabs and newlines -============================================== - -Question --------- - -Write a program to count blanks, tabs, and newlines. - -Solution --------- - -.. literalinclude:: ../../languages/cprogs/Ex_1.8_count_blanks_etc.c - :language: c - :tab-width: 4 - -.. runcode:: ../../languages/cprogs/Ex_1.8_count_blanks_etc.c - :language: c - :codesite: ideone - -Explanation -=========== - -In this program we are going to count the number of Blanks, tabs and new lines -present in the input. To do this the program, while reading the characters -checks for the condition c = getchar !=EOF which means if the character is not -end of file continue counting Blanks tabs and newlines. Example input: - -I like programming -In C -And the out put shall be: -Blanks: 4 -Tabs: 0 -Newlines: 1 - - - -.. seealso:: - - * :c-suggest-improve:`Ex_1.8_count_blanks_etc.c` - * :c-better-explain:`Ex_1.8_count_blanks_etc.rst` - diff --git a/source/cprogramming/Ex_1.9_SinBlank.rst b/source/cprogramming/Ex_1.9_SinBlank.rst deleted file mode 100644 index e256efbf..00000000 --- a/source/cprogramming/Ex_1.9_SinBlank.rst +++ /dev/null @@ -1,44 +0,0 @@ -=========================================================== -Exercise 1.9 - Replace Continous blanks with a single blank -=========================================================== - -Question --------- - - -Write a program to copy its input to its output, replacing each string of one or -more blanks by a single blank. - -Solution --------- - -.. literalinclude:: ../../languages/cprogs/Ex_1.9_SinBlank.c - :language: c - :tab-width: 2 - -.. runcode:: ../../languages/cprogs/Ex_1.9_SinBlank.c - :language: c - :codesite: ideone - -Explanation -=========== - -The essence of this program is, while reading the characters, if the last -character that we encoutered is a blank, then we skip printing it. - -:: - - if(lastc!=' ') - putchar(c); - -This means that if the last character is not a blank, *only* then print it. We -store the last character in the lastc variable in the line `lastc = c`. For rest -of the characters we simplying print it by `putchar (c)`. - - - -.. seealso:: - - * :c-suggest-improve:`Ex_1.9_SinBlank.c` - * :c-better-explain:`Ex_1.9_SinBlank.rst` - diff --git a/source/cprogramming/Ex_2.10_lowercondit.rst b/source/cprogramming/Ex_2.10_lowercondit.rst deleted file mode 100644 index 7e51e4d7..00000000 --- a/source/cprogramming/Ex_2.10_lowercondit.rst +++ /dev/null @@ -1,44 +0,0 @@ -================================================ -Exercise 2.10 - upper case letters to lower case -================================================ - -Question -======== - -Rewrite the function lower, which converts upper case letters to lower case, -with a conditional expression instead of if-else. - -.. literalinclude:: ../../languages/cprogs/Ex_2.10_lowercondit.c - :language: c - :tab-width: 4 - -.. runcode:: ../../languages/cprogs/Ex_2.10_lowercondit.c - :language: c - :codesite: ideone - -Explanation -=========== - -In this program we are going to convert upper case letters to lower case. We -declare a function called lower in the beginning of the program. When the -program enters the while loop it each character it gets to lower:: - - while((c=getchar())!=EOF) - { - putchar(lower(c)); - } - -The lower function checks for all the uppercase characters and prints everything -in the lowercase. It does this by a conditional statement, where if a upper case -character is found, it subtracts 'A' to get relative index, adds it to 'a' to -return corresponding smaller case character, if a lower case character is found, -it is simply returned:: - - return c>='A' && c<='Z'? c+'a'-'A':c; - - - -.. seealso:: - - * :c-suggest-improve:`Ex_2.10_lowercondit.c` - * :c-better-explain:`Ex_2.10_lowercondit.rst` diff --git a/source/cprogramming/Ex_2.1_cal_limits.rst b/source/cprogramming/Ex_2.1_cal_limits.rst deleted file mode 100644 index b21623dc..00000000 --- a/source/cprogramming/Ex_2.1_cal_limits.rst +++ /dev/null @@ -1,135 +0,0 @@ -=============================== -Exercise 2.1 - Count the Ranges -=============================== - -Question -======== - -Write a program to determine the ranges of char, short, int, and long variables, -both signed and unsigned, by printing appropriate values from standard headers -and by direct computation. Harder if you compute them: determine the ranges of -the various floating-point types. - - -.. literalinclude:: ../../languages/cprogs/Ex_2.1_cal_limits.c - :language: c - :tab-width: 4 - -.. runcode:: ../../languages/cprogs/Ex_2.1_cal_limits.c - :language: c - :codesite: ideone - -Explanation -=========== - - -The execution of the above program will give:: - - Minimum Signed Char -128 - Maximum Signed Char 127 - Minimum Signed Short -32768 - Maximum Signed Short 32767 - Minimum Signed Int -2147483648 - Maximum Signed Int 2147483647 - Minimum Signed Long -2147483648 - Maximum signed Long 2147483647 - Maximum Unsigned Char 255 - Maximum Unsigned Short 65535 - Maximum Unsigned Int 4294967295 - Maximum Unsigned Long 4294967295 - - -In order explain how we calculate the maximum values, we will have to do some -bit arthimetic. Let's start by calculating the maximum unsigned char. - -Sign bit is usually the left most bit of the type. To make it unsigned, we -remove the sign bit and store 0 in it's place. - -To represent (unsigned char) 0 = **0000 0000** -To represent it's complement, (unsigned char) ~0 = **1111 1111** - -Right Shift 1 will shift that entire sequence to the right and insert 0 from the -left side, so it will give 0111 1111 - -Converting 0111 1111 to integer will be:: - - 0 * 2^7 + 1 * 2^ 6 + 1 * 2^5 + 1 * 2^4 + 1 * 2^3 + 1 *2^2 + 1 * 2^1 + 1 * 2^0 - = 0 * 0 + 1 * 64 + 1 * 32 + 1 * 16 + 1 * 8 + 1 * 4 + 1 * 2 + 1 * 1 - = 0 + 64 + 32 + 16 + 8 + 4 + 2 + 1 - = 127 - -That is the maximum signed char value. To get the minimum signed char value, we -look for the number in the other end of the number line. - -That is got by, multiplying it by -1 and going one number further to the left in -the number line:: - - = - 127 -1 - = -128 - -So our range is displayed like this:: - - -128..-2..-1..0 1 2 3 4... 127 - -Maximum signed short --------------------- - -To get the maximum signed short number, we start with unsigned short type again -and repeat the same operations like we did above. - -(short)((unsigned short)~0 >> 1) - -In our compiler, a short is 2 bytes - -(unsigned short) 0 means **0000 0000 0000 0000** -(unsigned short) ~0 means **1111 1111 1111 1111** - -Logical right shift, is we are eliminating the sign bit, which is the left most -bit in the sequence. - -(unsigned short)~0 >> 1) - -Take this portion ``1111 1111 1111 111`` 1 and place it as **1111 1111 1111 111** -And then add 0 to the left **0** 1111 1111 1111 111 -Rearranging we get **0111 1111 1111 1111** - -What is value of 0111 1111 1111 1111 ? - -Similar to above:: - - = 0 * 2^15 + 1 * 2^14 + 1 * 2^13 + 1 * 2^12 - + 1 * 2^11 + 1* 2^10 + 1 * 2^9 + 1 * 2^8 - + 1*2^7 + 1 * 2^6 + 1*2^5 + 1*2^4 - + 1* 2^3 + 1*2^2 + 1* 2^1 +1*2^0 - - = 16384 + 8192 + 4096 + 2048 + 1024 + 512 + 256 + 128 + 64 + 32 + 16 + 8 + 4 + 2 - = + 1 32767 - -So, our maximum unsigned short is 32767 - -Mininum unsigned short will be the negative of that number going one step -further, i.e:: - - = -32767 - 1 = -32768 - -Similarily, we can calculate for int and long types. - -For unsigned types, we do not do the shifting (to remove the sign) but simply -print the value of all 1s of the type - -(unsigned char)~0; - -can be represented as (unsigned char) ~0 = 1111 1111 - -:: - - = 1 * 2^7 + 1 * 2^ 6 + 1 * 2^5 + 1 * 2^4 + 1 * 2^3 + 1 *2^2 + 1 * 2^1 + 1 * 2^0 - = 128 + 64 + 32 + 16 + 8 + 4 + 2 + 1 - = 255 - - - -.. seealso:: - - * :c-suggest-improve:`Ex_2.1_cal_limits.c` - * :c-better-explain:`Ex_2.1_cal_limits.rst` diff --git a/source/cprogramming/Ex_2.2_getline_without_and_or.rst b/source/cprogramming/Ex_2.2_getline_without_and_or.rst deleted file mode 100644 index d70ba6e3..00000000 --- a/source/cprogramming/Ex_2.2_getline_without_and_or.rst +++ /dev/null @@ -1,60 +0,0 @@ -======================================================= -Exercise 2.2 - Write getline without && and || operator -======================================================= - -Question -======== - -For example, here is a loop from the input function getline that we -wrote in Chapter 1:: - - for (i=0; i < lim-1 && (c=getchar()) != '\n' && c != EOF; ++i) - s[i] = c; - - -Write a loop equivalent to the for loop above without using && or ||. - - -.. literalinclude:: ../../languages/cprogs/Ex_2.2_getline_without_and_or.c - :language: c - :tab-width: 4 - -.. runcode:: ../../languages/cprogs/Ex_2.2_getline_without_and_or.c - :language: c - :codesite: ideone - - -Explanation -=========== - -We use mgetline instead of getline, so that our compiler does not get confused -with the builtin getline function. - -The crux of the program is this. - -:: - - for(i=0; i < lim - 1 ;++i) { - c = getchar(); - if (c == EOF) - break; - if (c == '\n') - break; - s[i] = c; - } - - -Here we removed `c = getchar()` from the loop condition testing and we **enter** -the loop and then check for conditions like EOF and \n. If we encounter those -undesirable condition, we simply break out of the for loop. - -This is equivalent to the for loop above in the question which uses && condition -to check. - - - -.. seealso:: - - * :c-suggest-improve:`Ex_2.2_getline_without_and_or.c` - * :c-better-explain:`Ex_2.2_getline_without_and_or.rst` - diff --git a/source/cprogramming/Ex_2.3_htoi.rst b/source/cprogramming/Ex_2.3_htoi.rst deleted file mode 100644 index 41a68eea..00000000 --- a/source/cprogramming/Ex_2.3_htoi.rst +++ /dev/null @@ -1,98 +0,0 @@ -========================================================== -Exercise 2.3 - Converting Hexadecimal Digits Into Integers -========================================================== - -Question -======== - -Write a function htoi(s), which converts a string of hexadecimal digits -(including an optional 0x or 0X) into its equivalent integer value. The -allowable digits are 0 through 9, a through f,and A through F. - -.. literalinclude:: ../../languages/cprogs/Ex_2.3_htoi.c - :language: c - :tab-width: 4 - -.. runcode:: ../../languages/cprogs/Ex_2.3_htoi.c - :language: c - :codesite: ideone - -Explanation -=========== - -In this program we are going to convert a string of hexadecimal digits into -integer value. If give input as `F` then the output should be 15. This is done -by the htoi function:: - - int htoi(char s[]) - { - int hexdigit,i,inhex,n; - i = 0; - if( s[i] == '0') - { - ++i; - if(s[i] == 'x' || s[i] == 'X') - ++i; - } - - n = 0; - inhex = YES; - - for(;inhex==YES;++i) - { - if(s[i] >='0' && s[i] <='9') - hexdigit= s[i] - '0'; - else if(s[i] >='a' && s[i] <='f') - hexdigit= s[i] -'a' + 10; - else if(s[i] >='A' && s[i] <='F') - hexdigit= s[i] -'A' + 10; - else - inhex = NO; - - if(inhex == YES) - n = 16 * n + hexdigit; - } - return n; - } - -In the above fragment of the program we declare some variables such as hexdigit -for storing each digit in hexadecimal ,i as a counter,inhex as flag to see if we -are still looking a hexadecimal and finally n where we store our converted -hexadecimal number. - -First we strip off any characters which look like `0x` or `0X` and then we enter -to convert rest of the characters. Then we start the conversion process, we set -the flag index to YES and n to 0. - -Then in the for loop as long as index is YES, then we check each character 0 to -9, a to f or A to F. If we find 0 to 9, we store the value char - `0`, if we -find a character between a to f, we store char - `a` + 10, becase hexadecimal -'a' is decimal 10 and similar for character range capital A to F. - -Then we take each hex digit and for it's position or previous value stored in n, -we mutiply by 16 and add hexdigit. - - if(inhex == YES) - n = 16 * n + hexdigit; - -For example to convert **0XAF**. - -1. We strip off 0X. -2. For A, we get the value hexdigit = 10 -3. n = 16 * 0 + 10 - = 10 -4. We gather F, we store hexdigit = 'F' - 'A' + 10; - = 70 - 65 + 10; (70 is ascii value for F, 65 is ascii value for A) - = 15 -5. n = 16 * n + hexdigit - = 16 * 10 + 15 - = 160 + 15 - = 175 - -**175** - - -.. seealso:: - - * :c-suggest-improve:`Ex_2.3_htoi.c` - * :c-better-explain:`Ex_2.3_htoi.rst` diff --git a/source/cprogramming/Ex_2.4_squeezess.rst b/source/cprogramming/Ex_2.4_squeezess.rst deleted file mode 100644 index 57a29f2b..00000000 --- a/source/cprogramming/Ex_2.4_squeezess.rst +++ /dev/null @@ -1,52 +0,0 @@ -============================================================ -Exercise 2.4 - Compare S1, S2 To Delete Same Character in S1 -============================================================ - -Question -======== - -Write an alternative version of squeeze(s1,s2) that deletes each character in s1 -that matches any character in the string s2. - -.. literalinclude:: ../../languages/cprogs/Ex_2.4_squeezess.c - :language: c - :tab-width: 4 - -.. runcode:: ../../languages/cprogs/Ex_2.4_squeezess.c - :language: c - :codesite: ideone - -Explanation -=========== - -Let's take the two inputs strings as: - - s1: HelloWorld - - s2: ol - -Our desired output is:: - - HeWrd - -This has removed the characters `o` and `l` from the first string. The way -squeeze works is, it take each character from the first string and if there is -no match found, stores it with a new index `k`. If there is a match found in -**s2**, it simply skips it. The way it skips is realized by the following:: - - for(j=0; (s1[i]!=s2[j]) && s2[j]!='\0' ;++j) - ; - if(s2[j]=='\0') - s1[k++] = s1[i]; - -When the match is found **s1[i] == s2[j]** so our first for loop will **end**. -The second **if condtion** will fail too as s2 is not iterated till the end, so -we do not place the character in **s1[k++]** and we have successfully skipped -it. - - - -.. seealso:: - - * :c-suggest-improve:`Ex_2.4_squeezess.c` - * :c-better-explain:`Ex_2.4_squeezess.rst` diff --git a/source/cprogramming/Ex_2.5_any.rst b/source/cprogramming/Ex_2.5_any.rst deleted file mode 100644 index c3668e48..00000000 --- a/source/cprogramming/Ex_2.5_any.rst +++ /dev/null @@ -1,44 +0,0 @@ -====================================================================== -Exercise 2.5 - return the first location in the string s1 comparing s2 -====================================================================== - -Question -======== - -Write the function any(s1,s2), which returns the first location in a string s1 -where any character from the string s2 occurs, or -1 if s1 contains no -characters from s2. (The standard library function strpbrk does the same job but -returns a pointer to the location.) - -.. literalinclude:: ../../languages/cprogs/Ex_2.5_any.c - :language: c - :tab-width: 4 - -.. runcode:: ../../languages/cprogs/Ex_2.5_any.c - :language: c - :codesite: ideone - -Explanation -=========== - - -The important part of the program is the function `any` which takes two strings -`s1` and `s2` and tries to find if any character in `s2` matches `s1`. We set a -**flag**, `check_next_char` which is toggled to **0** if we find the match, -otherwise we have it as 1. - -The first for loop iterates through all the characters in s1 while the condition -`check_next_char` is 1. In the second for loop, if we find that a char in s2 -matches s1, that is `s2[j] == s1[i]` and s2 has not reached EOL, then we set -check_next_char to 0. That is we found a match at **i** and we return that. - -If we dont find a match in s2, we increment i and take the next character from -s1. If dont find a match at all, then we return -1. - - - -.. seealso:: - - * :c-suggest-improve:`Ex_2.5_any.c` - * :c-better-explain:`Ex_2.5_any.rst` - diff --git a/source/cprogramming/Ex_2.6_setbits.rst b/source/cprogramming/Ex_2.6_setbits.rst deleted file mode 100644 index bb7e0e16..00000000 --- a/source/cprogramming/Ex_2.6_setbits.rst +++ /dev/null @@ -1,160 +0,0 @@ -=========================================== -Exercise 2.6 - Setting bits at a position n -=========================================== - -Question -======== - -Write a function setbits(x,p,n,y) that returns x with the n bits that begin at -position p set to the rightmost n bits of y, leaving the other bits unchanged. - -.. literalinclude:: ../../languages/cprogs/Ex_2.6_setbits.c - :language: c - :tab-width: 4 - -.. runcode:: ../../languages/cprogs/Ex_2.6_setbits.c - :language: c - :codesite: ideone - -Explanation -=========== - -The important piece of the program is this:: - - (x & ~(~(~0 << n) << (p+1-n))) | ( y & (~(~0<> n; - x = x | rbit; - - For the same example. - -:: - - n is between 0 - wordlength() - - condition 1.when (n == 0) or (n == wordlength()) - - rightrot(x, 0) == x - - condition 2. when (n > 0) and (n < wordlength()) like n = 3 - - x = 0001 1001 - the right n bits will be 001. - the right rightrot(x,n)result should be 0010 0011 - - x << (wordlength() - n) = 0001 1001 << (8 - 3) - = 0001 1001 << 5 - = 0010 0000 - -So we have got the right most n bits set.Now we right x by 1 and OR the rbit with x. - -:: - - x >> n = 0001 1001 >> 3 - = 0000 0011 - - x | rbit = 0000 0011 | 0010 0000 - = 0010 0011 - -Which is our expected result. - -:: - - condition 3. when (n > wordlength()) like n = 12 - -The Compiler will auto transfer "n" to "n % wordlength()", n will be 3, then see "n" as condition 2. -The result should be correct too! - -:: - condition 4. when n < 0 (which is not Often use) - -The result will mirror the function,the rightrot(x,n) function will move the left most n(n > 0)bits to the right -side ,the function should called leftrot(x,n). - - - -.. seealso:: - - * :c-suggest-improve:`Ex_2.8_rightrot.c` - * :c-better-explain:`Ex_2.8_rightrot.rst` diff --git a/source/cprogramming/Ex_2.9_bitcount2s.rst b/source/cprogramming/Ex_2.9_bitcount2s.rst deleted file mode 100644 index b73a9079..00000000 --- a/source/cprogramming/Ex_2.9_bitcount2s.rst +++ /dev/null @@ -1,155 +0,0 @@ -============================================= -Exercise 2.9 - two's complement number system -============================================= - -Question -======== - -In a two's complement number system, x &= (x-1) deletes the rightmost 1-bit in -x. Explain why. Use this observation to write a faster version of bitcount. - -.. literalinclude:: ../../languages/cprogs/Ex_2.9_bitcount2s.c - :language: c - :tab-width: 4 - -.. runcode:: ../../languages/cprogs/Ex_2.9_bitcount2s.c - :language: c - :codesite: ideone - -Explanation -=========== - -**ones** complement is a system used in some computers to represent negative -numbers. To negate a number, each bit of the number is inverted (zeros are -replaced with ones and vice versa). - -:: - - ... - 000...00011 = +3 - 000...00010 = +2 - 000...00001 = +1 - 000...00000 = +0 - 111...11111 = -0 - 111...11110 = -1 - 111...11101 = -2 - 111...11100 = -3 - ... - -This has the consequence that there are two reperesentations for zero, either -all zeros or all ones. - -In **twos complement** each bit of the number is inverted (zeros are replaced -with ones and vice versa), as for ones complement, but then one (000...0001) is -added (ignoring overflow). This avoids the two representations for zero found in -ones complement by using all ones to represent -1 - -:: - - ... - 000...00011 = +3 - 000...00010 = +2 - 000...00001 = +1 - 000...00000 = 0 - 111...11111 = -1 - 111...11110 = -2 - 111...11101 = -3 - ... - -This representation simplifies the logic required for addition and subtraction, -at the expense of a little extra complexity for negation. - -For e.g - -We want to calculate -4 + 5 = 1 - -In order to represent, -4, we can use two's complement. - - -:: - - 4 = 0000 0100 - 1's complement of 4 = 1111 1011 - 2's complement of 4 = 1111 1100 - - 5 = 0000 0101 - - -4 + 5 = 1111 1100 - + 0000 0101 - ----------- - 0000 0001 - - with 1 overflow which is ignored. - - So the answer is 0000 0001 = 1 that we expected. - - -The question asks us to explain why *x &= (x-1)* deletes the right most bit. - -:: - - x &= (x-1) can be written as x = x & (x - 1) - - x - 1 is any binary number subtrated by 0000 0001 - x - 1 has the property of changing the right most 1 to 0. - and right most 0 to 1 by using borrows. - - -To get concrete:: - - x = 1 = 0000 0001 - - x-1 = 0000 0001 - - 0000 0001 - ------------ - 0000 0000 - ------------ - - x = 2 = 0000 0010 - - x - 1 = 0000 0010 - -0000 0001 - ---------- - 0000 0001 - ---------- - - x = 5 = 0000 0101 - - x -1 = 0000 0101 - -0000 0001 - ---------- - 0000 0100 - ---------- - -We see that x-1 has the property of inverting the last bit. So, *x & x -1* will -always set the last bit to 0. - - -If we use the property of **x & x-1** setting the last bit to 0, then we can we -use this to count the number of bits. This is done in our bitcount's for loop. - -:: - - for(b=0; x!=0; x &= x-1) - ++b; - -This gives the number of 1 bits in our program. **AND** operation is faster than -shifting, because all bits of the number are **not** moved and thereby makes our -program more efficient. - - -References -========== - -* `Ones complement`_ -* `Twos complement`_ - -.. _Ones complement: http://foldoc.org/ones+complement -.. _Twos complement: http://foldoc.org/twos+complement - - - -.. seealso:: - - * :c-suggest-improve:`Ex_2.9_bitcount2s.c` - * :c-better-explain:`Ex_2.9_bitcount2s.rst` diff --git a/source/cprogramming/Ex_3.1_binsearch-2.rst b/source/cprogramming/Ex_3.1_binsearch-2.rst deleted file mode 100644 index bf8db706..00000000 --- a/source/cprogramming/Ex_3.1_binsearch-2.rst +++ /dev/null @@ -1,39 +0,0 @@ -====================================================================== -Exercise 3.1 - Binsearch function, writing minimum tests inside a loop -====================================================================== - -Question -======== - -Our binary search makes two tests inside the loop, when one would suffice (at -the price of more tests outside.) Write a version with only one test inside the -loop and measure the difference in runtime. - -.. literalinclude:: ../../languages/cprogs/Ex_3.1_binsearch-2.c - :language: c - :tab-width: 4 - -.. runcode:: ../../languages/cprogs/Ex_3.1_binsearch-2.c - :language: c - :codesite: ideone - -Explanation -=========== - - The program demonstrates a binsearch function which - takes element (x) to search for, an array of integers and the length of the array as arguments. - - The program determines the position of the element(x) by doing a binary search. Binary search can only - be used for sorted arrays. Program compares search element (x) with mid element of the given array. If mid element is greater than search - element then search continues among the rest of the elements towards left of current mid element. - Search continues in similar fashion. If found, program returns the position of search element in the array. - - In the example above search element is 9. Program returns 4 which is the position of search element - in the given array. - - - - .. seealso:: - - * :c-suggest-improve:`Ex_3.1_binsearch-2.c` - * :c-better-explain:`Ex_3.1_binsearch-2.rst` diff --git a/source/cprogramming/Ex_3.2_escape.rst b/source/cprogramming/Ex_3.2_escape.rst deleted file mode 100644 index fcdda5e4..00000000 --- a/source/cprogramming/Ex_3.2_escape.rst +++ /dev/null @@ -1,39 +0,0 @@ -======================================================== -Exercise 3.2 - escape sequences into the real characters -======================================================== - -Question -======== - -Write a function escape(s,t) that converts characters like newline and tab into -visible escape sequences like \n and \t as it copies the string t to s. Use a -switch. Write a function for the other direction as well, converting escape -sequences into the real characters. - -.. literalinclude:: ../../languages/cprogs/Ex_3.2_escape.c - :language: c - :tab-width: 4 - -.. runcode:: ../../languages/cprogs/Ex_3.2_escape.c - :language: c - :codesite: ideone - -Explanation -=========== - -C Program interpreters ``\n`` and ``\t`` as space characters and outputs them. Our -intention is to capture the ``\n`` and ``\t`` characters and display them visibly as -**\n** or **\t**. In order to do that we need to *escape* them, the escaping is -done by adding ``\`` character. - -So in the program as soon as we see a ``\n`` character, in the array where we are -copying to, we copy ``\\`` character and add a ``n`` character and similarly, when -we see a ``\t`` character, in the array where we are copying to, we copy ``\\`` -character and add a ``t`` character. - - - -.. seealso:: - - * :c-suggest-improve:`Ex_3.2_escape.c` - * :c-better-explain:`Ex_3.2_escape.rst` diff --git a/source/cprogramming/Ex_3.3_expand.rst b/source/cprogramming/Ex_3.3_expand.rst deleted file mode 100644 index c6f11afa..00000000 --- a/source/cprogramming/Ex_3.3_expand.rst +++ /dev/null @@ -1,44 +0,0 @@ -============================================================== -Exercise 3.3 - expand short hand notation in s1 into string s2 -============================================================== - -Question -======== - -Write a function expand(s1,s2) that expands shorthand notations like a-z in the -string s1 into the equivalent complete list abc...xyz in s2. Allow for letters -of either case and digits, and be prepared to handle cases like a-b-c and a-z0-9 -and -a-z. Arrange that a leading or trailing -is taken literally. - -.. literalinclude:: ../../languages/cprogs/Ex_3.3_expand.c - :language: c - :tab-width: 4 - - -.. runcode:: ../../languages/cprogs/Ex_3.3_expand.c - :language: c - :codesite: ideone - - -Explanation -=========== - -Here we expand the strings like a-z from s1 into an expanded form in s2. We -utilize the ascii table property that the second character is higher than the -first character and it is incremental. - -In the outer while loop, we get the character in c, and then check if the next -character is ``-`` and character beyond that (i+1) is greater than c. With this -check, we ascertain that we are in a range like ``a-z``. - -To expand the range, we keep incrementing the character in **c**, till it hits -the end character, storing all the characters in s2. - -s2 will now have the expanded string. - - - -.. seealso:: - - * :c-suggest-improve:`Ex_3.3_expand.c` - * :c-better-explain:`Ex_3.3_expand.rst` diff --git a/source/cprogramming/Ex_3.4_itoa-2.rst b/source/cprogramming/Ex_3.4_itoa-2.rst deleted file mode 100644 index 08b19b71..00000000 --- a/source/cprogramming/Ex_3.4_itoa-2.rst +++ /dev/null @@ -1,46 +0,0 @@ -====================================================== -Exercise 3.4 - itoa to handle largest negative integer -====================================================== - -Question -======== - -In a two's complement number representation, our version of itoa does not handle -the largest negative number, that is, the value of n equal to -(2wordsize-1). -Explain why not. Modify it to print that value correctly, regardless of the -machine on which it runs. - -The previous version of itoa was this:: - -.. literalinclude:: ../../languages/cprogs/Ex_3.4_itoa-previous.c - :language: c - :tab-width: 4 - -.. literalinclude:: ../../languages/cprogs/Ex_3.4_itoa-2.c - :language: c - :tab-width: 4 - -.. runcode:: ../../languages/cprogs/Ex_3.4_itoa-2.c - :language: c - :codesite: ideone - -Explanation -=========== - -In this version of itoa, which involves a largest negative number, we first -store the number itself in an integer called sign. Then get numbers from -unittest by doing `n%10`, get the unsigned number by doing a `abs` value and get -character by adding it to `0`. - -Thus we go about converting each digit starting from unit place to a character. -Once this process is over. We check if we were converting negative number, by -checking if the sign is less than 0, if it was, we add a `-` to the string. - -And then we do a simple `reverse` of the string to get our `itoa`. - - - -.. seealso:: - - * :c-suggest-improve:`Ex_3.4_itoa-2.c` - * :c-better-explain:`Ex_3.4_itoa-2.rst` diff --git a/source/cprogramming/Ex_3.5_itob.rst b/source/cprogramming/Ex_3.5_itob.rst deleted file mode 100644 index e8593a06..00000000 --- a/source/cprogramming/Ex_3.5_itob.rst +++ /dev/null @@ -1,42 +0,0 @@ -============================================================== -Exercise 3.5 - function itob, converts a integer into a string -============================================================== - -Question -======== - -Write the function itob(n,s,b) that converts the integer n into a base b -character representation in the string s. In particular, itob(n,s,16) formats s -as a hexadecimal integer in s. - -.. literalinclude:: ../../languages/cprogs/Ex_3.5_itob.c - :language: c - :tab-width: 4 - -.. runcode:: ../../languages/cprogs/Ex_3.5_itob.c - :language: c - :codesite: ideone - -Explanation -=========== - - -In this, we are specifically targetting the conversion to base 16, though we -should be able to extend the program to any base. - -As before we get the number and store it in sign, then we get the remainder of -the number after dividing by base `b`. We covert the number we have gotten to -hexadecimal by this expression ` (j <= 9)?j+'0':j+'a'-10`, which states that if -the number is less than 10, return the string representation of it, otherwise -subtract 10 from it and add 'a' to get the hexadecimal representation of 10 to -15 that (a,b,c,d,e,f). - -We store these in a string and it number was a negative number, we append '-' -sign to it. We get the result, by reversing the string which we constructed. - - - -.. seealso:: - - * :c-suggest-improve:`Ex_3.5_itob.c` - * :c-better-explain:`Ex_3.5_itob.rst` diff --git a/source/cprogramming/Ex_3.6_itoa-3.rst b/source/cprogramming/Ex_3.6_itoa-3.rst deleted file mode 100644 index 04883c3f..00000000 --- a/source/cprogramming/Ex_3.6_itoa-3.rst +++ /dev/null @@ -1,53 +0,0 @@ -==================================== -Exercise 3.6 - itoa with field width -==================================== - -Question -======== - -Write a version of itoa that accepts three arguments instead of two. The third -argument is a minimum field width; the converted number must be padded with -blanks on the left if necessary to make it wide enough. - -.. literalinclude:: ../../languages/cprogs/Ex_3.6_itoa-3.c - :language: c - :tab-width: 4 - -.. runcode:: ../../languages/cprogs/Ex_3.6_itoa-3.c - :language: c - :codesite: ideone - -Explanation -=========== - -Note: For negative numbers the negative sign is written close to the number -instead of before the padded width. This is ``itoa`` conversion with padding. We -specify the width of the number we want in ``w`` and as before, we proceed with -``itoa``, wherein extract the unit digit (n ``% 10``), convert it to character and -store it in a character array. If it were a negative number we store the sign -too. We keep track of number of digits in the number in a variable, ``i`` and for -the remaining digits, for ``i < w``, we append the space character " ". - -We reverse the string thus constructed for our result. - - -Visualize It -============ - -.. raw:: html - - - -Run It -====== - -.. raw:: html - - - - - -.. seealso:: - - * :c-suggest-improve:`Ex_3.6_itoa-3.c` - * :c-better-explain:`Ex_3.6_itoa-3.rst` diff --git a/source/cprogramming/Ex_4.10_calculator_getline.rst b/source/cprogramming/Ex_4.10_calculator_getline.rst deleted file mode 100644 index c857b000..00000000 --- a/source/cprogramming/Ex_4.10_calculator_getline.rst +++ /dev/null @@ -1,89 +0,0 @@ -======================================== -Exercise 4.10 - Calculator using getline -======================================== - -Question -======== - -An alternate organization uses getline to read an entire input line; this makes -getch and ungetch unnecessary. Revise the calculator to use this approach. - -.. literalinclude:: ../../languages/cprogs/Ex_4.10_calculator_getline.c - :language: c - :tab-width: 4 - -.. runcode:: ../../languages/cprogs/Ex_4.10_calculator_getline.c - :language: c - :codesite: ideone - -Explanation -=========== - -This program uses `mgetline` to get the characters and operands from the input -and and proceeds with the RPN calculator logic. - -This is the main part of the program. - - -:: - - /* getop: get next operator or numeric operand */ - - int getop(char s[]) - { - int c,i; - - if(line[li] == '\0') - if(mgetline(line,MAXLINE) == 0) - return EOF; - else - li =0; - - while((s[0] = c = line[li++]) == ' ' || c == '\t') - ; - - s[1] = '\0'; - - if(!isdigit(c) && c!= '.') - return c; - - i = 0; - - if(isdigit(c)) - while(isdigit(s[++i] = c = line[li++])) - ; - if( c == '.') - while(isdigit(s[++i] = c = line[li++])) - ; - - s[i] = '\0'; - - li--; - - return NUMBER; - } - - -From the mgetline function, it takes the input in the line character array, and -if if the line is `\0` only, then we define that as EOF and return `EOF`. Then -we assign to `c` the value present at `line` and look for various conditions -like, if line is a space or tab character, we simply skip it. If we encouter c -which is not a digit or not a `.` character, we return `c` immediately. At the -end if it is valid number, we return a NUMBER, which is then pushed onto the -stack of the RPN calculator. - -An example execution will look like this. - -:: - - 10 10 + - 20 - 10.1 20.2 + - 30.3 - - - -.. seealso:: - - * :c-suggest-improve:`Ex_4.10_calculator_getline.c` - * :c-better-explain:`Ex_4.10_calculator_getline.rst` diff --git a/source/cprogramming/Ex_4.11_getch_static.rst b/source/cprogramming/Ex_4.11_getch_static.rst deleted file mode 100644 index 05aeedb5..00000000 --- a/source/cprogramming/Ex_4.11_getch_static.rst +++ /dev/null @@ -1,87 +0,0 @@ -==================================== -Exercise 4.11 - getline using static -==================================== - -Question -======== - -Modify getop so that it doesn't need to use ungetch. Hint: use an internal -static variable. - -.. literalinclude:: ../../languages/cprogs/Ex_4.11_getch_static.c - :language: c - :tab-width: 4 - -.. runcode:: ../../languages/cprogs/Ex_4.11_getch_static.c - :language: c - :codesite: ideone - -Explanation -=========== - -The point of illustration of this program is the static variable, `lastc`, which -gets initialized once as a static variable and maintains its state at each -invocation. The `getop` function declares the variable `lastc` and proceeds as -before. It calles `getch` to get the last character and if it is a `EOF` it -returns the EOF, if it a space ignores and if not a number, it returns -immediately and ensures that it parses a valid number. - -At the end, it verifies that the character read is not `EOF` and the stores the -last character which was read using `getch` in the `lastc` variable. - - -:: - - - - int getop(char s[]) - { - int c,i; - static int lastc = 0; - - if(lastc == 0) - c = getch(); - else - { - c = lastc; - lastc = 0; - } - - while((s[0]=c) == ' ' || c == '\t') - c = getch(); - - s[1]='\0'; - - if(!isdigit(c) && c!= '.') - return c; - - i = 0; - if(isdigit(c)) - while(isdigit(s[++i] =c=getch())) - ; - if(c=='.') - while(isdigit(s[++i] =c=getch())) - ; - s[i]='\0'; - - if(c!=EOF) - lastc=c; - - return NUMBER; - } - -The program execution looks like this. - -:: - - 10 10 + - 20 - 201 305 + 20 * - 10120 - - - -.. seealso:: - - * :c-suggest-improve:`Ex_4.11_getch_static.c` - * :c-better-explain:`Ex_4.11_getch_static.rst` diff --git a/source/cprogramming/Ex_4.12_recursive_itoa.rst b/source/cprogramming/Ex_4.12_recursive_itoa.rst deleted file mode 100644 index da74b830..00000000 --- a/source/cprogramming/Ex_4.12_recursive_itoa.rst +++ /dev/null @@ -1,62 +0,0 @@ -======================================================================== -Exercise 4.12 - convert integer into string by calling recursive routine -======================================================================== - -Question -======== - -Adapt the ideas of printd to write a recursive version of itoa; that is, convert -an integer into a string by calling a recursive routine. - -.. literalinclude:: ../../languages/cprogs/Ex_4.12_recursive_itoa.c - :language: c - :tab-width: 4 - -.. runcode:: ../../languages/cprogs/Ex_4.12_recursive_itoa.c - :language: c - :codesite: ideone - -Explanation -=========== - -The main part of this program is the `itoa` routine, which takes an `integer n` -and `string s` and is called recursively. - -:: - - void itoa(int n,char s[]) - { - static int i; - - if(n/10) - itoa(n/10,s); - else - { - i = 0; - if( n < 0) - s[i++]='-'; - } - - s[i++] = abs(n) % 10 + '0'; - - s[i] = '\0'; - - } - - -In the first invocation from the main program, this is called with `n = 1723` -and within the program the number n is divided by 10 (until it is less than 10), -and the new number (which is old number / 10) is called with `itoa` again. When -we reach the first digit of the number, the number is converted to a string -using `abs(n) % 10 + '0'` and stored in the s array. The array is closed with -`\0`, in subsequent recurssion, the next values like 7,2,3 will override \0 -stored from the previous iteration and in the last call of the recursion, the -number the complete number is transformed from integer to string. `s` will look -like `['1','7','2','8','\0']` and this will be printed in the main program. - - - -.. seealso:: - - * :c-suggest-improve:`Ex_4.12_recursive_itoa.c` - * :c-better-explain:`Ex_4.12_recursive_itoa.rst` diff --git a/source/cprogramming/Ex_4.13_reverse_string.rst b/source/cprogramming/Ex_4.13_reverse_string.rst deleted file mode 100644 index 99e5076c..00000000 --- a/source/cprogramming/Ex_4.13_reverse_string.rst +++ /dev/null @@ -1,56 +0,0 @@ -==================================== -Exercise 4.13 - reverse the string s -==================================== - -Question -======== - -Write a recursive version of the function reverse(s), which reverses the string -s in place. - -.. literalinclude:: ../../languages/cprogs/Ex_4.13_reverse_string.c - :language: c - :tab-width: 4 - -.. runcode:: ../../languages/cprogs/Ex_4.13_reverse_string.c - :language: c - :codesite: ideone - -Explanation -=========== - -The main part of this program is the reverser function. - -:: - - void reverser(char s[],int i,int len) - { - int c,j; - - j = len - (i + 1); - - if( i < j ) - { - c = s[i]; - s[i] = s[j]; - s[j] = c; - - reverser(s,++i,len); - } - } - - -The string to be reversed is taken in the character array `s` and the first -invocation is called with `i=0`. The value `len` stands for the length of the -string. During each invocation, `j` is calculated as `len - (i+1)`, which is the -character from the end which needs to be swapped and characters at `i is -swapped with j`. And then reverser is called again with the next value of i, -i.e, `++i`. This whole operation is done till i (from left hand side of the -string) is less than j (from the right end), i.e, `i < j`. - - - -.. seealso:: - - * :c-suggest-improve:`Ex_4.13_reverse_string.c` - * :c-better-explain:`Ex_4.13_reverse_string.rst` diff --git a/source/cprogramming/Ex_4.14_swap_t_x_y.rst b/source/cprogramming/Ex_4.14_swap_t_x_y.rst deleted file mode 100644 index ea10100d..00000000 --- a/source/cprogramming/Ex_4.14_swap_t_x_y.rst +++ /dev/null @@ -1,48 +0,0 @@ -============================================================== -Exercise 4.14 - swap that interchanges two arguments of type t -============================================================== - -Question -======== - -Define a macro swap(t,x,y) that interchanges two arguments of type t. - -.. literalinclude:: ../../languages/cprogs/Ex_4.14_swap_t_x_y.c - :language: c - :tab-width: 4 - -.. runcode:: ../../languages/cprogs/Ex_4.14_swap_t_x_y.c - :language: c - :codesite: ideone - -Explanation -=========== - -There are two types of macros in C namely object-like and function-like. In -object type, we do substitution and in function macros we can send a variable as -argument. In this program we are going to use function-like macro to swap. - -We do this by defining macro:: - - #define swap(t,x,y) { t _z; \ - _z = x;\ - x = y;\ - y = _z; } - -In the macro, we send type `t` as an argument and two variables `x` and `y` to -swap. We create a temperorary variable called `_z` of type `t` and use it to -swap `x` and `y`. - -References -========== - -* `More on C macros`_ - -.. _More on C macros: http://en.wikipedia.org/wiki/C_preprocessor#Macro_definition_and_expansion - - - -.. seealso:: - - * :c-suggest-improve:`Ex_4.14_swap_t_x_y.c` - * :c-better-explain:`Ex_4.14_swap_t_x_y.rst` diff --git a/source/cprogramming/Ex_4.1_strindex_rightmost.rst b/source/cprogramming/Ex_4.1_strindex_rightmost.rst deleted file mode 100644 index f201d1f6..00000000 --- a/source/cprogramming/Ex_4.1_strindex_rightmost.rst +++ /dev/null @@ -1,51 +0,0 @@ -======================================================== -Exercise 4.1- strindex which returns rightmost occurance -======================================================== - -Question -======== - -Write the function strindex(s,t) which returns the position of the rightmost -occurrence of t in s, or -1 if there is none. - -.. literalinclude:: ../../languages/cprogs/Ex_4.1_strindex_rightmost.c - :language: c - :tab-width: 4 - -.. runcode:: ../../languages/cprogs/Ex_4.1_strindex_rightmost.c - :language: c - :codesite: ideone - -Explanation -=========== - -We find the rightmost of index of our substring in this program. If we ask to -look for pattern "abc" in the line "abcdedfabcde", the program should correctly -identify the rightmost occurance which happens at position 7. - -This is done by our `mstringindex` function and in this loop. - -:: - - result = -1; - - for(i=0;s[i]!='\0';i++) - { - for(j=i,k=0;t[k]!='\0' && s[j]==t[k];j++,k++) - ; - if(k>0 && t[k] == '\0') - result = i; - } - -The outer loop goes over each character in string `s` and in the inner we check -if we find a substring `t` matching in the outer loop. If we find a substring -match, we **dont break** the loop, but record the position `i` and proceed -further. Thus our right most match is noted. If no search is found, then the -result, `-1` is returned. - - - -.. seealso:: - - * :c-suggest-improve:`Ex_4.1_strindex_rightmost.c` - * :c-better-explain:`Ex_4.1_strindex_rightmost.rst` diff --git a/source/cprogramming/Ex_4.2_atof_scientific.rst b/source/cprogramming/Ex_4.2_atof_scientific.rst deleted file mode 100644 index ec118ea8..00000000 --- a/source/cprogramming/Ex_4.2_atof_scientific.rst +++ /dev/null @@ -1,36 +0,0 @@ -======================================================== -Exercise 4.2 - Extend atof to handle scientific notation -======================================================== - -Question -======== - -Extend atof to handle scientific notation of the form 123.45e-6 where a -floating-point number may be followed by e or E and an optionally signed -exponent. - -.. literalinclude:: ../../languages/cprogs/Ex_4.2_atof_scientific.c - :language: c - :tab-width: 4 - -.. runcode:: ../../languages/cprogs/Ex_4.2_atof_scientific.c - :language: c - :codesite: ideone - -Explanation -=========== - -For the input:: - - 1.0e10 - -We might get the output:: - - 1410065408.000000 - - - -.. seealso:: - - * :c-suggest-improve:`Ex_4.2_atof_scientific.c` - * :c-better-explain:`Ex_4.2_atof_scientific.rst` diff --git a/source/cprogramming/Ex_4.3_rpn_modulus_negative.rst b/source/cprogramming/Ex_4.3_rpn_modulus_negative.rst deleted file mode 100644 index e4f67cd2..00000000 --- a/source/cprogramming/Ex_4.3_rpn_modulus_negative.rst +++ /dev/null @@ -1,62 +0,0 @@ -======================================================== -Exercise 4.3 - RPN modulus operator and negative numbers -======================================================== - -Question -======== - -Given the basic framework, it's straightforward to extend the calculator. Add -the modulus (%) operator and provisions for negative numbers. - -.. literalinclude:: ../../languages/cprogs/Ex_4.3_rpn_modulus_negative.c - :language: c - :tab-width: 4 - -.. runcode:: ../../languages/cprogs/Ex_4.3_rpn_modulus_negative.c - :language: c - :codesite: ideone - -Explanation -=========== - -This program has number of helper functions like getop, push and pop, which we -use to the implement the reverse polish notation calculator. - -The function getop takes a string and determines if it is number. If it is a -number, both integer or decimal, it will store that number in the array and -return a flag NUMBER which states that number is found. It will push that number -to the stack. If it getop returns an operator like +, -, * or /, it will pop two -numbers out of the stack and operate on it. When it encounters a /, it ensures -that the second operand is not 0 and disallows. - -It pushes each number to the stack and when it finds an operand, it will pop out -two numbers in the stack and operate on it and push the result back into the -stack. When it encounters a `\n` it will pop out the last stored number in the -stack and gives the result. - -Thus our operation of the RPN calculator for few inputs look like this. - - -:: - - 10 10 + 100 + 2 * - 240 - 500 2 * - 1000 - 100 3 / - 33.333333 - -10 -10 - - 0 - 20 -10 + - 10 - -20 10 + - -10 - -10 -10 + - -20 - - - -.. seealso:: - - * :c-suggest-improve:`Ex_4.3_rpn_modulus_negative.c` - * :c-better-explain:`Ex_4.3_rpn_modulus_negative.rst` diff --git a/source/cprogramming/Ex_4.4_rpn_top_two_elements.rst b/source/cprogramming/Ex_4.4_rpn_top_two_elements.rst deleted file mode 100644 index 098fef5a..00000000 --- a/source/cprogramming/Ex_4.4_rpn_top_two_elements.rst +++ /dev/null @@ -1,73 +0,0 @@ -=================================================================================== -Exercise 4.4 - RPN Calculator - print two top elements of the stack without popping -=================================================================================== - -Question -======== - -Add the commands to print the top elements of the stack without popping, to -duplicate it, and to swap the top two elements. Add a command to clear the -stack. - -.. literalinclude:: ../../languages/cprogs/Ex_4.4_rpn_top_two_elements.c - :language: c - :tab-width: 4 - -.. runcode:: ../../languages/cprogs/Ex_4.4_rpn_top_two_elements.c - :language: c - :codesite: ideone - -Explanation -=========== - -This program has number of helper functions like getop, push and pop, which we -use to the implement the reverse polish notation calculator. It enhances the RPN -calculator with additional features like `d` to double the entries of the top -two elements, `s` to swap the entries of the top two elements, `?` to display -the top element and finally `c` to clear the stack. - -The function getop takes a string and determines if it is number. If it is a -number, both integer or decimal, it will store that number in the array and -return a flag NUMBER which states that number is found. It will push that number -to the stack. If it getop returns an operator like +, -, * or /, it will pop two -numbers out of the stack and operate on it. When it encounters a /, it ensures -that the second operand is not 0 and disallows. - -It pushes each number to the stack and when it finds an operand, it will pop out -two numbers in the stack and operate on it and push the result back into the -stack. When it encounters a n it will pop out the last stored number in the -stack and gives the result. - -On d, It doubles the characters. - -On s, It swaps the characters. - -On c, It clears the characters in the stack. - -On ?, It goes to the top element of the stack. - -So here is how the expression is evaluated. - -:: - - 1 d + 3 s ? - 2 - 2 - ? - 3 - 3 - ? - -It takes 1 and `d` doubles it. So our stack will be `1 1`. And then when it sees -`+`, it will add the two values and substitute with the result. So our stack -will now be `2`. We push 3 to the stack and `s` swaps it. Our stack will be `3 -2`. So when we input `?` and enter. We get the top element `2` out. And then -pressing `?` again will pop next element `3`. - - - -.. seealso:: - - * :c-suggest-improve:`Ex_4.4_rpn_top_two_elements.c` - * :c-better-explain:`Ex_4.4_rpn_top_two_elements.rst` - diff --git a/source/cprogramming/Ex_4.5_calculator_math_functions.rst b/source/cprogramming/Ex_4.5_calculator_math_functions.rst deleted file mode 100644 index cd88a5ce..00000000 --- a/source/cprogramming/Ex_4.5_calculator_math_functions.rst +++ /dev/null @@ -1,59 +0,0 @@ -========================================================= -Exercise 4.5 - RPN Calculator with mathematical functions -========================================================= - -Question -======== - -Add access to library functions like sin, exp, and pow. - -.. literalinclude:: ../../languages/cprogs/Ex_4.5_calculator_math_functions.c - :language: c - :tab-width: 4 - -.. runcode:: ../../languages/cprogs/Ex_4.5_calculator_math_functions.c - :language: c - :codesite: ideone - -Explanation -=========== - -The RPN calculator has addition features like doing mathematical functions. In the input, if a string is given then the -calculator identifies it as a NAME and goes to the mathfun. - -In the mathfun, the string input is compared with "sin" and if it is a sin, the mathematical function `sin` is called on -the popped value. If the intput is `cos`, the cosine function is called and if the input is "pow", then first value is -popped and stored in `op2` and second value is raised to the power of op2. - - -The curx of program is in this function. - -:: - - void mathfnc(char s[]) - { - double op2; - - if(strcmp(s,"sin")==0) - push(sin(pop())); - else if(strcmp(s,"cos")==0) - push(cos(pop())); - else if(strcmp(s,"exp")==0) - push(exp(pop())); - else if(strcmp(s,"pow")==0) - { - op2 = pop(); - push(pow(pop(),op2)); - } - else - printf("error: %s is not supported\n",s); - } - - - - - -.. seealso:: - - * :c-suggest-improve:`Ex_4.5_calculator_math_functions.c` - * :c-better-explain:`Ex_4.5_calculator_math_functions.rst` diff --git a/source/cprogramming/Ex_4.6_calculator_variables.rst b/source/cprogramming/Ex_4.6_calculator_variables.rst deleted file mode 100644 index a3667eec..00000000 --- a/source/cprogramming/Ex_4.6_calculator_variables.rst +++ /dev/null @@ -1,46 +0,0 @@ -============================================ -Exercise 4.6 - RPN Calculator with variables -============================================ - -Question -======== - -Add commands for handling variables. (It's easy to provide twenty-six variables -with single-letter names.) Add a variable for the most recently printed value. - -.. literalinclude:: ../../languages/cprogs/Ex_4.6_calculator_variables.c - :language: c - :tab-width: 4 - -.. runcode:: ../../languages/cprogs/Ex_4.6_calculator_variables.c - :language: c - :codesite: ideone - -Explanation -=========== - -This adds variables to our RPN calculator. An example execution goes like this. - -:: - - 10 A = 20 B = A B + - 30 - v - 30 - - -The RPN notation for assigning to variables is like this `10 A =`. When an `=` -sign is encountered the previous value is popped and the value that is stored in -`var` variable (that is the previous one is taken) and then it's value is -assigned to the next popped variable. Thus two variables `A` and `B` are set in -the above expression. - -Then `A B +` acts as if we are acting on two numbers. A special variable `v` is -used to assign to the last printed value. - - - -.. seealso:: - - * :c-suggest-improve:`Ex_4.6_calculator_variables.c` - * :c-better-explain:`Ex_4.6_calculator_variables.rst` diff --git a/source/cprogramming/Ex_4.7_ungets.rst b/source/cprogramming/Ex_4.7_ungets.rst deleted file mode 100644 index d4fab0cb..00000000 --- a/source/cprogramming/Ex_4.7_ungets.rst +++ /dev/null @@ -1,46 +0,0 @@ -================================================================================== -Exercise 4.7 - Function ungets that will push back an entire string onto the input -================================================================================== - -Question -======== - -Write a routine ungets(s) that will push back an entire string onto the input. -Should ungets know about buf and bufp, or should it just use ungetch? - -.. literalinclude:: ../../languages/cprogs/Ex_4.7_ungets.c - :language: c - :tab-width: 4 - -.. runcode:: ../../languages/cprogs/Ex_4.7_ungets.c - :language: c - :codesite: ideone - -Explanation -=========== - -This program defines `ungets(s)`, which takes a string as an input and and -removes one character at a time from the back of the string and puts them into a -the buffer BUF. It does this, till all the characters from the input string are -placed onto the buffer. It uses the function `ungetch` to place to the buffer. - -When getch() is called, the characters from the buffer are read first and it is -output on the screen. - -So, when we write something like this. - -:: - - $ ./a.out - this is a sentence - this is a sentence - -The first sentence is read as input and placed in the BUF and the next sentence -is read using `getch()` from the BUF array. - - - -.. seealso:: - - * :c-suggest-improve:`Ex_4.7_ungets.c` - * :c-better-explain:`Ex_4.7_ungets.rst` diff --git a/source/cprogramming/Ex_4.8_getch_ungetch_pushback.rst b/source/cprogramming/Ex_4.8_getch_ungetch_pushback.rst deleted file mode 100644 index c273d583..00000000 --- a/source/cprogramming/Ex_4.8_getch_ungetch_pushback.rst +++ /dev/null @@ -1,33 +0,0 @@ -============================================================ -Exercise 4.8 - getch and ungetch handling pushback character -============================================================ - -Question -======== - -Suppose that there will never be more than one character of pushback. Modify -getch and ungetch accordingly. - - -.. literalinclude:: ../../languages/cprogs/Ex_4.8_getch_ungetch_pushback.c - :language: c - :tab-width: 4 - -.. runcode:: ../../languages/cprogs/Ex_4.8_getch_ungetch_pushback.c - :language: c - :codesite: ideone - -Explanation -=========== - -This program maintains a character buffer `char buf=0` which holds a single -character from the input. The function `ungetch(c)` when called places the -character in the input and `getch()`, if it finds the character in the buf, -returns it or it calls `getchar` to get character from the user. - - - -.. seealso:: - - * :c-suggest-improve:`Ex_4.8_getch_ungetch_pushback.c` - * :c-better-explain:`Ex_4.8_getch_ungetch_pushback.rst` diff --git a/source/cprogramming/Ex_4.9_getch_ungetch_eof.rst b/source/cprogramming/Ex_4.9_getch_ungetch_eof.rst deleted file mode 100644 index 1b674e02..00000000 --- a/source/cprogramming/Ex_4.9_getch_ungetch_eof.rst +++ /dev/null @@ -1,35 +0,0 @@ -======================================================= -Exercise 4.9 - getch and ungetch handling EOF Character -======================================================= - -Question -======== - -Our getch and ungetch do not handle a pushed-back EOF correctly. Decide what -their properties ought to be if an EOF is pushed back, then implement your -design. - -.. literalinclude:: ../../languages/cprogs/Ex_4.9_getch_ungetch_eof.c - :language: c - :tab-width: 4 - -.. runcode:: ../../languages/cprogs/Ex_4.9_getch_ungetch_eof.c - :language: c - :codesite: ideone - -Explanation -=========== - -The previous `getch` and `ungetch` functions declared buf as `char buf[BUFSIZ]`. -This has a limitation wherein the when an `EOF` character is encountered, it -wont be stored in the buffer. The EOF character is an integer type. This problem -can be solved by declaring our buf to be of integer type, like `int -buf[BUFSIZE]` and `ungetch(c)` will store the character c, including EOF, now in -an integer array. - - - -.. seealso:: - - * :c-suggest-improve:`Ex_4.9_getch_ungetch_eof.c` - * :c-better-explain:`Ex_4.9_getch_ungetch_eof.rst` diff --git a/source/cprogramming/Ex_5.10_exprcmd.rst b/source/cprogramming/Ex_5.10_exprcmd.rst deleted file mode 100644 index 88f73ec4..00000000 --- a/source/cprogramming/Ex_5.10_exprcmd.rst +++ /dev/null @@ -1,41 +0,0 @@ -==================================================== -Exercise 5.10 - expr, evaluate rpn from command line -==================================================== - -Question -======== - -Write the program expr, which evaluates a reverse Polish expression from the -command line, where each operator or operand is a separate argument. - -.. literalinclude:: ../../languages/cprogs/Ex_5.10_exprcmd.c - :language: c - :tab-width: 4 - -.. runcode:: ../../languages/cprogs/Ex_5.10_exprcmd.c - :language: c - :codesite: ideone - -Explanation -=========== - -This program reads the input to our rpn calculator from the command line itself. -`2 3 4 + *` and then goes about doing the RPN caculator work on it. - -The main function has a signature now, that is `int main(int argc, char -*argv[])`, that is it takes the command line args, **argc** for count of the -args and **argv** is the array which stores the arguments. - -So, 2, 3, 4, +, * will be stored in the array **agrv** as strings. In this -program, we go about by getting each argument from argv and then giving that as -the input to our RPN calculator, like the program in sec_4.3. If we find an -operand, using the push function, we push it to the stack and when we find a -operator in the input, we pop() the two operands out of the stack and do the -operation. - - - -.. seealso:: - - * :c-suggest-improve:`Ex_5.10_exprcmd.c` - * :c-better-explain:`Ex_5.10_exprcmd.rst` diff --git a/source/cprogramming/Ex_5.11_conddetab.rst b/source/cprogramming/Ex_5.11_conddetab.rst deleted file mode 100644 index f5a62afa..00000000 --- a/source/cprogramming/Ex_5.11_conddetab.rst +++ /dev/null @@ -1,47 +0,0 @@ -======================================================= -Exercise 5.11 - entab and detab which accepts arguments -======================================================= - -Question -======== - -Modify the program entab and detab (written as exercises in Chapter 1) to accept -a list of tab stops as arguments. Use the default tab settings if there are no -arguments. - -.. literalinclude:: ../../languages/cprogs/Ex_5.11_conddetab.c - :language: c - :tab-width: 4 - -.. runcode:: ../../languages/cprogs/Ex_5.11_conddetab.c - :language: c - :codesite: ideone - -Explanation -=========== - -This program is about accepting the arguments for entab and entab as command -line args. So the main program accepts argc and argv. - -The program is to take an argument like -m +n, which means tab stops every n -columns;starting at column m. - -So, the main program sends it to esettab function, both argc, argv and a -character array tab[MAXLINE-1]; - -If we had not given, m or n, it takes the TABINC of 8 and starts with the first -colummn and marking every TABINC position as tab (setting the value to YES) in -character array tab. If we give the values for m and n, it marks the -corresponding position in tab as 'yes'. - -This function only implements detab, which replaces the tab with spaces. So, -when a sentence is read with detab, the function consults `tabpos` function to -see if it s tab. If it is tab, then till it meets the next tab, it will output -space ' ', thus converting the tabs to spaces. - - - -.. seealso:: - - * :c-suggest-improve:`Ex_5.11_conddetab.c` - * :c-better-explain:`Ex_5.11_conddetab.rst` diff --git a/source/cprogramming/Ex_5.12_condientab.rst b/source/cprogramming/Ex_5.12_condientab.rst deleted file mode 100644 index 28e8097b..00000000 --- a/source/cprogramming/Ex_5.12_condientab.rst +++ /dev/null @@ -1,63 +0,0 @@ -================================================== -Exercise 5.12 - entab -m + which accepts arguments -================================================== - -Question -======== - -Extend entab and detab to accept the shorthand. - -.. literalinclude:: ../../languages/cprogs/Ex_5.12_condientab.c - :language: c - :tab-width: 4 - -.. runcode:: ../../languages/cprogs/Ex_5.12_condientab.c - :language: c - :codesite: ideone - -Explanation -=========== - -This program is similar to the Exercise 5.11, where we send the arguments to -entab and detab. So the main program accepts argc and argv. The program is to -take an argument like -m +n, which means tab stops every n columns;starting at -column m. - -The main program sends it to esettab function, both argc, argv and a character -array `tab[MAXLINE-1]`. - -esettab function's purpose is to fill the character array `tab` with values YES -(1) or NO(0). It determines from the arguments the -m , which is the POS and +n, -the increment, and marks at each `m`, the tab value as YES, and then increments -by `n`, and marks the next tab value as YES. If m and n are not provided, it -goes with sane defaults. - -The entab function implemented in this program, converts the spaces to tab -characters. So, the entab function, when it encounters a space character c, like -`if(c == ' ')`, it checks the corresponding position in the previously formed -`tab`, if the position value is `YES` or `NO`. If it is YES, then it increments -the tab count, `++nt`, if it is not tab position, it increments the blank count -`++nb`. - -When it encounters a first non-space character, then it checks it internal -variables, nt and nb. If `nt` is greater than 0, it meansm that we have tabs to -print, so it prints the tab characters for each nt count. It also prints the -literal tabs, it encounters. - -After printing it all the tabs, it checks the variable, `nb`, namely if we have -determined any blanks. If there blanks to be printed, it prints them out too. - -And finally, the prints the character using `putchar(c)`. - -We also have to handle cases when we encounter a newline character. When we -encounter a newline, like `\n`, we print the new line, but reset the position, -so that our position, `pos`, now becomes 0. When we encounter a tab character, -we increment the position (pos) to the next tab, so that when we encounter the -next space, we can verify it for the new position. - - - -.. seealso:: - - * :c-suggest-improve:`Ex_5.12_condientab.c` - * :c-better-explain:`Ex_5.12_condientab.rst` diff --git a/source/cprogramming/Ex_5.13_tailn.rst b/source/cprogramming/Ex_5.13_tailn.rst deleted file mode 100644 index 038da37a..00000000 --- a/source/cprogramming/Ex_5.13_tailn.rst +++ /dev/null @@ -1,53 +0,0 @@ -===================================================== -Exercise 5.13 - tail prints the last n lines of input -===================================================== - -Question -======== - -Write the program tail, which prints the last n lines of its input. - -.. literalinclude:: ../../languages/cprogs/Ex_5.13_tailn.c - :language: c - :tab-width: 4 - -.. runcode:: ../../languages/cprogs/Ex_5.13_tailn.c - :language: c - :codesite: ideone - -Explanation -=========== - -This program is to print the last n lines of a file, with default being last 10 -lines. The program sets aside an array of character pointers (strings) to store -the n lines. The LINES value below being the maximum number of lines that can -be printed, the default value being 100. - -:: - - char *lineptr[LINES]; /* pointer to lines read */ - -The program works by first allocating enough memory for the last n lines in a -buffer. Gets each line using `mgetline(line, MAXLEN)` and then copies each line -to an index entry in the lineptr array. - -:: - - strcpy(lineptr[last],line); - -It advances the pointer `last` at each copy, and when it exceed the maximum -count, it just rolls over, starting from 0. - -Next, we have to define the logic to print the last n lines. We offset line -value appropriately to the number of lines. It is either `last - n` lines and if -that value goes negative, then we increment it to max lines LINES. We start at -first value of line and as long as the the line number count represented by n -exists, we print the line, decrementing the count at each step. - - - - -.. seealso:: - - * :c-suggest-improve:`Ex_5.13_tailn.c` - * :c-better-explain:`Ex_5.13_tailn.rst` diff --git a/source/cprogramming/Ex_5.14_sortrevnum.rst b/source/cprogramming/Ex_5.14_sortrevnum.rst deleted file mode 100644 index 8cff5b02..00000000 --- a/source/cprogramming/Ex_5.14_sortrevnum.rst +++ /dev/null @@ -1,116 +0,0 @@ -===================================================== -Exercise 5.14 - sorting in reverse (decreasing) order -===================================================== - -Question -======== - -Modify the sort program to handle a -r flag, which indicates sorting in reverse -(decreasing) order. Be sure that -r works with -n. - -.. literalinclude:: ../../languages/cprogs/Ex_5.14_sortrevnum.c - :language: c - :tab-width: 4 - -.. runcode:: ../../languages/cprogs/Ex_5.14_sortrevnum.c - :language: c - :codesite: ideone - -Explanation -=========== - -This program when executed with flags `-nr` and when given an input in any order -will sort the arguments and print the numbers in reverse order. - -For .e.g, when given an input - -:: - - $ ./mysort -nr - 10 - 40 - 242 - 42 - 52 - -The output was:: - - 242 - 52 - 42 - 40 - 10 - - -The program works by implementing a version of quicksort. In quicksort, we give -two indices, left value (starting 0) and right value (nlines, the number of -lines), we send the array of strings (`char *lineptr[]`) to be sorted and then -we send a comparator function as a pointer too. - -The declartion of myqsort looks like this. - -:: - - void myqsort(void *v[],int left,int right,int (*comp)(void *,void *)); - -The comparator function, `numcmp` will return -1, if the first argument is less -than second, it will return 1, if the first argument is greater, otherwise it -will 0. This is a standard way in which many comparator functions are defined. - -In the execution of quicksort, it partitions the array into 2, and recursively, -sorts the left half and then the right half. - -Since we have to sort it "in-place", the details of the implementation needs -careful analysis. - -We choose the middle element and move it to extreme left (position 0), the -compare the values, starting with next element (at position 1) upto our right -pointer, the middle of the array. - -If we find any values which are less than our element (position 0), we swap it -to left, next to our left element and keep that counter as the last value. - -Thus for all the values less then our first element, we might have moved them to -left. - -For e.g. - -If our first iteration starts like this. - -:: - - 40 45 55 30 10 60 - ^ - left - -Our first few iterations will be:: - - 40 30 45 55 10 60 - ^ ^ - left last - - 40 30 10 45 55 60 - ^ ^ - left last - -And then finally we swap the left and last:: - - 10 30 40 45 55 60 - ^ ^ - last left - -Thus we have a partially sorted left side. Thus by carefully moving the pointers -we sorted the left side comparing each element with the middle element. -Similarly, we do the same for the right half of the array, and then recursively -divide each half to sort it. - -The curx of the program is in `myqsort`` function and once that is sorted, the -program displays the output as we desire. - - - - -.. seealso:: - - * :c-suggest-improve:`Ex_5.14_sortrevnum.c` - * :c-better-explain:`Ex_5.14_sortrevnum.rst` diff --git a/source/cprogramming/Ex_5.15_sortfnr.rst b/source/cprogramming/Ex_5.15_sortfnr.rst deleted file mode 100644 index fb0c482d..00000000 --- a/source/cprogramming/Ex_5.15_sortfnr.rst +++ /dev/null @@ -1,29 +0,0 @@ -================================================== -Exercise 5.15 - fold upper and lower case together -================================================== - -Question -======== - -Add the option -f to fold upper and lower case together, so that case -distinctions are not made during sorting; for example, a and A compare equal. - -.. literalinclude:: ../../languages/cprogs/Ex_5.15_sortfnr.c - :language: c - :tab-width: 4 - -.. runcode:: ../../languages/cprogs/Ex_5.15_sortfnr.c - :language: c - :codesite: ideone - - -Explanation -=========== - - - - -.. seealso:: - - * :c-suggest-improve:`Ex_5.15_sortfnr.c` - * :c-better-explain:`Ex_5.15_sortfnr.rst` diff --git a/source/cprogramming/Ex_5.16_sort_dfnr.rst b/source/cprogramming/Ex_5.16_sort_dfnr.rst deleted file mode 100644 index a5faf76c..00000000 --- a/source/cprogramming/Ex_5.16_sort_dfnr.rst +++ /dev/null @@ -1,27 +0,0 @@ -=============================================================== -Exercise 5.16 - -d makes comparison on letters, numbers, blanks -=============================================================== - -Question -======== - -Add the -d (``directory order``) option, which makes comparisons only on -letters, numbers and blanks. Make sure it works in conjunction with -f. - -.. literalinclude:: ../../languages/cprogs/Ex_5.16_sort_dfnr.c - :language: c - :tab-width: 4 - -.. runcode:: ../../languages/cprogs/Ex_5.16_sort_dfnr.c - :language: c - :codesite: ideone - -Explanation -=========== - - - -.. seealso:: - - * :c-suggest-improve:`Ex_5.16_sort_dfnr.c` - * :c-better-explain:`Ex_5.16_sort_dfnr.rst` diff --git a/source/cprogramming/Ex_5.17_sortdfnr-withoption.rst b/source/cprogramming/Ex_5.17_sortdfnr-withoption.rst deleted file mode 100644 index 7c9ea9fd..00000000 --- a/source/cprogramming/Ex_5.17_sortdfnr-withoption.rst +++ /dev/null @@ -1,29 +0,0 @@ -==================================== -Exercise 5.17 - Sorting with options -==================================== - -Question -======== - -Add a field-searching capability, so sorting may bee done on fields within -lines, each field sorted according to an independent set of options. (The index -for this book was sorted with -df for the index category and -n for the page -numbers.) - -.. literalinclude:: ../../languages/cprogs/Ex_5.17_sortdfnr-withoption.c - :language: c - :tab-width: 4 - -.. runcode:: ../../languages/cprogs/Ex_5.17_sortdfnr-withoption.c - :language: c - :codesite: ideone - -Explanation -=========== - - - -.. seealso:: - - * :c-suggest-improve:`Ex_5.17_sortdfnr-withoption.c` - * :c-better-explain:`Ex_5.17_sortdfnr-withoption.rst` diff --git a/source/cprogramming/Ex_5.18_dcl-errorec.rst b/source/cprogramming/Ex_5.18_dcl-errorec.rst deleted file mode 100644 index 5d9c903a..00000000 --- a/source/cprogramming/Ex_5.18_dcl-errorec.rst +++ /dev/null @@ -1,26 +0,0 @@ -========================================= -Exercise 5.18 - recover from input errors -========================================= - -Question -======== - -Make dcl recover from input errors. - -.. literalinclude:: ../../languages/cprogs/Ex_5.18_dcl-errorec.c - :language: c - :tab-width: 4 - -.. runcode:: ../../languages/cprogs/Ex_5.18_dcl-errorec.c - :language: c - :codesite: ideone - -Explanation -=========== - - - -.. seealso:: - - * :c-suggest-improve:`Ex_5.18_dcl-errorec.c` - * :c-better-explain:`Ex_5.18_dcl-errorec.rst` diff --git a/source/cprogramming/Ex_5.19_undcl.rst b/source/cprogramming/Ex_5.19_undcl.rst deleted file mode 100644 index bb81749f..00000000 --- a/source/cprogramming/Ex_5.19_undcl.rst +++ /dev/null @@ -1,26 +0,0 @@ -======================================================== -Exercise 5.19 - undcl does not add redundant parentheses -======================================================== - -Question -======== - -Modify undcl so that it does not add redundant parentheses to declarations. - -.. literalinclude:: ../../languages/cprogs/Ex_5.19_undcl.c - :language: c - :tab-width: 4 - -.. runcode:: ../../languages/cprogs/Ex_5.19_undcl.c - :language: c - :codesite: ideone - -Explanation -=========== - - - -.. seealso:: - - * :c-suggest-improve:`Ex_5.19_undcl.c` - * :c-better-explain:`Ex_5.19_undcl.rst` diff --git a/source/cprogramming/Ex_5.1_getint.rst b/source/cprogramming/Ex_5.1_getint.rst deleted file mode 100644 index 1645b708..00000000 --- a/source/cprogramming/Ex_5.1_getint.rst +++ /dev/null @@ -1,86 +0,0 @@ -================================================== -Exercise 5.1 - get next integer from input to \*pn -================================================== - -Question -======== - -As written, getint treats a + or - not followed by a digit as a valid -representation of zero. Fix it to push such a character back on the input. - -.. literalinclude:: ../../languages/cprogs/Ex_5.1_getint.c - :language: c - :tab-width: 4 - -.. runcode:: ../../languages/cprogs/Ex_5.1_getint.c - :language: c - :codesite: ideone - -Explanation -=========== - -We are to explain the function ``getint(int *)`` which takes a pointer to an -integer as the argument. We also use ``getch`` and ``ungetch`` as two functions, -from chapter 4, which work on ``buf`` of ``BUFSIZE`` sharing a global variable -called ``bufp``. ``ungetch`` function returns the character read to ``buf`` while -``getch`` tries to read that character to our program and if no character is -present, it uses ``getchar`` to get the character. - -In this program, we declare an ``array`` of size of 1000, and we send each digit -of the array to getint using a call like ``getint(&array[n])``. Our intention is -to load the characters in array with a valid integer format like ``+/-1234EOF``, -that is + or - 1234 and ending with EOF character. - -In getint function, we get a character and if it's space, we simply ignore it. -And this snippet. - -:: - - if(!isdigit(c) && c !=EOF && c!='+' && c!='-') - { - ungetch(c); /* it's not a number */ - return 0; - } - -Ensures that if we get a character which is not +,-, digit, EOF, then we return -0 and in the main loop we end the program. That is, we strictly look for -characters that can be converted to integer in this program. So the only valid -inputs are like this. - -:: - - 123 - +123 - -123 - -And if we get any invalid input. - -:: - - abc - %** - -Then the program will immediately end. - - -So, on a valid input, the initial check is done to see if there is a ``sign`` and -if yes, it stores the ``sign`` and then it goes about finding the next digit in a -for loop and calculates the number using this expression. - -:: - - *pn = 10 * *pn + (c-'0') - -This is responsible for converting the character like ``1`` to integer 1 and store -it in ``*pn``, the place in the array. We multiply the number by sign and when we -find EOF, we store that EOF, so that the program terminates correctly. - -Once the getint sees an EOF, we end the program and print the contents of the -array. - - - -.. seealso:: - - * :c-suggest-improve:`Ex_5.1_getint.c` - * :c-better-explain:`Ex_5.1_getint.rst` diff --git a/source/cprogramming/Ex_5.20_dcl-funcargs.rst b/source/cprogramming/Ex_5.20_dcl-funcargs.rst deleted file mode 100644 index a98cdde0..00000000 --- a/source/cprogramming/Ex_5.20_dcl-funcargs.rst +++ /dev/null @@ -1,27 +0,0 @@ -================================================================================== -Exercise 5.20 - dcl handling declarations with function argument types, qualifiers -================================================================================== - -Question -======== - -Expand dcl to handle declarations with function argument types, qualifiers like -const, and so on. - -.. literalinclude:: ../../languages/cprogs/Ex_5.20_dcl-funcargs.c - :language: c - :tab-width: 4 - -.. runcode:: ../../languages/cprogs/Ex_5.20_dcl-funcargs.c - :language: c - :codesite: ideone - -Explanation -=========== - - - -.. seealso:: - - * :c-suggest-improve:`Ex_5.20_dcl-funcargs.c` - * :c-better-explain:`Ex_5.20_dcl-funcargs.rst` diff --git a/source/cprogramming/Ex_5.2_getfloat.rst b/source/cprogramming/Ex_5.2_getfloat.rst deleted file mode 100644 index 8abd6408..00000000 --- a/source/cprogramming/Ex_5.2_getfloat.rst +++ /dev/null @@ -1,67 +0,0 @@ -================================================ -Exercise 5.2 - get next float from input to \*pn -================================================ - -Question -======== - -Write getfloat, the floating-point analog of getint. What type does getfloat -return as its function value? - -.. literalinclude:: ../../languages/cprogs/Ex_5.2_getfloat.c - :language: c - :tab-width: 4 - -.. runcode:: ../../languages/cprogs/Ex_5.2_getfloat.c - :language: c - :codesite: ideone - -Explanation -=========== - -The function `getfloat` is similar to the `getint` function, wherein instead of -getting an integer, we get a float value. - -We declare an array, `float array[SIZE]` in which we store the float values and -the the float value is got from the function `int getfloat(float *);` - -The function getfloat, sends a pointer to the float and stores a float value in -the array. The mechanism of how it gets a float is defined in the `getfloat` -function. - -The curx of how the float is got is in this snippet. The function reads all the -characters and converts to a float and stores them in the `*pn` pointer. Then it -reads the decimal part and for all the digits after the decimal point, it -increments the power by 10. For e.g. if the decimal was `0.123` for 3 decimal -digits, the power will be 10 * 10 * 10 = 1000. - - -:: - - for(*pn = 0.0 ; isdigit(c);c=getch()) - *pn = 10.0 * *pn + (c - '0'); - if( c == '.') - c = getch(); - - for(power=1.0;isdigit(c);c=getch()) - { - *pn = 10.0 * *pn + (c - '0'); /* fractional part */ - power *= 10.0; - } - - *pn *= sign / power; - - -Finally to get the decimal representation along with sign, then the number in pn -is divided by power and multiplied by sign, i.e, `*pn = ((*pn * sign) / power)` -and thus the correct float value is obtained. - -The float value is stored in the array index that was sent from the main -program. - - - -.. seealso:: - - * :c-suggest-improve:`Ex_5.2_getfloat.c` - * :c-better-explain:`Ex_5.2_getfloat.rst` diff --git a/source/cprogramming/Ex_5.3_strcat.rst b/source/cprogramming/Ex_5.3_strcat.rst deleted file mode 100644 index 9c54d787..00000000 --- a/source/cprogramming/Ex_5.3_strcat.rst +++ /dev/null @@ -1,55 +0,0 @@ -============================================================== -Exercise 5.3 - strcat(s,t) copies the string t to the end of s -============================================================== - -Question -======== - -Write a pointer version of the function strcat that we showed in Chapter 2: -strcat(s,t) copies the string t to the end of s. - -.. literalinclude:: ../../languages/cprogs/Ex_5.3_strcat.c - :language: c - :tab-width: 4 - -.. runcode:: ../../languages/cprogs/Ex_5.3_strcat.c - :language: c - :codesite: ideone - -Explanation -=========== - -This is a string concatenation program using pointers. The function mystrcat is -defined to take two strings as character pointers `mystrcat(char *s, char *t)` -and this function returns the concatenated string in `s` itself. - -The way it does is, the position in `s` is advanced till we meet a `\0` -character and then we append the characters from the string `t` to `s`, starting -from the `\0` character till we hit the end of the string `t` which is a `\0` -again. - - - -:: - - void mystrcat(char *s,char *t) - { - while(*s!='\0') - s++; - s--; /* goes back to \0 char */ - while((*s=*t)!='\0') - { - s++; - t++; - } - } - - -The construct `while((*s=*t)!='\0')` assigns the character in `t` to `s` and then checks if the character is `\0`. - - - -.. seealso:: - - * :c-suggest-improve:`Ex_5.3_strcat.c` - * :c-better-explain:`Ex_5.3_strcat.rst` diff --git a/source/cprogramming/Ex_5.4_strend.rst b/source/cprogramming/Ex_5.4_strend.rst deleted file mode 100644 index 3864c899..00000000 --- a/source/cprogramming/Ex_5.4_strend.rst +++ /dev/null @@ -1,85 +0,0 @@ -============================================================================= -Exercise 5.4 - strend returns 1 if string t occurs at the end of the string s -============================================================================= - -Question -======== - -Write the function strend(s,t), which returns 1 if the string t occurs at the -end of the string s, and zero otherwise. - -.. literalinclude:: ../../languages/cprogs/Ex_5.4_strend.c - :language: c - :tab-width: 4 - -.. runcode:: ../../languages/cprogs/Ex_5.4_strend.c - :language: c - :codesite: ideone - -Explanation -=========== - -This program determines if the string `t` occurs at the end of string `s`. So -the output of the program will look like. - -:: - - $ ./a.out - something - thing - 1 - - $ ./a.out - something - non - 0 - - -The primary part of this program is the `strend` function, which takes two -character pointers, `s` and `t`. It calculates the length of t and stores in the -variable len. And then, we back off till the last characters in both s and t. - -:: - - while(*s!='\0') - ++s; - --s; - - while(*t!='\0') - ++t; - - --t; - - -And then we look for the match from the end. This is checked in this while loop. -While the len is > 0, check if s and t are same and back off one character at a -time. - -:: - - - while(len > 0) - { - if(*t==*s) - { - --t; - --s; - --len; - } - else - return 0; - } - if( len == 0) - return 1; - - -If the string t exhausts, that is, it's length, len becomes 0, then we known -that string `t` occurs at the end of string `s` and we return 1. Otherwise, we -return 0. - - - -.. seealso:: - - * :c-suggest-improve:`Ex_5.4_strend.c` - * :c-better-explain:`Ex_5.4_strend.rst` diff --git a/source/cprogramming/Ex_5.5_strncpy.rst b/source/cprogramming/Ex_5.5_strncpy.rst deleted file mode 100644 index f610d8bf..00000000 --- a/source/cprogramming/Ex_5.5_strncpy.rst +++ /dev/null @@ -1,52 +0,0 @@ -=============================================================== -Exercise 5.5 - simple versions of strncpy, strncat, and strncmp -=============================================================== - -Question -======== - -Write versions of the library functions strncpy, strncat, and strncmp, which -operate on at most the first n characters of their argument strings. - -.. literalinclude:: ../../languages/cprogs/Ex_5.5_strncpy.c - :language: c - :tab-width: 4 - -.. runcode:: ../../languages/cprogs/Ex_5.5_strncpy.c - :language: c - :codesite: ideone - -Explanation -=========== - -mystrlen assigns the address of s to p in `char *p = s` and then goes one -character at a time, till it reaches \0. When it is at the end of the word, it -subtracts the current address s with intial address p, which thus returns the -len of string. - -mystrncpy copies n characters of source string to destination. It does this by -copying or overwriting one character a time from source to destination and -keeps track of count n. When source is exhausted or n characters are copied, it -checks if there further characters in destination, if it exists, it goes past -them without over-writing and then closes the string by \0. - -mystrncat, takes three arguments, str1, str2 and dest. It concatenates n -characters from str2 to str1 into a new string dest. It does this by copying all -characters from str1 to dest and then keeps a track of count n, and copies n -characters of str2 to dest. After copying n characters, it closes the dest -string by `\0` character. - -mystrncmp, compares the lhs string with rhs string. It compares one character at -a time and as long as both characters are same, it keeps going and if the lhs is -exhaused before n characters are compared, it means we still satisfy the -criteria and we return 0. Otherwise, it returns the difference between lhs -character and rhs character, which will be 0 if they are equal, negative if lhs -is smaller than rhs or positive value if lhs is greater than rhs. - - - - -.. seealso:: - - * :c-suggest-improve:`Ex_5.5_strncpy.c` - * :c-better-explain:`Ex_5.5_strncpy.rst` diff --git a/source/cprogramming/Ex_5.6_findpattern.rst b/source/cprogramming/Ex_5.6_findpattern.rst deleted file mode 100644 index 480d3574..00000000 --- a/source/cprogramming/Ex_5.6_findpattern.rst +++ /dev/null @@ -1,82 +0,0 @@ -============================================== -Exercise 5.6 - Find the pattern using pointers -============================================== - -Question -======== - -Rewrite appropriate programs from earlier chapters and exercises with pointers -instead of array indexing. Good possibilities include getline (Chapters 1 and -4), atoi, itoa, and their variants (Chapters 2, 3, and 4), reverse (Chapter 3), -and strindex and getop (Chapter 4). - -.. literalinclude:: ../../languages/cprogs/Ex_5.6_findpattern.c - :language: c - :tab-width: 4 - -.. runcode:: ../../languages/cprogs/Ex_5.6_findpattern.c - :language: c - :codesite: ideone - -Explanation -=========== - -mgetline takes a string ``(char *)`` and MAXLINE, the maximum length of the line. It -gets one character at a time using getchar() and as long as we are under limit -(less than MAXLINE) and it is not \n character. It stores the charaacters in the -line, advancing the pointer for each character. - -When it hits \n, it adds \n and closes the line with \0. mgetline returns the -length of the line, subtracting the last address with initial address. - - -atoi - the gets the sign and then read each read each character using the -pointer, checks if it is digit and converts it to integer. The curx of this -function is:: - - for(n=0;isdigit(*s);s++) - n = 10 *n + *s - '0'; - -itoa - takes the number, converts it into a string, by adding '0' and stores -them to a character pointer, advancing the pointer after each assignment. When -the assignments are done, it adds a null character to form a valid C string:: - - do - { - *s++ = n % 10 + '0'; - } while ((n /= 10) > 0); - - if(sign < 0) - *s++ = '-'; - *s='\0'; - - -reverse takes a ``char *s`` as argument and uses a temporary string ``char *t``, to -swap the characters from the end to the front. It uses another intermediate -character ``c`` to do the swap. - -strindex takes two strings ``char *s`` and ``char *t`` and determines the start of -the string t in s. It stores the s position in the base, b and then advances s -and for each advance checks if the substring t is contained in s. If the -substring is contained, it returns the current position - base position, that ``s --b``, otherwise it returns -1. - -getop works by taking a ``char *s`` as it's argument. It reads the character and -stores it in s. It skips the whitespaces and then checks if it isdigit. -If it not a digit, it closes the string using \0 and returns the character. - -If it is digit, then it reads both real and decimal part, along with dot, closes -the string using \0 and the returns that it found a NUMBER. - -Since checking of the character, happens after reading, an extra character is -read when our condition fails (that is we have completely read the NUMBER) In -that case, we do a ungetch, to return the character back to buffer and return -that we found a NUMBER. - - - - -.. seealso:: - - * :c-suggest-improve:`Ex_5.6_findpattern.c` - * :c-better-explain:`Ex_5.6_findpattern.rst` diff --git a/source/cprogramming/Ex_5.7_readlines_using_array.rst b/source/cprogramming/Ex_5.7_readlines_using_array.rst deleted file mode 100644 index 88fdcfac..00000000 --- a/source/cprogramming/Ex_5.7_readlines_using_array.rst +++ /dev/null @@ -1,32 +0,0 @@ -==================================== -Exercise 5.7 - Readlines using array -==================================== - -Question -======== - -Rewrite readlines to store lines in an array supplied by main, rather than -calling alloc to maintain storage. How much faster is the program? - - -.. literalinclude:: ../../languages/cprogs/Ex_5.7_readlines_using_array.c - :language: c - :tab-width: 4 - -.. runcode:: ../../languages/cprogs/Ex_5.7_readlines_using_array.c - :language: c - :codesite: ideone - -Explanation -=========== - -This uses the same qsort program. But instead of calculating the memory required -using the alloc operator. It sends a predefined amount of memory from the main -program. - - - -.. seealso:: - - * :c-suggest-improve:`Ex_5.7_readlines_using_array.c` - * :c-better-explain:`Ex_5.7_readlines_using_array.rst` diff --git a/source/cprogramming/Ex_5.8_day_date.rst b/source/cprogramming/Ex_5.8_day_date.rst deleted file mode 100644 index aa996ad3..00000000 --- a/source/cprogramming/Ex_5.8_day_date.rst +++ /dev/null @@ -1,44 +0,0 @@ -============================================================== -Exercise 5.8 - program which has day of the year and month day -============================================================== - -Question -======== - -There is no error checking in day_of_year or month_day. Remedy this defect. - -.. literalinclude:: ../../languages/cprogs/Ex_5.8_day_date.c - :language: c - :tab-width: 4 - -.. runcode:: ../../languages/cprogs/Ex_5.8_day_date.c - :language: c - :codesite: ideone - -Explanation -=========== - -Given a calendar date, we will determine how many days from the start of the -year is that date; we will also do the reverse, wherein give the days from the -start of the year, which date and month does it fall. - -We define the function `int day_of_year(int year,int month,int day)` which takes -the calendar date details like year, month and day. Using the year, it -determines if it is leap year. A year is a leap year, if it divisible by 4 and -but not by 100, except when it is divisible by 400. If it is leap year, we use -29 days in feb, otherwise it is 28. We store the number of days each month in a -static array `char daytab`, which we use in our calculations. - -In day_of_year, we add the days in eac month till our current month and then add -remain days and return. - -In the `month_day` function, we subtract days of each month from the day, till -the day is lesser than days in that month and then print the result that we got -after conversion. - - - -.. seealso:: - - * :c-suggest-improve:`Ex_5.8_day_date.c` - * :c-better-explain:`Ex_5.8_day_date.rst` diff --git a/source/cprogramming/Ex_5.9_day_date_using_pointers.rst b/source/cprogramming/Ex_5.9_day_date_using_pointers.rst deleted file mode 100644 index c42b90cd..00000000 --- a/source/cprogramming/Ex_5.9_day_date_using_pointers.rst +++ /dev/null @@ -1,34 +0,0 @@ -============================================================================= -Exercise 5.9 - program which has day of the year and month day using pointers -============================================================================= - -Question -======== - -Rewrite the routines day_of_year and month_day with pointers instead of -indexing. - -.. literalinclude:: ../../languages/cprogs/Ex_5.9_day_date_using_pointers.c - :language: c - :tab-width: 4 - -.. runcode:: ../../languages/cprogs/Ex_5.9_day_date_using_pointers.c - :language: c - :codesite: ideone - -Explanation -=========== - -This program is same as the previous program Exercise 5.8 and we calculate the -day of the year as before and return it to be printed in the main function. - -In the month_day, we send two additional pointers `int *pmonth,int *pday` and -after calculating the number of months and days, we return it using the pointers -itself to the main function instead of printing them in the function. - - - -.. seealso:: - - * :c-suggest-improve:`Ex_5.9_day_date_using_pointers.c` - * :c-better-explain:`Ex_5.9_day_date_using_pointers.rst` diff --git a/source/cprogramming/Ex_6.1_getword.rst b/source/cprogramming/Ex_6.1_getword.rst deleted file mode 100644 index 68e16335..00000000 --- a/source/cprogramming/Ex_6.1_getword.rst +++ /dev/null @@ -1,27 +0,0 @@ -====================== -Exercise 6.1 - getword -====================== - -Question -======== - -Our version of getword does not properly handle underscores, string constants, -comments, or preprocessor control lines. Write a better version. - -.. literalinclude:: ../../languages/cprogs/Ex_6.1_getword.c - :language: c - :tab-width: 4 - -.. runcode:: ../../languages/cprogs/Ex_6.1_getword.c - :language: c - :codesite: ideone - -Explanation -=========== - - - -.. seealso:: - - * :c-suggest-improve:`Ex_6.1_getword.c` - * :c-better-explain:`Ex_6.1_getword.rst` diff --git a/source/cprogramming/Ex_6.2_identical_variables.rst b/source/cprogramming/Ex_6.2_identical_variables.rst deleted file mode 100644 index 4c141d39..00000000 --- a/source/cprogramming/Ex_6.2_identical_variables.rst +++ /dev/null @@ -1,30 +0,0 @@ -================================== -Exercise 6.2 - Identical Variables -================================== - - -Question -======== - -Write a program that reads a C program and prints in alphabetical order each -group of variable names that are identical in the first 6 characters, but -different somewhere thereafter. Don't count words within strings and comments. -Make 6 a parameter that can be set from the command line. - -.. literalinclude:: ../../languages/cprogs/Ex_6.2_identical_variables.c - :language: c - :tab-width: 4 - -.. runcode:: ../../languages/cprogs/Ex_6.2_identical_variables.c - :language: c - :codesite: ideone - -Explanation -=========== - - - -.. seealso:: - - * :c-suggest-improve:`Ex_6.2_identical_variables.c` - * :c-better-explain:`Ex_6.2_identical_variables.rst` diff --git a/source/cprogramming/Ex_6.3.rst b/source/cprogramming/Ex_6.3.rst deleted file mode 100644 index bf31e59a..00000000 --- a/source/cprogramming/Ex_6.3.rst +++ /dev/null @@ -1,61 +0,0 @@ -=============================== -Exercise 6.3 - Cross Referencer -=============================== - -Question -======== - -Write a cross-referencer that prints a list of all words in a document, and for -each word, a list of the line numbers on which it occurs. Remove noise words -like ``the, and`` and so on. - -.. literalinclude:: ../../languages/cprogs/Ex_6.3.c - :language: c - :tab-width: 4 - -.. runcode:: ../../languages/cprogs/Ex_6.3.c - :language: c - :codesite: ideone - -Explanation -=========== - -Here is an example execution of this program. - -:: - - This is a - cross reference - word - document - creator - lists words and their line numbers. - Gets the word and puts their line numbers. - x - - Words with line numbers - - Gets :6, - This :0, - a :0, - and :5,6, - creator :4, - cross :1, - document :3, - is :0, - line :5,6, - lists :5, - numbers :5,6, - puts :6, - reference :1, - the :6, - their :5,6, - word :2,6, - words :5, - - - -.. seealso:: - - * :c-suggest-improve:`Ex_6.3.c` - * :c-better-explain:`Ex_6.3.rst` diff --git a/source/cprogramming/Ex_6.4.rst b/source/cprogramming/Ex_6.4.rst deleted file mode 100644 index b71e878f..00000000 --- a/source/cprogramming/Ex_6.4.rst +++ /dev/null @@ -1,44 +0,0 @@ -================================== -Exercise 6.4 - Words and Frequency -================================== - -Question -======== - -Write a program that prints the distinct words in its input sorted into -decreasing order of frequency of occurrence. Precede each word by its count. - -.. literalinclude:: ../../languages/cprogs/Ex_6.4.c - :language: c - :tab-width: 4 - -.. runcode:: ../../languages/cprogs/Ex_6.4.c - :language: c - :codesite: ideone - -Explanation -=========== - -:: - - ab - ab - bc - cd - ef - gh - ab - x - Words and their frequencies: - bc->1 - cd->1 - ef->1 - gh->1 - ab->3 - - - -.. seealso:: - - * :c-suggest-improve:`Ex_6.4.c` - * :c-better-explain:`Ex_6.4.rst` diff --git a/source/cprogramming/Ex_6.5.rst b/source/cprogramming/Ex_6.5.rst deleted file mode 100644 index 43cc6ab9..00000000 --- a/source/cprogramming/Ex_6.5.rst +++ /dev/null @@ -1,39 +0,0 @@ -=========================================================== -Exercise 6.5 - undef: remove name and definition from table -=========================================================== - -Question -======== - -Write a function undef that will remove a name and definition from the table -maintained by lookup and install. - -.. literalinclude:: ../../languages/cprogs/Ex_6.5.c - :language: c - :tab-width: 4 - -.. runcode:: ../../languages/cprogs/Ex_6.5.c - :language: c - :codesite: ideone - -Explanation -=========== - -Sample run of this program. - -:: - - key1->value1 - key2->value2 - key3->value3 - key not found - key1->value1 - key2->value2 - key not found - - - -.. seealso:: - - * :c-suggest-improve:`Ex_6.5.c` - * :c-better-explain:`Ex_6.5.rst` diff --git a/source/cprogramming/Ex_6.6.rst b/source/cprogramming/Ex_6.6.rst deleted file mode 100644 index 30da0777..00000000 --- a/source/cprogramming/Ex_6.6.rst +++ /dev/null @@ -1,35 +0,0 @@ -=============================== -Exercise 6.6 - define processor -=============================== - -Question -======== - -Implement a simple version of the #define processor (i.e., no arguments) -suitable for use with C programs, based on the routines of this section. You may -also find getch and ungetch helpful. - -.. literalinclude:: ../../languages/cprogs/Ex_6.6.c - :language: c - :tab-width: 4 - -.. runcode:: ../../languages/cprogs/Ex_6.6.c - :language: c - :codesite: ideone - -Explanation -=========== - -Example output. - -:: - - #define key value x - key->value - - - -.. seealso:: - - * :c-suggest-improve:`Ex_6.6.c` - * :c-better-explain:`Ex_6.6.rst` diff --git a/source/cprogramming/Ex_7.1_lower-upper.rst b/source/cprogramming/Ex_7.1_lower-upper.rst deleted file mode 100644 index e017181a..00000000 --- a/source/cprogramming/Ex_7.1_lower-upper.rst +++ /dev/null @@ -1,27 +0,0 @@ -========================================================= -Exercise 7.1 - upper case to lower or lower case to upper -========================================================= - -Question -======== - -Write a program that converts upper case to lower or lower case to upper, -depending on the name it is invoked with, as found in argv[0] - -.. literalinclude:: ../../languages/cprogs/Ex_7.1_lower-upper.c - :language: c - :tab-width: 4 - -.. runcode:: ../../languages/cprogs/Ex_7.1_lower-upper.c - :language: c - :codesite: ideone - -Explanation -=========== - - - -.. seealso:: - - * :c-suggest-improve:`Ex_7.1_lower-upper.c` - * :c-better-explain:`Ex_7.1_lower-upper.rst` diff --git a/source/cprogramming/Ex_7.2_nongraphic.rst b/source/cprogramming/Ex_7.2_nongraphic.rst deleted file mode 100644 index 6a0d50da..00000000 --- a/source/cprogramming/Ex_7.2_nongraphic.rst +++ /dev/null @@ -1,28 +0,0 @@ -=================================================================== -Exercise 7.2 - print non-graphic characters in octal or hexadecimal -=================================================================== - -Question -======== - -Write a program that will print arbitrary input in a sensible way. As a minimum, -it should print non-graphic characters in octal or hexadecimal according to -local custom, and break long text lines. - -.. literalinclude:: ../../languages/cprogs/Ex_7.2_nongraphic.c - :language: c - :tab-width: 4 - -.. runcode:: ../../languages/cprogs/Ex_7.2_nongraphic.c - :language: c - :codesite: ideone - -Explanation -=========== - - - -.. seealso:: - - * :c-suggest-improve:`Ex_7.2_nongraphic.c` - * :c-better-explain:`Ex_7.2_nongraphic.rst` diff --git a/source/cprogramming/Ex_7.3_minprintf.rst b/source/cprogramming/Ex_7.3_minprintf.rst deleted file mode 100644 index f2230fc8..00000000 --- a/source/cprogramming/Ex_7.3_minprintf.rst +++ /dev/null @@ -1,26 +0,0 @@ -======================================================= -Exercise 7.3 - minprintf to handle facilities of printf -======================================================= - -Question -======== - -Revise minprintf to handle more of the other facilities of printf. - -.. literalinclude:: ../../languages/cprogs/Ex_7.3_minprintf.c - :language: c - :tab-width: 4 - -.. runcode:: ../../languages/cprogs/Ex_7.3_minprintf.c - :language: c - :codesite: ideone - -Explanation -=========== - - - -.. seealso:: - - * :c-suggest-improve:`Ex_7.3_minprintf.c` - * :c-better-explain:`Ex_7.3_minprintf.rst` diff --git a/source/cprogramming/Ex_7.4.rst b/source/cprogramming/Ex_7.4.rst deleted file mode 100644 index c8447ba2..00000000 --- a/source/cprogramming/Ex_7.4.rst +++ /dev/null @@ -1,28 +0,0 @@ -======================================= -Exercise 7.4 - private version of scanf -======================================= - - -Question -======== - -Write a private version of scanf analogous to minprintf from the previous -section. - -.. literalinclude:: ../../languages/cprogs/Ex_7.4.c - :language: c - :tab-width: 4 - -.. runcode:: ../../languages/cprogs/Ex_7.4.c - :language: c - :codesite: ideone - -Explanation -=========== - - - -.. seealso:: - - * :c-suggest-improve:`Ex_7.4.c` - * :c-better-explain:`Ex_7.4.rst` diff --git a/source/cprogramming/Ex_7.5.rst b/source/cprogramming/Ex_7.5.rst deleted file mode 100644 index 6145d545..00000000 --- a/source/cprogramming/Ex_7.5.rst +++ /dev/null @@ -1,27 +0,0 @@ -============================================= -Exercise 7.5 - Postfix calculator using scanf -============================================= - -Question -======== - -Rewrite the postfix calculator of Chapter 4 to use scanf and/or sscanf to do the -input and number conversion. - -.. literalinclude:: ../../languages/cprogs/Ex_7.5.c - :language: c - :tab-width: 4 - -.. runcode:: ../../languages/cprogs/Ex_7.5.c - :language: c - :codesite: ideone - -Explanation -=========== - - - -.. seealso:: - - * :c-suggest-improve:`Ex_7.5.c` - * :c-better-explain:`Ex_7.5.rst` diff --git a/source/cprogramming/Ex_7.6.rst b/source/cprogramming/Ex_7.6.rst deleted file mode 100644 index 3a7d6f34..00000000 --- a/source/cprogramming/Ex_7.6.rst +++ /dev/null @@ -1,26 +0,0 @@ -================================ -Exercise 7.6 - Compare Two files -================================ - -Question -======== - -Write a program to compare two files, printing the first line where they differ. - -.. literalinclude:: ../../languages/cprogs/Ex_7.6.c - :language: c - :tab-width: 4 - -.. runcode:: ../../languages/cprogs/Ex_7.6.c - :language: c - :codesite: ideone - -Explanation -=========== - - - -.. seealso:: - - * :c-suggest-improve:`Ex_7.6.c` - * :c-better-explain:`Ex_7.6.rst` diff --git a/source/cprogramming/Ex_7.7.rst b/source/cprogramming/Ex_7.7.rst deleted file mode 100644 index b7e28eeb..00000000 --- a/source/cprogramming/Ex_7.7.rst +++ /dev/null @@ -1,28 +0,0 @@ -================================================== -Exercise 7.7 - Pattern matching program with files -================================================== - -Question -======== - -Modify the pattern finding program of Chapter 5 to take its input from a set of -named files or, if no files are named as arguments, from the standard input. -Should the file name be printed when a matching line is found? - -.. literalinclude:: ../../languages/cprogs/Ex_7.7.c - :language: c - :tab-width: 4 - -.. runcode:: ../../languages/cprogs/Ex_7.7.c - :language: c - :codesite: ideone - -Explanation -=========== - - - -.. seealso:: - - * :c-suggest-improve:`Ex_7.7.c` - * :c-better-explain:`Ex_7.7.rst` diff --git a/source/cprogramming/Ex_7.8.rst b/source/cprogramming/Ex_7.8.rst deleted file mode 100644 index 0dc5915f..00000000 --- a/source/cprogramming/Ex_7.8.rst +++ /dev/null @@ -1,28 +0,0 @@ -=================================== -Exercise 7.8 - Print Pages to Files -=================================== - -Question -======== - -Write a program to print a set of files, starting each new one on a new page, -with a title and a running page count for each file. - - -.. literalinclude:: ../../languages/cprogs/Ex_7.8.c - :language: c - :tab-width: 4 - -.. runcode:: ../../languages/cprogs/Ex_7.8.c - :language: c - :codesite: ideone - -Explanation -=========== - - - -.. seealso:: - - * :c-suggest-improve:`Ex_7.8.c` - * :c-better-explain:`Ex_7.8.rst` diff --git a/source/cprogramming/Ex_7.9.rst b/source/cprogramming/Ex_7.9.rst deleted file mode 100644 index 519e095d..00000000 --- a/source/cprogramming/Ex_7.9.rst +++ /dev/null @@ -1,27 +0,0 @@ -================================================= -Exercise 7.9 - Analyze implementations of isupper -================================================= - -Question -======== - -Functions like isupper can be implemented to save space or to save time. Explore -both possibilities. - -.. literalinclude:: ../../languages/cprogs/Ex_7.9.c - :language: c - :tab-width: 4 - -.. runcode:: ../../languages/cprogs/Ex_7.9.c - :language: c - :codesite: ideone - -Explanation -=========== - - - -.. seealso:: - - * :c-suggest-improve:`Ex_7.9.c` - * :c-better-explain:`Ex_7.9.rst` diff --git a/source/cprogramming/Ex_8.1_mycat.rst b/source/cprogramming/Ex_8.1_mycat.rst deleted file mode 100644 index 8df9a607..00000000 --- a/source/cprogramming/Ex_8.1_mycat.rst +++ /dev/null @@ -1,26 +0,0 @@ -============================================================ -Exercise 8.1 - program cat using read, write, open and close -============================================================ - -Question -======== - -Rewrite the program cat from Chapter 7 using read, write, open, and close -instead of their standard library equivalents. Perform experiments to determine -the relative speeds of the two versions. - -.. literalinclude:: ../../languages/cprogs/Ex_8.1_mycat.c - :language: c - :tab-width: 4 - - -Explanation -=========== - - - - -.. seealso:: - - * :c-suggest-improve:`Ex_8.1_mycat.c` - * :c-better-explain:`Ex_8.1_mycat.rst` diff --git a/source/cprogramming/Ex_8.2.rst b/source/cprogramming/Ex_8.2.rst deleted file mode 100644 index 0f4d7ecd..00000000 --- a/source/cprogramming/Ex_8.2.rst +++ /dev/null @@ -1,29 +0,0 @@ -===================================================== -Exercise 8.2 - Rewrite fopen and _fillbuf with fields -===================================================== - -Question -======== - -Rewrite fopen and _fillbuf with fields instead of explicit bit operations. -Compare code size and execution speed. - -**inprogress** - -.. literalinclude:: ../../languages/cprogs/Ex_8.2.c - :language: c - :tab-width: 4 - -.. runcode:: ../../languages/cprogs/Ex_8.2.c - :language: c - :codesite: ideone - -Explanation -=========== - - - -.. seealso:: - - * :c-suggest-improve:`Ex_8.2.c` - * :c-better-explain:`Ex_8.2.rst` diff --git a/source/cprogramming/Ex_8.3.rst b/source/cprogramming/Ex_8.3.rst deleted file mode 100644 index dd730aa1..00000000 --- a/source/cprogramming/Ex_8.3.rst +++ /dev/null @@ -1,28 +0,0 @@ -=========================================== -Exercise 8.3 - _flushbuf, fflush and fclose -=========================================== - -Question -======== - -Design and write _flushbuf, fflush, and fclose. - -**inprogress** - -.. literalinclude:: ../../languages/cprogs/Ex_8.3.c - :language: c - :tab-width: 4 - -.. runcode:: ../../languages/cprogs/Ex_8.3.c - :language: c - :codesite: ideone - -Explanation -=========== - - - -.. seealso:: - - * :c-suggest-improve:`Ex_8.3.c` - * :c-better-explain:`Ex_8.3.rst` diff --git a/source/cprogramming/Ex_8.4.rst b/source/cprogramming/Ex_8.4.rst deleted file mode 100644 index c24fb5f1..00000000 --- a/source/cprogramming/Ex_8.4.rst +++ /dev/null @@ -1,31 +0,0 @@ -============================== -Exercise 8.4 - implement fseek -============================== - -Question -======== - -The standard library function: - - ``int fseek(FILE *fp, long offset, int origin)`` - -**inprogress** - - -.. literalinclude:: ../../languages/cprogs/Ex_8.4.c - :language: c - :tab-width: 4 - -.. runcode:: ../../languages/cprogs/Ex_8.4.c - :language: c - :codesite: ideone - -Explanation -=========== - - - -.. seealso:: - - * :c-suggest-improve:`Ex_8.4.c` - * :c-better-explain:`Ex_8.4.rst` diff --git a/source/cprogramming/Ex_8.5_fsize.rst b/source/cprogramming/Ex_8.5_fsize.rst deleted file mode 100644 index fd9cd2af..00000000 --- a/source/cprogramming/Ex_8.5_fsize.rst +++ /dev/null @@ -1,28 +0,0 @@ -========================== -Exercise 8.5 - inode entry -========================== - -Question -======== - -Modify the fsize program to print the other information contained in the inode -entry. - - -.. literalinclude:: ../../languages/cprogs/Ex_8.5_fsize.c - :language: c - :tab-width: 4 - -.. runcode:: ../../languages/cprogs/Ex_8.5_fsize.c - :language: c - :codesite: ideone - -Explanation -=========== - - - -.. seealso:: - - * :c-suggest-improve:`Ex_8.5_fsize.c` - * :c-better-explain:`Ex_8.5_fsize.rst` diff --git a/source/cprogramming/Ex_8.6_calloc.rst b/source/cprogramming/Ex_8.6_calloc.rst deleted file mode 100644 index 98f084b3..00000000 --- a/source/cprogramming/Ex_8.6_calloc.rst +++ /dev/null @@ -1,28 +0,0 @@ -============================================== -Exercise 8.6 - Write calloc, by calling malloc -============================================== - -Question -======== - -The standard library function calloc(n,size) returns a pointer to n objects of -size size, with the storage initialized to zero. Write calloc, by calling malloc -or by modifying it. - -.. literalinclude:: ../../languages/cprogs/Ex_8.6_calloc.c - :language: c - :tab-width: 4 - -.. runcode:: ../../languages/cprogs/Ex_8.6_calloc.c - :language: c - :codesite: ideone - -Explanation -=========== - - - -.. seealso:: - - * :c-suggest-improve:`Ex_8.6_calloc.c` - * :c-better-explain:`Ex_8.6_calloc.rst` diff --git a/source/cprogramming/Ex_8.7_malloc.rst b/source/cprogramming/Ex_8.7_malloc.rst deleted file mode 100644 index e653e385..00000000 --- a/source/cprogramming/Ex_8.7_malloc.rst +++ /dev/null @@ -1,28 +0,0 @@ -======================================= -Exercise 8.7 - Error checking by malloc -======================================= - -Question -======== - -Malloc accepts a size request without checking its plausibility; free believes -that the block it is asked to free contains a valid size field. Improve these -routines so they make more pains with error checking. - -.. literalinclude:: ../../languages/cprogs/Ex_8.7_malloc.c - :language: c - :tab-width: 4 - -.. runcode:: ../../languages/cprogs/Ex_8.7_malloc.c - :language: c - :codesite: ideone - -Explanation -=========== - - - -.. seealso:: - - * :c-suggest-improve:`Ex_8.7_malloc.c` - * :c-better-explain:`Ex_8.7_malloc.rst` diff --git a/source/cprogramming/Ex_8.8_bfree.rst b/source/cprogramming/Ex_8.8_bfree.rst deleted file mode 100644 index 9320d33c..00000000 --- a/source/cprogramming/Ex_8.8_bfree.rst +++ /dev/null @@ -1,28 +0,0 @@ -========================================= -Exercise 8.8 - bfree maintained by malloc -========================================= - -Question -======== - -Write a routine bfree(p,n) that will free any arbitrary block p of n characters -into the free list maintained by malloc and free. By using bfree, a user can add -a static or external array to the free list at any time. - -.. literalinclude:: ../../languages/cprogs/Ex_8.8_bfree.c - :language: c - :tab-width: 4 - -.. runcode:: ../../languages/cprogs/Ex_8.8_bfree.c - :language: c - :codesite: ideone - -Explanation -=========== - - - -.. seealso:: - - * :c-suggest-improve:`Ex_8.8_bfree.c` - * :c-better-explain:`Ex_8.8_bfree.rst` diff --git a/source/cprogramming/Fibonacci.rst b/source/cprogramming/Fibonacci.rst deleted file mode 100644 index 96e218d9..00000000 --- a/source/cprogramming/Fibonacci.rst +++ /dev/null @@ -1,16 +0,0 @@ -========= -Fibonacci -========= - -*Fibonacci.c* - -.. literalinclude:: ../../languages/cprogs/Fibonacci.c - :language: c - :tab-width: 4 - - - -.. seealso:: - - * :c-suggest-improve:`Fibonacci.c` - * :c-better-explain:`Fibonacci.rst` diff --git a/source/cprogramming/alloc_afree.rst b/source/cprogramming/alloc_afree.rst deleted file mode 100644 index a0bfc890..00000000 --- a/source/cprogramming/alloc_afree.rst +++ /dev/null @@ -1,16 +0,0 @@ -=========== -alloc_afree -=========== - -*alloc_afree.c* - -.. literalinclude:: ../../languages/cprogs/alloc_afree.c - :language: c - :tab-width: 4 - - - -.. seealso:: - - * :c-suggest-improve:`alloc_afree.c` - * :c-better-explain:`alloc_afree.rst` diff --git a/source/cprogramming/anylonglinelen.rst b/source/cprogramming/anylonglinelen.rst deleted file mode 100644 index c579a1e3..00000000 --- a/source/cprogramming/anylonglinelen.rst +++ /dev/null @@ -1,16 +0,0 @@ -============== -anylonglinelen -============== - -*anylonglinelen.c* - -.. literalinclude:: ../../languages/cprogs/anylonglinelen.c - :language: c - :tab-width: 4 - - - -.. seealso:: - - * :c-suggest-improve:`anylonglinelen.c` - * :c-better-explain:`anylonglinelen.rst` diff --git a/source/cprogramming/append_identifiers.py b/source/cprogramming/append_identifiers.py deleted file mode 100644 index b4cb1d63..00000000 --- a/source/cprogramming/append_identifiers.py +++ /dev/null @@ -1,11 +0,0 @@ -import glob -list_of_files = glob.glob("*.rst") -for file_name in list_of_files: - if file_name.startswith('Ex') or file_name.startswith('sec') or file_name == 'append_identifiers.py': - continue - progname = file_name.split('.')[0] - with open(file_name, 'a') as fhandle: - fhandle.write("\n\n\n") - fhandle.write(".. seealso::\n\n") - fhandle.write("\t* :c-suggest-improve:`%s.c`\n" % progname) - fhandle.write("\t* :c-better-explain:`%s.rst`\n" % progname) diff --git a/source/cprogramming/atoiv2.rst b/source/cprogramming/atoiv2.rst deleted file mode 100644 index 92672e75..00000000 --- a/source/cprogramming/atoiv2.rst +++ /dev/null @@ -1,20 +0,0 @@ -====== -atoiv2 -====== - -*atoiv2.c* - -.. literalinclude:: ../../languages/cprogs/atoiv2.c - :language: c - :tab-width: 4 - - -.. raw:: html - - - - -.. seealso:: - - * :c-suggest-improve:`atoiv2.c` - * :c-better-explain:`atoiv2.rst` diff --git a/source/cprogramming/binsearch.rst b/source/cprogramming/binsearch.rst deleted file mode 100644 index 18e53297..00000000 --- a/source/cprogramming/binsearch.rst +++ /dev/null @@ -1,16 +0,0 @@ -========= -binsearch -========= - -*binsearch.c* - -.. literalinclude:: ../../languages/cprogs/binsearch.c - :language: c - :tab-width: 4 - - - -.. seealso:: - - * :c-suggest-improve:`binsearch.c` - * :c-better-explain:`binsearch.rst` diff --git a/source/cprogramming/bitcount.rst b/source/cprogramming/bitcount.rst deleted file mode 100644 index 1360df42..00000000 --- a/source/cprogramming/bitcount.rst +++ /dev/null @@ -1,16 +0,0 @@ -======== -bitcount -======== - -*bitcount.c* - -.. literalinclude:: ../../languages/cprogs/bitcount.c - :language: c - :tab-width: 4 - - - -.. seealso:: - - * :c-suggest-improve:`bitcount.c` - * :c-better-explain:`bitcount.rst` diff --git a/source/cprogramming/chapter1/cprogs/Ex_1.10_TbsBlnkSpaces.c b/source/cprogramming/chapter1/cprogs/ex_1.10_tbsblnkspaces.c similarity index 98% rename from source/cprogramming/chapter1/cprogs/Ex_1.10_TbsBlnkSpaces.c rename to source/cprogramming/chapter1/cprogs/ex_1.10_tbsblnkspaces.c index 14d434b4..f2562e6f 100644 --- a/source/cprogramming/chapter1/cprogs/Ex_1.10_TbsBlnkSpaces.c +++ b/source/cprogramming/chapter1/cprogs/ex_1.10_tbsblnkspaces.c @@ -2,8 +2,7 @@ * Exercise 1.10 - Write a Program to copy its input to its output, * replacing each tab by \t, each backspace by \b, and each backslash by \\. * This makes tabs and backspaces visible in an unambiguous way. - * - * */ + **/ #include diff --git a/source/cprogramming/chapter1/cprogs/Ex_1.13.2_His_vertical.c b/source/cprogramming/chapter1/cprogs/ex_1.13.2_his_vertical.c similarity index 100% rename from source/cprogramming/chapter1/cprogs/Ex_1.13.2_His_vertical.c rename to source/cprogramming/chapter1/cprogs/ex_1.13.2_his_vertical.c diff --git a/source/cprogramming/chapter1/cprogs/Ex_1.13_His_Horizontal.c b/source/cprogramming/chapter1/cprogs/ex_1.13_his_horizontal.c similarity index 100% rename from source/cprogramming/chapter1/cprogs/Ex_1.13_His_Horizontal.c rename to source/cprogramming/chapter1/cprogs/ex_1.13_his_horizontal.c diff --git a/source/cprogramming/chapter1/cprogs/Ex_1.14_Hist_Freq.c b/source/cprogramming/chapter1/cprogs/ex_1.14_hist_freq.c similarity index 100% rename from source/cprogramming/chapter1/cprogs/Ex_1.14_Hist_Freq.c rename to source/cprogramming/chapter1/cprogs/ex_1.14_hist_freq.c diff --git a/source/cprogramming/chapter1/cprogs/Ex_1.15_tempconv.c b/source/cprogramming/chapter1/cprogs/ex_1.15_tempconv.c similarity index 81% rename from source/cprogramming/chapter1/cprogs/Ex_1.15_tempconv.c rename to source/cprogramming/chapter1/cprogs/ex_1.15_tempconv.c index a2f85045..e3cddba6 100644 --- a/source/cprogramming/chapter1/cprogs/Ex_1.15_tempconv.c +++ b/source/cprogramming/chapter1/cprogs/ex_1.15_tempconv.c @@ -6,14 +6,15 @@ * **/ -#include < stdio.h > +#include #define LOWER 0 #define UPPER 300 #define STEP 20 -void fahrtocelsius(void); -void celsiustofahr(void); +void fahr_to_celsius(void); + +void celsius_to_fahr(void); int main(void) { int c; @@ -26,23 +27,23 @@ int main(void) { c = getchar(); if (c == '1') - fahrtocelsius(); + fahr_to_celsius(); else if (c == '2') - celsiustofahr(); + celsius_to_fahr(); else printf("Invalid Choice\n"); return 0; } -void fahrtocelsius() { +void fahr_to_celsius() { float fahr; for (fahr = LOWER; fahr <= UPPER; fahr = fahr + STEP) printf("%3.0f%6.1f\n", fahr, (5.0 / 9.0) * (fahr - 32.0)); } -void celsiustofahr() { +void celsius_to_fahr() { float celsius; for (celsius = LOWER; celsius <= UPPER; celsius = celsius + STEP) diff --git a/source/cprogramming/chapter1/cprogs/Ex_1.16_LongLine.c b/source/cprogramming/chapter1/cprogs/ex_1.16_longline.c similarity index 84% rename from source/cprogramming/chapter1/cprogs/Ex_1.16_LongLine.c rename to source/cprogramming/chapter1/cprogs/ex_1.16_longline.c index 594b8073..40be31e5 100644 --- a/source/cprogramming/chapter1/cprogs/Ex_1.16_LongLine.c +++ b/source/cprogramming/chapter1/cprogs/ex_1.16_longline.c @@ -12,8 +12,9 @@ #define MAX 1000 /* define our functions*/ -int getNewLine(char line[], int max); -void copy(char to[], char from[]); +int get_line(char arr[], int lim); + +void copy(char to[], const char from[]); int main() { @@ -22,7 +23,7 @@ int main() { char longest[MAX]; max = 0; - while ((len = getNewLine(line, MAX)) > 0) { + while ((len = get_line(line, MAX)) > 0) { if (len > max) { @@ -40,7 +41,7 @@ int main() { } /* get a line in a character array */ -int getNewLine(char arr[], int lim) { +int get_line(char arr[], int lim) { int c, i; @@ -53,9 +54,7 @@ int getNewLine(char arr[], int lim) { arr[i] = c; ++i; - } - - else { + } else { /* Continue to count the length even if it is longer than the max */ while ((c = getchar() != EOF) && c != '\n') { @@ -75,7 +74,7 @@ int getNewLine(char arr[], int lim) { } /* copy one character array to another */ -void copy(char to[], char from[]) { +void copy(char to[], const char from[]) { int i; diff --git a/source/cprogramming/chapter1/cprogs/Ex_1.17_lengt80.c b/source/cprogramming/chapter1/cprogs/ex_1.17_lengt80.c similarity index 67% rename from source/cprogramming/chapter1/cprogs/Ex_1.17_lengt80.c rename to source/cprogramming/chapter1/cprogs/ex_1.17_lengt80.c index 16db88ae..5873a15f 100644 --- a/source/cprogramming/chapter1/cprogs/Ex_1.17_lengt80.c +++ b/source/cprogramming/chapter1/cprogs/ex_1.17_lengt80.c @@ -12,18 +12,18 @@ /*** * - * We call it ngetline, for new getline so that it does not conflict with + * We call it _getline, for new getline so that it does not conflict with * system function getline * ***/ -int ngetline(char line[], int lim); +int _getline(char line[], int lim); int main(void) { int len; char line[MAXLINE]; - while ((len = ngetline(line, MAXLINE)) > 0) { + while ((len = _getline(line, MAXLINE)) > 0) { if (len > LIMIT) printf("%s", line); } @@ -31,17 +31,17 @@ int main(void) { return 0; } -int ngetline(char s[], int lim) { +int _getline(char line[], int lim) { int i, c; for (i = 0; i < lim - 1 && (c = getchar()) != EOF && c != '\n'; ++i) - s[i] = c; + line[i] = c; if (c == '\n') { - s[i] = c; + line[i] = c; ++i; } - s[i] = '\0'; + line[i] = '\0'; return i; } diff --git a/source/cprogramming/chapter1/cprogs/Ex_1.18_remtrailbt.c b/source/cprogramming/chapter1/cprogs/ex_1.18_remtrailbt.c similarity index 57% rename from source/cprogramming/chapter1/cprogs/Ex_1.18_remtrailbt.c rename to source/cprogramming/chapter1/cprogs/ex_1.18_remtrailbt.c index 76f20e98..4728c4a9 100644 --- a/source/cprogramming/chapter1/cprogs/Ex_1.18_remtrailbt.c +++ b/source/cprogramming/chapter1/cprogs/ex_1.18_remtrailbt.c @@ -9,52 +9,50 @@ #define MAXLINE 1000 -int mgetline(char line[], int lim); -int removetrail(char rline[]); +int _getline(char line[], int lim); + +int remove_trail(char rline[]); int main(void) { int len; char line[MAXLINE]; - while ((len = mgetline(line, MAXLINE)) > 0) - if (removetrail(line) > 0) + while ((len = _getline(line, MAXLINE)) > 0) + if (remove_trail(line) > 0) printf("%s", line); return 0; } -int mgetline(char s[], int lim) { +int _getline(char line[], int lim) { int i, c; for (i = 0; i < lim - 1 && (c = getchar()) != EOF && c != '\n'; ++i) - s[i] = c; + line[i] = c; if (c == '\n') { - s[i] = c; + line[i] = c; ++i; } - s[i] = '\0'; + line[i] = '\0'; return i; } /* To remove Trailing Blanks,tabs. Go to End and proceed backwards removing */ - -int removetrail(char s[]) { +int remove_trail(char rline[]) { int i; - for (i = 0; s[i] != '\n'; ++i) - ; + for (i = 0; rline[i] != '\n'; ++i); --i; /* To consider raw line without \n */ - for (i > 0; ((s[i] == ' ') || (s[i] == '\t')); --i) - ; /* Removing the Trailing Blanks and Tab Spaces */ + for (i > 0; ((rline[i] == ' ') || (rline[i] == '\t')); --i); /* Removing the Trailing Blanks and Tab Spaces */ if (i >= 0) /* Non Empty Line */ { ++i; - s[i] = '\n'; + rline[i] = '\n'; ++i; - s[i] = '\0'; + rline[i] = '\0'; } return i; } diff --git a/source/cprogramming/chapter1/cprogs/Ex_1.19_reversestr.c b/source/cprogramming/chapter1/cprogs/ex_1.19_reversestr.c similarity index 77% rename from source/cprogramming/chapter1/cprogs/Ex_1.19_reversestr.c rename to source/cprogramming/chapter1/cprogs/ex_1.19_reversestr.c index c5ea33e9..bf9509bf 100644 --- a/source/cprogramming/chapter1/cprogs/Ex_1.19_reversestr.c +++ b/source/cprogramming/chapter1/cprogs/ex_1.19_reversestr.c @@ -8,7 +8,7 @@ #define MAXLINE 1000 -int mgetline(char line[], int lim); +int _getline(char line[], int lim); void reverse(char rline[]); @@ -16,7 +16,7 @@ int main(void) { int len; char line[MAXLINE]; - while ((len = mgetline(line, MAXLINE)) > 0) { + while ((len = _getline(line, MAXLINE)) > 0) { reverse(line); printf("%s", line); } @@ -24,17 +24,17 @@ int main(void) { return 0; } -int mgetline(char s[], int lim) { +int _getline(char line[], int lim) { int i, c; for (i = 0; i < lim - 1 && (c = getchar()) != EOF && c != '\n'; ++i) - s[i] = c; + line[i] = c; if (c == '\n') { - s[i] = c; + line[i] = c; ++i; } - s[i] = '\0'; + line[i] = '\0'; return i; } @@ -43,8 +43,7 @@ void reverse(char rline[]) { int i, j; char temp; - for (i = 0; rline[i] != '\0'; ++i) - ; + for (i = 0; rline[i] != '\0'; ++i); --i; diff --git a/source/cprogramming/chapter1/cprogs/Ex_1.20_detab.c b/source/cprogramming/chapter1/cprogs/ex_1.20_detab.c similarity index 96% rename from source/cprogramming/chapter1/cprogs/Ex_1.20_detab.c rename to source/cprogramming/chapter1/cprogs/ex_1.20_detab.c index 92331121..952abf99 100644 --- a/source/cprogramming/chapter1/cprogs/Ex_1.20_detab.c +++ b/source/cprogramming/chapter1/cprogs/ex_1.20_detab.c @@ -1,9 +1,8 @@ /** - * Exercise 1.20 - + * Exercise 1.20 * * Write a Program detab, which replaces tabs in the input with a proper * number of blanks to spaces - * **/ #include diff --git a/source/cprogramming/chapter1/cprogs/Ex_1.21_entab.c b/source/cprogramming/chapter1/cprogs/ex_1.21_entab.c similarity index 100% rename from source/cprogramming/chapter1/cprogs/Ex_1.21_entab.c rename to source/cprogramming/chapter1/cprogs/ex_1.21_entab.c diff --git a/source/cprogramming/chapter1/cprogs/Ex_1.22_fold.c b/source/cprogramming/chapter1/cprogs/ex_1.22_fold.c similarity index 89% rename from source/cprogramming/chapter1/cprogs/Ex_1.22_fold.c rename to source/cprogramming/chapter1/cprogs/ex_1.22_fold.c index db7d58a1..2a558507 100644 --- a/source/cprogramming/chapter1/cprogs/Ex_1.22_fold.c +++ b/source/cprogramming/chapter1/cprogs/ex_1.22_fold.c @@ -1,7 +1,3 @@ -/* Exercise 1-22: Write a program to "fold" long input lines into two or more - shorter lines after the last non-blank character that occurs - before the n-th column of input. */ - #include #define MAXCOL 35 /* folded line length */ @@ -9,7 +5,18 @@ #define CURTAB(c) (TABVAL - ((c) % TABVAL)) /* current tab size */ #define NO_BLANK -1 /* signifies no blank found */ -int lastblank(const char arr[], int len); +/* finds the last whitespace character in an array + and returns the position */ +int lastblank(const char arr[], int len) { + int i, lbc; + + lbc = -1; + for (i = 0; i < len; ++i) + if (arr[i] == ' ' || arr[i] == '\t' || arr[i] == '\n') + lbc = i; + + return lbc; +} /* folds long input lines into two or more shorter lines */ int main(void) { @@ -55,17 +62,4 @@ int main(void) { } return 0; -} - -/* finds the last whitespace character in an array - and returns the position */ -int lastblank(const char arr[], int len) { - int i, lbc; - - lbc = -1; - for (i = 0; i < len; ++i) - if (arr[i] == ' ' || arr[i] == '\t' || arr[i] == '\n') - lbc = i; - - return lbc; -} +} \ No newline at end of file diff --git a/source/cprogramming/chapter1/cprogs/Ex_1.23_remcomments.c b/source/cprogramming/chapter1/cprogs/ex_1.23_remcomments.c similarity index 99% rename from source/cprogramming/chapter1/cprogs/Ex_1.23_remcomments.c rename to source/cprogramming/chapter1/cprogs/ex_1.23_remcomments.c index 34956ba6..547dc0e1 100644 --- a/source/cprogramming/chapter1/cprogs/Ex_1.23_remcomments.c +++ b/source/cprogramming/chapter1/cprogs/ex_1.23_remcomments.c @@ -10,7 +10,9 @@ #include void rcomment(int c); + void incomment(void); + void echo_quote(int c); int main(void) { diff --git a/source/cprogramming/chapter1/cprogs/Ex_1.24_synerrors.c b/source/cprogramming/chapter1/cprogs/ex_1.24_synerrors.c similarity index 99% rename from source/cprogramming/chapter1/cprogs/Ex_1.24_synerrors.c rename to source/cprogramming/chapter1/cprogs/ex_1.24_synerrors.c index dc2c52b2..f07012f7 100644 --- a/source/cprogramming/chapter1/cprogs/Ex_1.24_synerrors.c +++ b/source/cprogramming/chapter1/cprogs/ex_1.24_synerrors.c @@ -12,7 +12,9 @@ int brace, brack, paren; void incomment(); + void inquote(int c); + void search(int c); int main(void) { diff --git a/source/cprogramming/chapter1/cprogs/Ex_1.3_fahr2celheading.c b/source/cprogramming/chapter1/cprogs/ex_1.3_fahr2celheading.c similarity index 100% rename from source/cprogramming/chapter1/cprogs/Ex_1.3_fahr2celheading.c rename to source/cprogramming/chapter1/cprogs/ex_1.3_fahr2celheading.c diff --git a/source/cprogramming/chapter1/cprogs/Ex_1.4_cel2fahr.c b/source/cprogramming/chapter1/cprogs/ex_1.4_cel2fahr.c similarity index 100% rename from source/cprogramming/chapter1/cprogs/Ex_1.4_cel2fahr.c rename to source/cprogramming/chapter1/cprogs/ex_1.4_cel2fahr.c diff --git a/source/cprogramming/chapter1/cprogs/Ex_1.5_reverse.c b/source/cprogramming/chapter1/cprogs/ex_1.5_reverse.c similarity index 89% rename from source/cprogramming/chapter1/cprogs/Ex_1.5_reverse.c rename to source/cprogramming/chapter1/cprogs/ex_1.5_reverse.c index 6600ca08..1bf08ff7 100644 --- a/source/cprogramming/chapter1/cprogs/Ex_1.5_reverse.c +++ b/source/cprogramming/chapter1/cprogs/ex_1.5_reverse.c @@ -20,7 +20,7 @@ int main(void) { celsius = upper; while (celsius >= lower) { - fahr = (float)((9.0 / 5.0) * celsius + 32.0); + fahr = (float) ((9.0 / 5.0) * celsius + 32.0); printf("%3.0f %6.1f\n", celsius, fahr); celsius = celsius - step; } diff --git a/source/cprogramming/chapter1/cprogs/Ex_1.6_verifyeof.c b/source/cprogramming/chapter1/cprogs/ex_1.6_verifyeof.c similarity index 100% rename from source/cprogramming/chapter1/cprogs/Ex_1.6_verifyeof.c rename to source/cprogramming/chapter1/cprogs/ex_1.6_verifyeof.c diff --git a/source/cprogramming/chapter1/cprogs/Ex_1.7_eofval.c b/source/cprogramming/chapter1/cprogs/ex_1.7_eofval.c similarity index 100% rename from source/cprogramming/chapter1/cprogs/Ex_1.7_eofval.c rename to source/cprogramming/chapter1/cprogs/ex_1.7_eofval.c diff --git a/source/cprogramming/chapter1/cprogs/Ex_1.8_count_blanks_etc.c b/source/cprogramming/chapter1/cprogs/ex_1.8_count_blanks_etc.c similarity index 100% rename from source/cprogramming/chapter1/cprogs/Ex_1.8_count_blanks_etc.c rename to source/cprogramming/chapter1/cprogs/ex_1.8_count_blanks_etc.c diff --git a/source/cprogramming/chapter1/cprogs/Ex_1.9_SinBlank.c b/source/cprogramming/chapter1/cprogs/ex_1.9_sinblank.c similarity index 97% rename from source/cprogramming/chapter1/cprogs/Ex_1.9_SinBlank.c rename to source/cprogramming/chapter1/cprogs/ex_1.9_sinblank.c index 037bb705..904081c8 100644 --- a/source/cprogramming/chapter1/cprogs/Ex_1.9_SinBlank.c +++ b/source/cprogramming/chapter1/cprogs/ex_1.9_sinblank.c @@ -1,8 +1,7 @@ /** * Exercise 1.9 - Write a Program to copy its input to its output, replacing * each string of one or more blanks by a single blank. - * - * */ + **/ #include diff --git a/source/cprogramming/chapter1/cprogs/sec_1.10_external_variables.c b/source/cprogramming/chapter1/cprogs/sec_1.10_external_variables.c index ea4eec5b..44023f89 100644 --- a/source/cprogramming/chapter1/cprogs/sec_1.10_external_variables.c +++ b/source/cprogramming/chapter1/cprogs/sec_1.10_external_variables.c @@ -1,17 +1,42 @@ #include + #define MAXLINE 1000 /* maximum input line size */ + int max; /* maximum length seen so far */ char line[MAXLINE]; /* current input line */ char longest[MAXLINE]; /* longest line saved here */ -int getline(void); -void copy(void); + + +/* copy: specialized version */ +void copy(void) { + int i; + extern char line[], longest[]; + i = 0; + while ((longest[i] = line[i]) != '\0') + ++i; +} + +/* getline: specialized version */ +int mgetline(void) { + int c, i; + extern char line[]; + for (i = 0; i < MAXLINE - 1 && (c = getchar()) != EOF && c != '\n'; ++i) + line[i] = c; + if (c == '\n') { + line[i] = c; + ++i; + } + line[i] = '\0'; + return i; +} + /* print longest input line; specialized version */ -main() { +int main() { int len; extern int max; extern char longest[]; max = 0; - while ((len = getline()) > 0) + while ((len = mgetline()) > 0) if (len > max) { max = len; copy(); @@ -19,26 +44,4 @@ main() { if (max > 0) /* there was a line */ printf("%s", longest); return 0; -} -/* getline: specialized version */ -int getline(void) { - int c, i; - extern char line[]; - for (i = 0; i < MAXLINE - 1 && (c = getchar)) - != EOF &&c != '\n'; ++i) -line[i] = c; - if (c == '\n') { - line[i] = c; - ++i; - } - line[i] = '\0'; - return i; -} -/* copy: specialized version */ -void copy(void) { - int i; - extern char line[], longest[]; - i = 0; - while ((longest[i] = line[i]) != '\0') - ++i; -} +} \ No newline at end of file diff --git a/source/cprogramming/chapter1/cprogs/sec_1.1_helloworld.c b/source/cprogramming/chapter1/cprogs/sec_1.1_helloworld.c index ae683a3f..412103bd 100644 --- a/source/cprogramming/chapter1/cprogs/sec_1.1_helloworld.c +++ b/source/cprogramming/chapter1/cprogs/sec_1.1_helloworld.c @@ -2,4 +2,6 @@ #include -int main() { printf("hello, world\n"); } +int main() { + printf("hello, world\n"); +} diff --git a/source/cprogramming/chapter1/cprogs/sec_1.3_for_loop.c b/source/cprogramming/chapter1/cprogs/sec_1.3_for_loop.c index 9f65d56b..926d982b 100644 --- a/source/cprogramming/chapter1/cprogs/sec_1.3_for_loop.c +++ b/source/cprogramming/chapter1/cprogs/sec_1.3_for_loop.c @@ -1,6 +1,7 @@ #include + /* print Fahrenheit-Celsius table */ -main() { +int main() { int fahr; for (fahr = 0; fahr <= 300; fahr = fahr + 20) printf("%3d %6.1f\n", fahr, (5.0 / 9.0) * (fahr - 32)); diff --git a/source/cprogramming/chapter1/cprogs/sec_1.4_symbolic.c b/source/cprogramming/chapter1/cprogs/sec_1.4_symbolic.c index 192f6556..c188f89b 100644 --- a/source/cprogramming/chapter1/cprogs/sec_1.4_symbolic.c +++ b/source/cprogramming/chapter1/cprogs/sec_1.4_symbolic.c @@ -1,8 +1,9 @@ #include -#define LOWER 0 /* lower limit of table */ -#define UPPER 300 /* upper limit */ -#define STEP 20 /* step size */ -/* print Fahrenheit-Celsius table */ + +#define LOWER 0 +#define UPPER 300 +#define STEP 20 + int main() { int fahr; for (fahr = LOWER; fahr <= UPPER; fahr = fahr + STEP) diff --git a/source/cprogramming/chapter1/cprogs/sec_1.5.1_File_Copying.c b/source/cprogramming/chapter1/cprogs/sec_1.5.1_file_copying.c similarity index 99% rename from source/cprogramming/chapter1/cprogs/sec_1.5.1_File_Copying.c rename to source/cprogramming/chapter1/cprogs/sec_1.5.1_file_copying.c index ed63fb8e..04f2e966 100644 --- a/source/cprogramming/chapter1/cprogs/sec_1.5.1_File_Copying.c +++ b/source/cprogramming/chapter1/cprogs/sec_1.5.1_file_copying.c @@ -1,4 +1,5 @@ #include + int main() { int c; c = getchar(); diff --git a/source/cprogramming/chapter1/cprogs/sec_1.5.2_Character_Counting.c b/source/cprogramming/chapter1/cprogs/sec_1.5.2_character_counting.c similarity index 91% rename from source/cprogramming/chapter1/cprogs/sec_1.5.2_Character_Counting.c rename to source/cprogramming/chapter1/cprogs/sec_1.5.2_character_counting.c index d997f4f7..87264ab9 100644 --- a/source/cprogramming/chapter1/cprogs/sec_1.5.2_Character_Counting.c +++ b/source/cprogramming/chapter1/cprogs/sec_1.5.2_character_counting.c @@ -1,6 +1,7 @@ #include + /* count characters in input; 1st version */ -main() { +int main() { long nc; nc = 0; while (getchar() != EOF) diff --git a/source/cprogramming/chapter1/cprogs/sec_1.5.2_Character_Counting2.c b/source/cprogramming/chapter1/cprogs/sec_1.5.2_character_counting2.c similarity index 64% rename from source/cprogramming/chapter1/cprogs/sec_1.5.2_Character_Counting2.c rename to source/cprogramming/chapter1/cprogs/sec_1.5.2_character_counting2.c index 302ab6fa..8ec8df2f 100644 --- a/source/cprogramming/chapter1/cprogs/sec_1.5.2_Character_Counting2.c +++ b/source/cprogramming/chapter1/cprogs/sec_1.5.2_character_counting2.c @@ -1,8 +1,8 @@ #include + /* count characters in input; 2nd version */ -main() { +int main() { double nc; - for (nc = 0; getchar() != EOF; ++nc) - ; + for (nc = 0; getchar() != EOF; ++nc); printf("%.0f\n", nc); } diff --git a/source/cprogramming/chapter1/cprogs/sec_1.5.3_line_counting.c b/source/cprogramming/chapter1/cprogs/sec_1.5.3_line_counting.c index 90c1eddb..907a5084 100644 --- a/source/cprogramming/chapter1/cprogs/sec_1.5.3_line_counting.c +++ b/source/cprogramming/chapter1/cprogs/sec_1.5.3_line_counting.c @@ -1,6 +1,7 @@ #include + /* count lines in input */ -main() { +int main() { int c, nl; nl = 0; while ((c = getchar()) != EOF) diff --git a/source/cprogramming/chapter1/cprogs/sec_1.5.4_word_counting.c b/source/cprogramming/chapter1/cprogs/sec_1.5.4_word_counting.c index aede6112..5bfe4801 100644 --- a/source/cprogramming/chapter1/cprogs/sec_1.5.4_word_counting.c +++ b/source/cprogramming/chapter1/cprogs/sec_1.5.4_word_counting.c @@ -1,8 +1,10 @@ #include + #define IN 1 /* inside a word */ #define OUT 0 /* outside a word */ + /* count lines, words, and characters in input */ -main() { +int main() { int c, nl, nw, nc, state; state = OUT; nl = nw = nc = 0; diff --git a/source/cprogramming/chapter1/cprogs/sec_1.5_inp2ou.c b/source/cprogramming/chapter1/cprogs/sec_1.5_inp2ou.c index ed63fb8e..04f2e966 100644 --- a/source/cprogramming/chapter1/cprogs/sec_1.5_inp2ou.c +++ b/source/cprogramming/chapter1/cprogs/sec_1.5_inp2ou.c @@ -1,4 +1,5 @@ #include + int main() { int c; c = getchar(); diff --git a/source/cprogramming/chapter1/cprogs/sec_1.6_arrays.c b/source/cprogramming/chapter1/cprogs/sec_1.6_arrays.c index c26199cc..20bd0dd3 100644 --- a/source/cprogramming/chapter1/cprogs/sec_1.6_arrays.c +++ b/source/cprogramming/chapter1/cprogs/sec_1.6_arrays.c @@ -1,6 +1,7 @@ #include + /* count digits, white space, others */ -main() { +int main() { int c, i, nwhite, nother; int ndigit[10]; nwhite = nother = 0; diff --git a/source/cprogramming/chapter1/cprogs/sec_1.7_functions.c b/source/cprogramming/chapter1/cprogs/sec_1.7_functions.c index 34c7a283..c8db6ff5 100644 --- a/source/cprogramming/chapter1/cprogs/sec_1.7_functions.c +++ b/source/cprogramming/chapter1/cprogs/sec_1.7_functions.c @@ -1,12 +1,15 @@ #include -int power(int m, int n); + +int power(int base, int n); + /* test power function */ -main() { +int main() { int i; for (i = 0; i < 10; ++i) printf("%d %d %d\n", i, power(2, i), power(-3, i)); return 0; } + /* power: raise base to n-th power; n >= 0 */ int power(int base, int n) { int i, p; @@ -14,4 +17,4 @@ int power(int base, int n) { for (i = 1; i <= n; ++i) p = p * base; return p; -} +} \ No newline at end of file diff --git a/source/cprogramming/chapter1/cprogs/sec_1.9_character_arrays.c b/source/cprogramming/chapter1/cprogs/sec_1.9_character_arrays.c index 67a04bb8..70b9814a 100644 --- a/source/cprogramming/chapter1/cprogs/sec_1.9_character_arrays.c +++ b/source/cprogramming/chapter1/cprogs/sec_1.9_character_arrays.c @@ -1,9 +1,13 @@ #include + #define MAXLINE 1000 /* maximum input line length */ + int mgetline(char line[], int maxline); + void copy(char to[], char from[]); + /* print the longest input line */ -main() { +int main() { int len; /* current line length */ int max; /* maximum length seen so far */ char line[MAXLINE]; /* current input line */ @@ -18,18 +22,20 @@ main() { printf("%s", longest); return 0; } -/* mgetline: read a line into s, return length */ -int mgetline(char s[], int lim) { + +/* mgetline: read a line into line, return length */ +int mgetline(char line[], int maxline) { int c, i; - for (i = 0; i < lim - 1 && (c = getchar()) != EOF && c != '\n'; ++i) - s[i] = c; + for (i = 0; i < maxline - 1 && (c = getchar()) != EOF && c != '\n'; ++i) + line[i] = c; if (c == '\n') { - s[i] = c; + line[i] = c; ++i; } - s[i] = '\0'; + line[i] = '\0'; return i; } + /* copy: copy 'from' into 'to'; assume to is big enough */ void copy(char to[], char from[]) { int i; diff --git a/source/cprogramming/chapter1/ex_1.10_tbsblnkspaces.rst b/source/cprogramming/chapter1/ex_1.10_tbsblnkspaces.rst index 6eb9223b..8beeb648 100644 --- a/source/cprogramming/chapter1/ex_1.10_tbsblnkspaces.rst +++ b/source/cprogramming/chapter1/ex_1.10_tbsblnkspaces.rst @@ -12,7 +12,7 @@ visible in an unambiguous way. Solution -------- -.. literalinclude:: cprogs/ex_1.10_TbsBlnkSpaces.c +.. literalinclude:: cprogs/ex_1.10_tbsblnkspaces.c :language: c Explanation diff --git a/source/cprogramming/chapter1/ex_1.11_test_word_count.rst b/source/cprogramming/chapter1/ex_1.11_test_word_count.rst index baf4e935..2d97340e 100644 --- a/source/cprogramming/chapter1/ex_1.11_test_word_count.rst +++ b/source/cprogramming/chapter1/ex_1.11_test_word_count.rst @@ -29,5 +29,4 @@ consisting of \n, or a file entirely consisting of \t character or a empty file. For invalid Inputs, an unclosed file which does not have EOF, which is tricky to provide can be given to this program. A unicode character file can be given and -see if getchar() handles it properly. We tested it and it works. - +see if getchar() handles it properly. We tested it and it works. \ No newline at end of file diff --git a/source/cprogramming/chapter1/ex_1.13.2_his_vertical.rst b/source/cprogramming/chapter1/ex_1.13.2_his_vertical.rst index 8c215fd1..d6e122e6 100644 --- a/source/cprogramming/chapter1/ex_1.13.2_his_vertical.rst +++ b/source/cprogramming/chapter1/ex_1.13.2_his_vertical.rst @@ -12,7 +12,7 @@ the histogram with the bars vertical. Solution -------- -.. literalinclude:: cprogs/ex_1.13.2_His_vertical.c +.. literalinclude:: cprogs/ex_1.13.2_his_vertical.c :language: c @@ -88,4 +88,4 @@ we will have hit the bottom of the histogram:: '*''*''*''*' -Combing them all, we would have drawn the horizontal histogram like above. +Combing them all, we would have drawn the horizontal histogram like above. \ No newline at end of file diff --git a/source/cprogramming/chapter1/ex_1.15_tempconv.rst b/source/cprogramming/chapter1/ex_1.15_tempconv.rst index fdbf52de..19ae98e1 100644 --- a/source/cprogramming/chapter1/ex_1.15_tempconv.rst +++ b/source/cprogramming/chapter1/ex_1.15_tempconv.rst @@ -23,7 +23,7 @@ In this program we are going to convert a given Fahrenheit temperature to Celsius or Celsius temperature to Fahrenheit temperature using the formula C=(5/9)(F-32 ). We retain most of the program from section 1.4. In addition This program contains functions such as fahrtocelsius and celsiustofhar. The -functions fahrtocelsius and celsiustofhar are used to make the program more +functions fahr_to_celsius and celsiustofhar are used to make the program more dynamic by giving choices to the users for conversion between 1 - Fahrenheit to Celsius Conversion 2 - Celsius to Fahrenheit Converion. diff --git a/source/cprogramming/chapter1/ex_1.18_remtrailbt.rst b/source/cprogramming/chapter1/ex_1.18_remtrailbt.rst index 8ab84be1..10d63943 100644 --- a/source/cprogramming/chapter1/ex_1.18_remtrailbt.rst +++ b/source/cprogramming/chapter1/ex_1.18_remtrailbt.rst @@ -18,7 +18,7 @@ Solution Explanation =========== -In the removetrail function, we go to the very end of the line and the trace +In the remove_trail function, we go to the very end of the line and the trace back to the find the character which is not a space, tab and then replace it with \0. This eliminates the trailing blanks in a line. For the empty lines whose length is 0, we simply skip that from output and thus removing it. diff --git a/source/cprogramming/chapter1/ex_1.1_exp_helloworld.rst b/source/cprogramming/chapter1/ex_1.1_exp_helloworld.rst index 39bc7f81..cd641c13 100644 --- a/source/cprogramming/chapter1/ex_1.1_exp_helloworld.rst +++ b/source/cprogramming/chapter1/ex_1.1_exp_helloworld.rst @@ -46,4 +46,3 @@ error. :: error: expected `;` before the '}' token - diff --git a/source/cprogramming/chapter1/ex_1.3_fahr2celheading.rst b/source/cprogramming/chapter1/ex_1.3_fahr2celheading.rst index 7e3a1828..2915cf1f 100644 --- a/source/cprogramming/chapter1/ex_1.3_fahr2celheading.rst +++ b/source/cprogramming/chapter1/ex_1.3_fahr2celheading.rst @@ -8,7 +8,6 @@ Question Modify the temperature conversion program to print a heading above the table. - Solution -------- @@ -16,13 +15,13 @@ Solution :language: c Explanation -=========== +----------- In this program we are going to convert a given Fahrenheit temperature to Celsius temperature using the formula C=(5/9)(F-32) To do this we declare some variables in the beginning of the program so that they can be used in the later stages of the program. The variables in this program are: lower,upper,step, -celsius,fahr. The variable lower is assigned the value 0 similarly upper to 300, -step to 20, and fahr to lower. So when the program enters the while loop it -checks whether fahr <= upper is true, if it is true then it assigns the variable -celsius 5 * (fahr - 32) / 9 and then it prints output. +celsius,fahr. The variable lower is assigned the value 0 similarly upper to +300, step to 20, and fahr to lower. So when the program enters the while loop +it checks whether fahr <= upper is true, if it is true then it assigns the +variable celsius 5 * (fahr - 32) / 9 and then it prints output. diff --git a/source/cprogramming/chapter1/ex_1.6_verifyeof.rst b/source/cprogramming/chapter1/ex_1.6_verifyeof.rst index 4370f11b..81240918 100644 --- a/source/cprogramming/chapter1/ex_1.6_verifyeof.rst +++ b/source/cprogramming/chapter1/ex_1.6_verifyeof.rst @@ -14,7 +14,7 @@ Solution :language: c Explanation -=========== +----------- 1. This program is similar to the previous one Ex 1.5, wherein after it gets the input, it prints the value of the expression getchar() != EOF. diff --git a/source/cprogramming/chapter1/index.rst b/source/cprogramming/chapter1/index.rst index c6552b4f..5a19106a 100644 --- a/source/cprogramming/chapter1/index.rst +++ b/source/cprogramming/chapter1/index.rst @@ -8,7 +8,6 @@ Chapter 1 sec_1.1_helloworld ex_1.1_exp_helloworld sec_1.2_fahr2cel - ex_1.2_exp_printf_c sec_1.3_for_loop ex_1.3_fahr2celheading sec_1.4_symbolic @@ -30,7 +29,6 @@ Chapter 1 sec_1.10_external_variables ex_1.10_tbsblnkspaces ex_1.11_test_word_count - ex_1.12_word_per_line ex_1.13.2_his_vertical ex_1.13_his_horizontal ex_1.14_hist_freq @@ -43,4 +41,4 @@ Chapter 1 ex_1.21_entab ex_1.22_fold ex_1.23_remcomments - ex_1.24_synerrors + ex_1.24_synerrors \ No newline at end of file diff --git a/source/cprogramming/chapter1/sec_1.1_helloworld.rst b/source/cprogramming/chapter1/sec_1.1_helloworld.rst index 136f2695..462db5d7 100644 --- a/source/cprogramming/chapter1/sec_1.1_helloworld.rst +++ b/source/cprogramming/chapter1/sec_1.1_helloworld.rst @@ -20,11 +20,11 @@ Solution .. literalinclude:: cprogs/sec_1.1_helloworld.c :language: c +Extras +====== -Visualize It -============ +What really happens when you run hello world program? -.. raw:: html - - +Peek into the assembly code and jmps that happen with hello world as +demonstrated in this article https://thecoder08.github.io/hello-world.html diff --git a/source/cprogramming/chapter1/sec_1.2_fahr2cel.rst b/source/cprogramming/chapter1/sec_1.2_fahr2cel.rst index 159c24c6..6ae4202a 100644 --- a/source/cprogramming/chapter1/sec_1.2_fahr2cel.rst +++ b/source/cprogramming/chapter1/sec_1.2_fahr2cel.rst @@ -31,16 +31,3 @@ The variable lower is assigned the value 0 similarly upper to 300, step to 20, and fahr to lower. So when the program enters the while loop it checks whether fahr <= upper is true if it is true then it assigns the variable celsius 5 * (fahr - 32) / 9 and then it prints out put. - - -Understand ----------- - -.. raw:: html - - - - ----- - - Last Updated |today| diff --git a/source/cprogramming/chapter1/sec_1.4_symbolic.rst b/source/cprogramming/chapter1/sec_1.4_symbolic.rst index 778dda5e..481b9b75 100644 --- a/source/cprogramming/chapter1/sec_1.4_symbolic.rst +++ b/source/cprogramming/chapter1/sec_1.4_symbolic.rst @@ -20,8 +20,4 @@ to 300, STEP to 20. So when the program enters the for loop it checks whether fahr <= UPPER, and the increments fahr using STEP in each iteration. *symbolic constants* are substituted inline in the program during pre-processing -phase of compilation. - ----- - -This document was updated on |today| +phase of compilation. \ No newline at end of file diff --git a/source/cprogramming/chapter1/sec_1.5.1_file_copying.rst b/source/cprogramming/chapter1/sec_1.5.1_file_copying.rst index 0dafc13f..f0ec240f 100644 --- a/source/cprogramming/chapter1/sec_1.5.1_file_copying.rst +++ b/source/cprogramming/chapter1/sec_1.5.1_file_copying.rst @@ -7,11 +7,4 @@ Program .. literalinclude:: cprogs/sec_1.5.1_file_copying.c - :language: c - -Explanation ------------ - ----- - -This document was updated on |today| + :language: c \ No newline at end of file diff --git a/source/cprogramming/chapter1/sec_1.5.2_character_counting.rst b/source/cprogramming/chapter1/sec_1.5.2_character_counting.rst index a1e41940..c9719190 100644 --- a/source/cprogramming/chapter1/sec_1.5.2_character_counting.rst +++ b/source/cprogramming/chapter1/sec_1.5.2_character_counting.rst @@ -7,7 +7,7 @@ Program ------- -.. literalinclude:: cprogs/sec_1.5.2_Character_Counting.c +.. literalinclude:: cprogs/sec_1.5.2_character_counting.c :language: c Explanation diff --git a/source/cprogramming/chapter2/cprogs/Ex_2.1_cal_limits.c b/source/cprogramming/chapter2/cprogs/Ex_2.1_cal_limits.c deleted file mode 100644 index f54afa55..00000000 --- a/source/cprogramming/chapter2/cprogs/Ex_2.1_cal_limits.c +++ /dev/null @@ -1,66 +0,0 @@ -/*** - * - * Exercise 2.1 - * - * Program to print maximum, minimum limits of char, int, long using - * calculation - * - ***/ - -/* The logic used is - * ~0 will give bits in 1s. - * (unsigned ) will cast it unsigned. - * >> 1 right shifts 1 bit to remove the sign bit. - * () casting it the required type again - */ - -#include -#include -#include - -int main() { - /* ranges of various floating-point types through calculation */ - printf("Ranges of various floating-point types through calculation:\n"); - - printf("Minimum Signed Char %d\n", -(char)((unsigned char)~0 >> 1) - 1); - printf("Maximum Signed Char %d\n", (char)((unsigned char)~0 >> 1)); - - printf("Minimum Signed Short %d\n", -(short)((unsigned short)~0 >> 1) - 1); - printf("Maximum Signed Short %d\n", (short)((unsigned short)~0 >> 1)); - - printf("Minimum Signed Int %d\n", -(int)((unsigned int)~0 >> 1) - 1); - printf("Maximum Signed Int %d\n", (int)((unsigned int)~0 >> 1)); - - printf("Minimum Signed Long %ld\n", -(long)((unsigned long)~0 >> 1) - 1); - printf("Maximum signed Long %ld\n", (long)((unsigned long)~0 >> 1)); - - /* Unsigned Maximum Values */ - - printf("Maximum Unsigned Char %d\n", (unsigned char)~0); - printf("Maximum Unsigned Short %d\n", (unsigned short)~0); - printf("Maximum Unsigned Int %u\n", (unsigned int)~0); - printf("Maximum Unsigned Long %lu\n\n", (unsigned long)~0); - - /* ranges of various floating-point types from standard headers */ - printf("Ranges of various floating-point types from standard headers:\n"); - printf("Minimum Signed Char %d\n", SCHAR_MIN); - printf("Maximum Signed Char %d\n", SCHAR_MAX); - - printf("Minimum Signed Short %d\n", SHRT_MIN); - printf("Maximum Signed Short %d\n", SHRT_MAX); - - printf("Minimum Signed Int %d\n", INT_MIN); - printf("Maximum Signed Int %d\n", INT_MAX); - - printf("Minimum Signed Long %ld\n", LONG_MIN); - printf("Maximum signed Long %ld\n", LONG_MAX); - - /* Unsigned Maximum Values */ - - printf("Maximum Unsigned Char %d\n", UCHAR_MAX); - printf("Maximum Unsigned Short %d\n", USHRT_MAX); - printf("Maximum Unsigned Int %u\n", UINT_MAX); - printf("Maximum Unsigned Long %lu\n", ULONG_MAX); - - return 0; -} diff --git a/source/cprogramming/chapter2/cprogs/Ex_2.3_htoi.c b/source/cprogramming/chapter2/cprogs/Ex_2.3_htoi.c deleted file mode 100644 index 0950c32a..00000000 --- a/source/cprogramming/chapter2/cprogs/Ex_2.3_htoi.c +++ /dev/null @@ -1,68 +0,0 @@ -/** - * Exercise 2.3 - htoi program, character to integer program. - * - */ - -#include -#define MAXLINE 100 - -#define YES 1 -#define NO 0 - -int mgetline(char line[], int maxline); -int htoi(char s[]); - -int main(void) { - char line[MAXLINE]; - int value; - - mgetline(line, MAXLINE); - value = htoi(line); - - printf("The value of %s is %d", line, value); - - return 0; -} - -int mgetline(char s[], int lim) { - int c, i; - - for (i = 0; i < lim - 1 && (c = getchar()) != EOF && c != '\n'; ++i) - s[i] = c; - - if (c == '\n') { - s[i] = c; - ++i; - } - s[i] = '\0'; - - return i; -} - -int htoi(char s[]) { - int hexdigit, i, inhex, n; - i = 0; - if (s[i] == '0') { - ++i; - if (s[i] == 'x' || s[i] == 'X') - ++i; - } - - n = 0; - inhex = YES; - - for (; inhex == YES; ++i) { - if (s[i] >= '0' && s[i] <= '9') - hexdigit = s[i] - '0'; - else if (s[i] >= 'a' && s[i] <= 'f') - hexdigit = s[i] - 'a' + 10; - else if (s[i] >= 'A' && s[i] <= 'F') - hexdigit = s[i] - 'A' + 10; - else - inhex = NO; - - if (inhex == YES) - n = 16 * n + hexdigit; - } - return n; -} diff --git a/source/cprogramming/chapter2/cprogs/Ex_2.5_any.c b/source/cprogramming/chapter2/cprogs/Ex_2.5_any.c deleted file mode 100644 index 42f415f4..00000000 --- a/source/cprogramming/chapter2/cprogs/Ex_2.5_any.c +++ /dev/null @@ -1,63 +0,0 @@ -/** - * Exercise 2.5 - * - * Write the function any(s1,s2) which returns the first location in the string - * s1 where any character from the string s2 occurs, or -1 if s1 contains - * no characters from s2. ( The standard library function strpbrk does - * the same job but retuns a pointer to the location - * - **/ - -#include -#define MAXLINE 1000 - -int mgetline(char line[], int maxline); -int any(char s1[], char s2[]); - -int main(void) { - char s1[MAXLINE], s2[MAXLINE]; - int val; - - /* Give the first string s1 */ - - mgetline(s1, MAXLINE); - - /* Give the second string s2 */ - - mgetline(s2, MAXLINE); - - val = any(s1, s2); - - printf("%d", val); - - return 0; -} - -int mgetline(char s[], int lim) { - int i, c; - for (i = 0; i < lim - 1 && (c = getchar()) != EOF && c != '\n'; ++i) - s[i] = c; - - if (c == '\n') - s[i++] = c; - s[i] = '\0'; -} - -int any(char s1[], char s2[]) { - int i, j; - - for (i = 0; s1[i] != '\0'; ++i) { - // iterate through s2 while trying to find matching character from s1 - for (j = 0; (s1[i] != s2[j]) && s2[j] != '\0'; ++j) - ; // continue - - if (s2[j] != '\0' && - s2[j] != '\n') { // check that s2 [j]! = '\n', since s1 and s2 both - // have the character '\n' in the penultimate - // position of the string. - return i; - } - } - - return -1; -} \ No newline at end of file diff --git a/source/cprogramming/chapter2/cprogs/Ex_2.6_setbits.c b/source/cprogramming/chapter2/cprogs/Ex_2.6_setbits.c deleted file mode 100644 index f3cb0607..00000000 --- a/source/cprogramming/chapter2/cprogs/Ex_2.6_setbits.c +++ /dev/null @@ -1,16 +0,0 @@ -/** - * - * Exercise 2.6 - Write a function setbits(x,p,n,y) that returns x with the - * n bits that begin at positionp set to the rightmost n bits of y,leaving - * the other bits unchanged. - **/ - -#include - -unsigned setbits(unsigned x, int p, int n, unsigned y); - -int main(void) { printf("%u", setbits((unsigned)12, 3, 2, (unsigned)57)); } - -unsigned setbits(unsigned x, int p, int n, unsigned y) { - return x & ~(~(~0 << n) << (p + 1 - n)) | (y & (~(~0 << n)) << (p + 1 - n)); -} diff --git a/source/cprogramming/chapter2/cprogs/Ex_2.10_lowercondit.c b/source/cprogramming/chapter2/cprogs/ex_2.10_lowercondit.c similarity index 100% rename from source/cprogramming/chapter2/cprogs/Ex_2.10_lowercondit.c rename to source/cprogramming/chapter2/cprogs/ex_2.10_lowercondit.c diff --git a/source/cprogramming/chapter2/cprogs/ex_2.1_cal_limits.c b/source/cprogramming/chapter2/cprogs/ex_2.1_cal_limits.c new file mode 100644 index 00000000..053cbf30 --- /dev/null +++ b/source/cprogramming/chapter2/cprogs/ex_2.1_cal_limits.c @@ -0,0 +1,93 @@ +/** + * Exercise 2.1 + * + * Write a program to print maximum, minimum limits of char, int, long using + * calculation. + * + */ + +/** + * Preliminary Information: + * + * ~0 will give bits in 1s. + * >> 1 right shift by 1 bit to remove the sign bit. + * -1 is added to the maximum limit to get the minimum limit. + * + * The maximum and minimum limits of various integer types can be calculated + * using the following logic: + * + * 1. The maximum limit of a signed integer type can be calculated by + * (unsigned ) ~0 >> 1 + * + * 2. The minimum limit of a signed integer type can be calculated by + * ((unsigned ) ~0 >> 1) - 1 + * * + * 3. We cast it back to the required type with sign to print the value. + * + */ + +#include +#include +#include + +int main() { + /* ranges of various integer types through calculation */ + printf("Ranges of various integer types through calculation:\n"); + + printf("Minimum Signed Char %d\n", -(int)((unsigned char)~0 >> 1) - 1); + printf("Maximum Signed Char %d\n", (int)((unsigned char)~0 >> 1)); + + printf("Minimum Signed Short %d\n", -(int)((unsigned short)~0 >> 1) - 1); + printf("Maximum Signed Short %d\n", (int)((unsigned short)~0 >> 1)); + + printf("Minimum Signed Int %d\n", -(int)((unsigned int)~0 >> 1) - 1); + printf("Maximum Signed Int %d\n", (int)((unsigned int)~0 >> 1)); + + printf("Minimum Signed Long %ld\n", -(long)((unsigned long)~0 >> 1) - 1); + printf("Maximum signed Long %ld\n", (long)((unsigned long)~0 >> 1)); + + /* Unsigned Maximum Values */ + + printf("Maximum Unsigned Char %d\n", (unsigned char)~0); + printf("Maximum Unsigned Short %d\n", (unsigned short)~0); + printf("Maximum Unsigned Int %u\n", (unsigned int)~0); + printf("Maximum Unsigned Long %lu\n\n", (unsigned long)~0UL); + + /* Calculating max values of float types can be tricky, we can use the standard headers */ + + /* ranges of various floating-point types from standard headers */ + printf("Ranges of various integer and floating-point types from standard headers:\n"); + printf("Minimum Signed Char %d\n", SCHAR_MIN); + printf("Maximum Signed Char %d\n", SCHAR_MAX); + + printf("Minimum Signed Short %d\n", SHRT_MIN); + printf("Maximum Signed Short %d\n", SHRT_MAX); + + printf("Minimum Signed Int %d\n", INT_MIN); + printf("Maximum Signed Int %d\n", INT_MAX); + + printf("Minimum Signed Long %ld\n", LONG_MIN); + printf("Maximum signed Long %ld\n", LONG_MAX); + + printf("Minimum Signed Long Long %lld\n", LLONG_MIN); + printf("Maximum Signed Long Long %lld\n", LLONG_MAX); + + printf("Minimum Float %E\n", FLT_MIN); + printf("Maximum Float %E\n", FLT_MAX); + + printf("Minimum Double %E\n", DBL_MIN); + printf("Maximum Double %E\n", DBL_MAX); + + printf("Minimum Long Double %LE\n", LDBL_MIN); + printf("Maximum Long Double %LE\n", LDBL_MAX); + + /* Unsigned Maximum Values */ + + printf("Maximum Unsigned Char %d\n", UCHAR_MAX); + printf("Maximum Unsigned Short %d\n", USHRT_MAX); + printf("Maximum Unsigned Int %u\n", UINT_MAX); + printf("Maximum Unsigned Long %lu\n", ULONG_MAX); + printf("Maximum Unsigned Long Long %llu\n", ULLONG_MAX); + + return 0; +} \ No newline at end of file diff --git a/source/cprogramming/chapter2/cprogs/Ex_2.2_getline_without_and_or.c b/source/cprogramming/chapter2/cprogs/ex_2.2_getline_without_and_or.c similarity index 81% rename from source/cprogramming/chapter2/cprogs/Ex_2.2_getline_without_and_or.c rename to source/cprogramming/chapter2/cprogs/ex_2.2_getline_without_and_or.c index d1f24233..f0f4539f 100644 --- a/source/cprogramming/chapter2/cprogs/Ex_2.2_getline_without_and_or.c +++ b/source/cprogramming/chapter2/cprogs/ex_2.2_getline_without_and_or.c @@ -7,10 +7,12 @@ **/ #include + #define MAXLINE 1000 int mgetline(char line[], int lim); -void copy(char to[], char from[]); + +void copy(char to[], const char from[]); int main(void) { int len, max; @@ -29,7 +31,7 @@ int main(void) { printf("%s", maxline); } -int mgetline(char s[], int lim) { +int mgetline(char line[], int lim) { int i, c; for (i = 0; i < lim - 1; ++i) { @@ -38,19 +40,19 @@ int mgetline(char s[], int lim) { break; if (c == '\n') break; - s[i] = c; + line[i] = c; } if (c == '\n') { - s[i] = c; + line[i] = c; ++i; } - s[i] = '\0'; + line[i] = '\0'; return i; } -void copy(char to[], char from[]) { +void copy(char to[], const char from[]) { int i; i = 0; diff --git a/source/cprogramming/chapter2/cprogs/ex_2.3_htoi.c b/source/cprogramming/chapter2/cprogs/ex_2.3_htoi.c new file mode 100644 index 00000000..e3c19907 --- /dev/null +++ b/source/cprogramming/chapter2/cprogs/ex_2.3_htoi.c @@ -0,0 +1,62 @@ +/** + * Exercise 2.3 - htoi program, character to integer program. + * + */ + +#include + +#define MAXLINE 100 +#define BASE 16 + +int mgetline(char line[], int lim); + +unsigned int htoi(const char s[], int len); + +int main(void) { + char line[MAXLINE]; + int len; + unsigned int value; + + len = mgetline(line, MAXLINE); + value = htoi(line, len); + + printf("The value of %s is %u \n", (char *) line, value); + + return 0; +} + +int mgetline(char line[], int lim) { + int c, i; + + for (i = 0; i < lim - 1 && (c = getchar()) != EOF && c != '\n'; ++i) + line[i] = (char) c; + + line[i] = '\0'; + + return i; +} + +unsigned int htoi(const char s[], int len) { + int digit; + int power = 1; + unsigned int result = 0; + int end_index = 0; + + if (s[0] == '0' && (s[1] == 'x' || s[1] == 'X')) { + end_index = 2; + } + + for(int i=len-1; i>=end_index; i--) { + if (s[i] >= '0' && s[i] <= '9') { + digit = (s[i] - '0'); + } else if (s[i] >= 'a' && s[i] <= 'f') { + digit = (s[i] - 'a') + 10; + } else if (s[i] >= 'A' && s[i] <= 'F') { + digit = (s[i] - 'A') + 10; + } + result += digit * power; + power *= BASE; + } + + return result; +} \ No newline at end of file diff --git a/source/cprogramming/chapter2/cprogs/Ex_2.4_squeezess.c b/source/cprogramming/chapter2/cprogs/ex_2.4_squeezess.c similarity index 72% rename from source/cprogramming/chapter2/cprogs/Ex_2.4_squeezess.c rename to source/cprogramming/chapter2/cprogs/ex_2.4_squeezess.c index afb0dd93..3c91036f 100644 --- a/source/cprogramming/chapter2/cprogs/Ex_2.4_squeezess.c +++ b/source/cprogramming/chapter2/cprogs/ex_2.4_squeezess.c @@ -2,30 +2,28 @@ * Exercise 2.4 * * Let us write a version of squeeze(s1,s2) that deletes each - * character in the string 1 that matches any character in the string s2 + * character in the string 1 that matches any character in the string s2. + * Utilize user defined function mgetline to input the strings. + * Don't use any standard library string manipulation function. * **/ #include + #define MAXLINE 1000 -int mgetline(char line[], int maxline); -void squeeze(char s1[], char s2[]); +int mgetline(char s[], int lim); + +void squeeze(char s1[], const char s2[]); int main(void) { char s1[MAXLINE], s2[MAXLINE]; - - putchar('s'); - putchar('1'); mgetline(s1, MAXLINE); - - putchar('s'); - putchar('2'); mgetline(s2, MAXLINE); squeeze(s1, s2); - printf("%s", s1); + printf("\n%s\n", s1); return 0; } @@ -40,9 +38,11 @@ int mgetline(char s[], int lim) { s[i++] = c; s[i] = '\0'; + + return i; } -void squeeze(char s1[], char s2[]) { +void squeeze(char s1[], const char s2[]) { int i, j, k; k = 0; @@ -54,4 +54,4 @@ void squeeze(char s1[], char s2[]) { } s1[k] = '\0'; -} +} \ No newline at end of file diff --git a/source/cprogramming/chapter2/cprogs/ex_2.5_any.c b/source/cprogramming/chapter2/cprogs/ex_2.5_any.c new file mode 100644 index 00000000..072ec593 --- /dev/null +++ b/source/cprogramming/chapter2/cprogs/ex_2.5_any.c @@ -0,0 +1,57 @@ +/** + * Exercise 2.5 + * + * Write the function any(s1,s2) which returns the first location in the string + * s1 where any character from the string s2 occurs, or -1 if s1 contains + * no characters from s2. ( The standard library function strpbrk does + * the same job but returns a pointer to the location + * + **/ + +#include + +#define MAXLINE 1000 + +int mgetline(char line[], int lim); + +int any(char s1[], const char s2[]); + +int main(void) { + char s1[MAXLINE], s2[MAXLINE]; + int val; + + mgetline(s1, MAXLINE); + mgetline(s2, MAXLINE); + + val = any(s1, s2); + + printf("%d", val); + + return 0; +} + +int mgetline(char line[], int lim) { + int i, c; + for (i = 0; i < lim - 1 && (c = getchar()) != EOF && c != '\n'; ++i) + line[i] = c; + + if (c == '\n') + line[i++] = c; + line[i] = '\0'; + + return i; +} + +int any(char s1[], const char s2[]) { + int i, j; + + for (i = 0; s1[i] != '\0'; ++i) { + for (j = 0; s2[j] != '\0'; ++j) { + if (s1[i] == s2[j] && s1[i] != '\n') { + return i; + } + } + } + + return -1; +} diff --git a/source/cprogramming/chapter2/cprogs/ex_2.6_setbits.c b/source/cprogramming/chapter2/cprogs/ex_2.6_setbits.c new file mode 100644 index 00000000..ce639ba3 --- /dev/null +++ b/source/cprogramming/chapter2/cprogs/ex_2.6_setbits.c @@ -0,0 +1,31 @@ +/** + * + * Exercise 2.6 - Write a function setbits(x,p,n,y) that returns x with the + * n bits that begin at position p set to the rightmost n bits of y,leaving + * the other bits unchanged. + **/ + +#include +#include + +unsigned setbits(unsigned x, int p, int n, unsigned y); + +unsigned setbits(unsigned x, int p, int n, unsigned y) { + return x & ((~0 << p + 1) | ~(~0 << p + 1 - n)) | ((y & ~(~0 << n)) << p + 1 - n); +} + + +int main(void) { + + printf("%u", setbits((unsigned)12, 3, 2, (unsigned)57)); + + assert(setbits(0x2, 2, 2, 0xD) == 0x2); /* x=00000(01)0 y=000011(01) : equal to x */ + assert(setbits(0x2, 0, 0, 0xD) == 0x2); /* x=00000010 y=00001101 : equal to x */ + assert(setbits(0xF, 3, 1, 0xE) == 0x7); /* x=0000(1)111 y=0000111(0) : 0000(0)111 */ + assert(setbits(0x37, 3, 2, 0x4E) == 0x3B); /* x=0011(01)11 y=010011(10) : 0011(10)11 */ + assert(setbits(0x37, 7, 8, 0x4E) == 0x4E); /* x=(00110111) y=(01001110) : equal to y */ + assert(setbits(0xFF, 3, 4, 0x00) == 0xF0); /* x=1111(1111) y=0000(0000) : 1111(0000) */ + assert(setbits(0xFF, 0, 1, 0x00) == 0xFE); /* x=1111111(1) y=0000000(0) : 1111111(0) */ + + return 0; +} \ No newline at end of file diff --git a/source/cprogramming/chapter2/cprogs/Ex_2.7_invert.c b/source/cprogramming/chapter2/cprogs/ex_2.7_invert.c similarity index 76% rename from source/cprogramming/chapter2/cprogs/Ex_2.7_invert.c rename to source/cprogramming/chapter2/cprogs/ex_2.7_invert.c index 257635ce..5c9600b3 100644 --- a/source/cprogramming/chapter2/cprogs/Ex_2.7_invert.c +++ b/source/cprogramming/chapter2/cprogs/ex_2.7_invert.c @@ -11,7 +11,7 @@ unsigned invert(unsigned x, int p, int n); -int main(void) { printf("%u", (unsigned)invert((unsigned)8, (int)3, (int)3)); } +int main(void) { printf("%u", (unsigned) invert((unsigned) 8, (int) 3, (int) 3)); } unsigned invert(unsigned x, int p, int n) { return x ^ (~(~0 << n) << (p + 1 - n)); diff --git a/source/cprogramming/chapter2/cprogs/Ex_2.8_rightrot.c b/source/cprogramming/chapter2/cprogs/ex_2.8_rightrot.c similarity index 89% rename from source/cprogramming/chapter2/cprogs/Ex_2.8_rightrot.c rename to source/cprogramming/chapter2/cprogs/ex_2.8_rightrot.c index 1dddb0e7..61e93a76 100644 --- a/source/cprogramming/chapter2/cprogs/Ex_2.8_rightrot.c +++ b/source/cprogramming/chapter2/cprogs/ex_2.8_rightrot.c @@ -1,4 +1,4 @@ -/* write a function rightrot(x,n) that returns the value of the integer x +/* Write a function rightrot(x,n) that returns the value of the integer x * rotated to rightby n bit positions */ #include @@ -18,6 +18,7 @@ unsigned rightrot(unsigned x, int n) { unsigned rbit; /* rightmost bit */ rbit = x << (wordlength() - n); + x = x >> n; x = x | rbit; @@ -26,9 +27,11 @@ unsigned rightrot(unsigned x, int n) { int wordlength(void) { int i; + unsigned v = (unsigned)~0; for (i = 1; (v = v >> 1) > 0; i++) ; + return i; } diff --git a/source/cprogramming/chapter2/cprogs/Ex_2.9_bitcount2s.c b/source/cprogramming/chapter2/cprogs/ex_2.9_bitcount2s.c similarity index 80% rename from source/cprogramming/chapter2/cprogs/Ex_2.9_bitcount2s.c rename to source/cprogramming/chapter2/cprogs/ex_2.9_bitcount2s.c index 64a4e1ea..485f405d 100644 --- a/source/cprogramming/chapter2/cprogs/Ex_2.9_bitcount2s.c +++ b/source/cprogramming/chapter2/cprogs/ex_2.9_bitcount2s.c @@ -4,10 +4,6 @@ #include -int bitcount(unsigned x); - -int main(void) { printf("%d", bitcount((unsigned)12)); } - int bitcount(unsigned x) { int b; @@ -16,3 +12,7 @@ int bitcount(unsigned x) { return b; } + +int main(void) { + printf("%d", bitcount((unsigned) 12)); +} \ No newline at end of file diff --git a/source/cprogramming/chapter2/ex_2.1_cal_limits.rst b/source/cprogramming/chapter2/ex_2.1_cal_limits.rst index 788cdb97..42c1dc30 100644 --- a/source/cprogramming/chapter2/ex_2.1_cal_limits.rst +++ b/source/cprogramming/chapter2/ex_2.1_cal_limits.rst @@ -20,18 +20,43 @@ Explanation The execution of the above program will give:: - Minimum Signed Char -128 - Maximum Signed Char 127 - Minimum Signed Short -32768 - Maximum Signed Short 32767 - Minimum Signed Int -2147483648 - Maximum Signed Int 2147483647 - Minimum Signed Long -2147483648 - Maximum signed Long 2147483647 - Maximum Unsigned Char 255 - Maximum Unsigned Short 65535 - Maximum Unsigned Int 4294967295 - Maximum Unsigned Long 4294967295 + Ranges of various floating-point types through calculation: + Minimum Signed Char -128 + Maximum Signed Char 127 + Minimum Signed Short -32768 + Maximum Signed Short 32767 + Minimum Signed Int -2147483648 + Maximum Signed Int 2147483647 + Minimum Signed Long -9223372036854775808 + Maximum signed Long 9223372036854775807 + Maximum Unsigned Char 255 + Maximum Unsigned Short 65535 + Maximum Unsigned Int 4294967295 + Maximum Unsigned Long 18446744073709551615 + + Ranges of various integer and floating-point types from standard headers: + Minimum Signed Char -128 + Maximum Signed Char 127 + Minimum Signed Short -32768 + Maximum Signed Short 32767 + Minimum Signed Int -2147483648 + Maximum Signed Int 2147483647 + Minimum Signed Long -9223372036854775808 + Maximum signed Long 9223372036854775807 + Minimum Signed Long Long -9223372036854775808 + Maximum signed Long Long 9223372036854775807 + Minimum Float 1.175494E-38 + Maximum Float 3.402823E+38 + Minimum Double 2.225074E-308 + Maximum Double 1.797693E+308 + Minimum Long Double 3.362103E-4932 + Maximum Long Double 1.189731E+4932 + Maximum Unsigned Char 255 + Maximum Unsigned Short 65535 + Maximum Unsigned Int 4294967295 + Maximum Unsigned Long 18446744073709551615 + Maximum Unsigned Long Long 18446744073709551615 + In order explain how we calculate the maximum values, we will have to do some bit arthimetic. Let's start by calculating the maximum unsigned char. diff --git a/source/cprogramming/chapter2/ex_2.2_getline_without_and_or.rst b/source/cprogramming/chapter2/ex_2.2_getline_without_and_or.rst index ca8ec78d..f943bd19 100644 --- a/source/cprogramming/chapter2/ex_2.2_getline_without_and_or.rst +++ b/source/cprogramming/chapter2/ex_2.2_getline_without_and_or.rst @@ -22,7 +22,7 @@ Write a loop equivalent to the for loop above without using && or ||. Explanation =========== -We use mgetline instead of getline, so that our compiler does not get confused +We use _getline instead of getline, so that our compiler does not get confused with the builtin getline function. The crux of the program is this. diff --git a/source/cprogramming/chapter2/ex_2.3_htoi.rst b/source/cprogramming/chapter2/ex_2.3_htoi.rst index c14a1b82..520afa17 100644 --- a/source/cprogramming/chapter2/ex_2.3_htoi.rst +++ b/source/cprogramming/chapter2/ex_2.3_htoi.rst @@ -9,7 +9,7 @@ Write a function htoi(s), which converts a string of hexadecimal digits (including an optional 0x or 0X) into its equivalent integer value. The allowable digits are 0 through 9, a through f,and A through F. -.. literalinclude:: ../../languages/cprogs/Ex_2.3_htoi.c +.. literalinclude:: cprogs/ex_2.3_htoi.c :language: c Explanation @@ -67,21 +67,40 @@ find a character between a to f, we store char - `a` + 10, becase hexadecimal Then we take each hex digit and for it's position or previous value stored in n, we mutiply by 16 and add hexdigit. +.. code-block:: c + if(inhex == YES) n = 16 * n + hexdigit; For example to convert **0XAF**. -1. We strip off 0X. -2. For A, we get the value hexdigit = 10 -3. n = 16 * 0 + 10 - = 10 -4. We gather F, we store hexdigit = 'F' - 'A' + 10; - = 70 - 65 + 10; (70 is ascii value for F, 65 is ascii value for A) - = 15 -5. n = 16 * n + hexdigit - = 16 * 10 + 15 - = 160 + 15 - = 175 - -**175** +.. code:: + + 1. We strip off 0X. + 2. For A, we get the value hexdigit = 10 + 3. n = 16 * 0 + 10 + = 10 + 4. We gather F, we store hexdigit = 'F' - 'A' + 10; + = 70 - 65 + 10; (70 is ascii value for F, 65 is ascii value for A) + = 15 + 5. n = 16 * n + hexdigit + = 16 * 10 + 15 + = 160 + 15 + = 175 + + 175 + +Visualization +============= + +.. raw:: html + + + +Try It Out +========== + + +.. raw:: html + + diff --git a/source/cprogramming/chapter2/ex_2.4_squeezess.rst b/source/cprogramming/chapter2/ex_2.4_squeezess.rst index 1cfab1e5..4a402b69 100644 --- a/source/cprogramming/chapter2/ex_2.4_squeezess.rst +++ b/source/cprogramming/chapter2/ex_2.4_squeezess.rst @@ -8,7 +8,7 @@ Question Write an alternative version of squeeze(s1,s2) that deletes each character in s1 that matches any character in the string s2. -.. literalinclude:: ../../languages/cprogs/Ex_2.4_squeezess.c +.. literalinclude:: cprogs/ex_2.4_squeezess.c :language: c Explanation @@ -16,18 +16,23 @@ Explanation Let's take the two inputs strings as: - s1: HelloWorld +.. code-block:: bash - s2: ol + HelloWorld + ol -Our desired output is:: +Our desired output is - HeWrd +.. code-block:: bash + + HeWrd This has removed the characters `o` and `l` from the first string. The way squeeze works is, it take each character from the first string and if there is no match found, stores it with a new index `k`. If there is a match found in -**s2**, it simply skips it. The way it skips is realized by the following:: +**s2**, it simply skips it. The way it skips is realized by the following + +.. code-block:: c for(j=0; (s1[i]!=s2[j]) && s2[j]!='\0' ;++j) ; @@ -38,3 +43,18 @@ When the match is found **s1[i] == s2[j]** so our first for loop will **end**. The second **if condtion** will fail too as s2 is not iterated till the end, so we do not place the character in **s1[k++]** and we have successfully skipped it. + +Visualization +============= + +.. raw:: html + + + + +Try It Out +========== + +.. raw:: html + + diff --git a/source/cprogramming/chapter2/ex_2.5_any.rst b/source/cprogramming/chapter2/ex_2.5_any.rst index c0c9ae2d..e7f8b697 100644 --- a/source/cprogramming/chapter2/ex_2.5_any.rst +++ b/source/cprogramming/chapter2/ex_2.5_any.rst @@ -10,7 +10,7 @@ where any character from the string s2 occurs, or -1 if s1 contains no characters from s2. (The standard library function strpbrk does the same job but returns a pointer to the location.) -.. literalinclude:: ../../languages/cprogs/Ex_2.5_any.c +.. literalinclude:: cprogs/ex_2.5_any.c :language: c Explanation @@ -29,3 +29,18 @@ check_next_char to 0. That is we found a match at **i** and we return that. If we dont find a match in s2, we increment i and take the next character from s1. If dont find a match at all, then we return -1. + + +Visualization +============= + +.. raw:: html + + + +Try It Out +========== + +.. raw:: html + + diff --git a/source/cprogramming/chapter2/ex_2.6_setbits.rst b/source/cprogramming/chapter2/ex_2.6_setbits.rst index 8ea3c071..e58f0cf7 100644 --- a/source/cprogramming/chapter2/ex_2.6_setbits.rst +++ b/source/cprogramming/chapter2/ex_2.6_setbits.rst @@ -14,133 +14,39 @@ position p set to the rightmost n bits of y, leaving the other bits unchanged. Explanation =========== -The important piece of the program is this:: +The setbits function takes 4 inputs: - (x & ~(~(~0 << n) << (p+1-n))) | ( y & (~(~0< -Converting 1111 0000 to decimal gives us 240 and that is answer. diff --git a/source/cprogramming/chapter2/ex_2.7_invert.rst b/source/cprogramming/chapter2/ex_2.7_invert.rst index 6560d71a..37816dfc 100644 --- a/source/cprogramming/chapter2/ex_2.7_invert.rst +++ b/source/cprogramming/chapter2/ex_2.7_invert.rst @@ -46,3 +46,10 @@ position onwards by:: x ^ (~(~0 << n) << (p + 1 - n)) = 0000 1000 ^ 0000 1111 = 0000 1111 = 15 + +Visualization +============= + +.. raw:: html + + diff --git a/source/cprogramming/chapter2/ex_2.8_rightrot.rst b/source/cprogramming/chapter2/ex_2.8_rightrot.rst index dd0b24de..e0807a05 100644 --- a/source/cprogramming/chapter2/ex_2.8_rightrot.rst +++ b/source/cprogramming/chapter2/ex_2.8_rightrot.rst @@ -19,18 +19,19 @@ We need to get the right most bit of the number provided. First we get the right n bits at one time. :: + rbit = x << (wordlength() - n); -Once we get the right n bits, in order to rotate the value of x, we right -shift x for n bits and then OR the result of x with the rbit determined in the previous -step. +Once we get the right n bits, in order to rotate the value of x, we right shift +x for n bits and then OR the result of x with the rbit determined in the +previous step. :: x = x >> n; x = x | rbit; - For the same example. +For the same example. :: @@ -50,7 +51,8 @@ step. = 0001 1001 << 5 = 0010 0000 -So we have got the right most n bits set.Now we right x by 1 and OR the rbit with x. +So we have got the right most n bits set.Now we right x by 1 and OR the rbit +with x. :: @@ -66,11 +68,20 @@ Which is our expected result. condition 3. when (n > wordlength()) like n = 12 -The Compiler will auto transfer "n" to "n % wordlength()", n will be 3, then see "n" as condition 2. -The result should be correct too! +The Compiler will auto transfer "n" to "n % wordlength()", n will be 3, then +see "n" as condition 2. The result should be correct too! :: + condition 4. when n < 0 (which is not Often use) -The result will mirror the function,the rightrot(x,n) function will move the left most n(n > 0)bits to the right -side ,the function should called leftrot(x,n). +The result will mirror the function,the rightrot(x,n) function will move the +left most n(n > 0)bits to the right side ,the function should called +leftrot(x,n). + +Visualization +============= + +.. raw:: html + + diff --git a/source/cprogramming/chapter2/ex_2.9_bitcount2s.rst b/source/cprogramming/chapter2/ex_2.9_bitcount2s.rst index ba59110c..a556a6d6 100644 --- a/source/cprogramming/chapter2/ex_2.9_bitcount2s.rst +++ b/source/cprogramming/chapter2/ex_2.9_bitcount2s.rst @@ -132,12 +132,9 @@ This gives the number of 1 bits in our program. **AND** operation is faster than shifting, because all bits of the number are **not** moved and thereby makes our program more efficient. +Visualization +============= -References -========== +.. raw:: html -* `Ones complement`_ -* `Twos complement`_ - -.. _Ones complement: http://foldoc.org/ones+complement -.. _Twos complement: http://foldoc.org/twos+complement + diff --git a/source/cprogramming/chapter3/cprogs/Ex_3.2_escape.c b/source/cprogramming/chapter3/cprogs/Ex_3.2_escape.c deleted file mode 100644 index fe2b7b79..00000000 --- a/source/cprogramming/chapter3/cprogs/Ex_3.2_escape.c +++ /dev/null @@ -1,58 +0,0 @@ -/* Write a function escape(s,t) that converts characters like newline and tab -into visible escape sequences like \n and \t as it copies the string t to s. Use -a Switch. Write a function for the other direction as well,converting the escape -sequences into the real characters */ - -#include -#define MAXLINE 1000 -int mgetline(char line[], int maxline); -void escape(char s[], char t[]); - -int main(void) { - char s[MAXLINE], t[MAXLINE]; - - mgetline(t, MAXLINE); - - escape(s, t); - - printf("%s", s); - - return 0; -} - -void escape(char s[], char t[]) { - int i, j; - - i = j = 0; - - while (t[i] != '\0') { - switch (t[i]) { - case '\t': - s[j] = '\\'; - ++j; - s[j] = 't'; - break; - case '\n': - s[j] = '\\'; - ++j; - s[j] = 'n'; - break; - default: - s[j] = t[i]; - break; - } - ++i; - ++j; - } - - s[j] = '\0'; -} - -int mgetline(char s[], int lim) { - int i, c; - - for (i = 0; i < lim - 1 && (c = getchar()) != EOF; ++i) - s[i] = c; - - s[i] = '\0'; -} diff --git a/source/cprogramming/chapter3/cprogs/Ex_3.4-itoa-previous.c b/source/cprogramming/chapter3/cprogs/Ex_3.4-itoa-previous.c deleted file mode 100644 index 4079c02a..00000000 --- a/source/cprogramming/chapter3/cprogs/Ex_3.4-itoa-previous.c +++ /dev/null @@ -1,15 +0,0 @@ -/* itoa: convert n to characters in s */ -void itoa(int n, char s[]) { - int i, sign; - if ((sign = n) < 0) /*record sign */ - n = -n; /* make n positive */ - i = 0; - do { /* generate digits in reverse order */ - s[i++] = n % 10 + '0'; /* get next digit */ - } while ((n /= 10) > 0); /* delete it */ - - if (sign < 0) - s[i++] = '-'; - s[i] = '\0'; - reverse(s); -} diff --git a/source/cprogramming/chapter3/cprogs/Ex_3.1_binsearch-2.c b/source/cprogramming/chapter3/cprogs/ex_3.1_binsearch-2.c similarity index 78% rename from source/cprogramming/chapter3/cprogs/Ex_3.1_binsearch-2.c rename to source/cprogramming/chapter3/cprogs/ex_3.1_binsearch-2.c index fd22711d..1655f8ae 100644 --- a/source/cprogramming/chapter3/cprogs/Ex_3.1_binsearch-2.c +++ b/source/cprogramming/chapter3/cprogs/ex_3.1_binsearch-2.c @@ -1,17 +1,5 @@ -/* Binsearch function, by writing minimum tests inside the loop ( at the cost of - * more outside)*/ - #include -int binsearch(int x, int v[], int n); - -int main(void) { - int arr[] = {2, 4, 6, 7, 9, 29, 45, 46, 49, 50, 51}; - printf("%d", binsearch(9, arr, 10)); - - return 0; -} - int binsearch(int x, int v[], int n) { int low, high, mid; @@ -34,3 +22,10 @@ int binsearch(int x, int v[], int n) { else return -1; } + +int main(void) { + int arr[] = {2, 4, 6, 7, 9, 29, 45, 46, 49, 50, 51}; + printf("%d", binsearch(9, arr, 10)); + + return 0; +} \ No newline at end of file diff --git a/source/cprogramming/chapter3/cprogs/ex_3.2_escape.c b/source/cprogramming/chapter3/cprogs/ex_3.2_escape.c new file mode 100644 index 00000000..a2b482eb --- /dev/null +++ b/source/cprogramming/chapter3/cprogs/ex_3.2_escape.c @@ -0,0 +1,51 @@ +#include +#define MAXLINE 1000 + +void escape(char s[], char t[]) { + int i, j; + + i = j = 0; + + while (t[i] != '\0') { + switch (t[i]) { + case '\t': + s[j] = '\\'; + ++j; + s[j] = 't'; + break; + case '\n': + s[j] = '\\'; + ++j; + s[j] = 'n'; + break; + default: + s[j] = t[i]; + break; + } + ++i; + ++j; + } + + s[j] = '\0'; +} + +int mgetline(char s[], int lim) { + int i, c; + + for (i = 0; i < lim - 1 && (c = getchar()) != EOF; ++i) + s[i] = c; + + s[i] = '\0'; +} + +int main(void) { + char s[MAXLINE], t[MAXLINE]; + + mgetline(t, MAXLINE); + + escape(s, t); + + printf("%s", s); + + return 0; +} \ No newline at end of file diff --git a/source/cprogramming/chapter3/cprogs/Ex_3.3_expand.c b/source/cprogramming/chapter3/cprogs/ex_3.3_expand.c similarity index 82% rename from source/cprogramming/chapter3/cprogs/Ex_3.3_expand.c rename to source/cprogramming/chapter3/cprogs/ex_3.3_expand.c index b5021c96..d4d9bc8b 100644 --- a/source/cprogramming/chapter3/cprogs/Ex_3.3_expand.c +++ b/source/cprogramming/chapter3/cprogs/ex_3.3_expand.c @@ -1,21 +1,20 @@ -/* expand: expand short hand notation in s1 into string s2. */ - #include #define MAXLINE 100 -int mgetline(char s[], int maxlimit); -void expand(char s1[], char s2[]); - -int main(void) { - char s1[MAXLINE], s2[MAXLINE]; - - mgetline(s1, MAXLINE); +void expand(char s1[], char s2[]) { + int i, j, c; - expand(s1, s2); + i = j = 0; - printf("%s", s2); + while ((c = s1[i++]) != '\0') + if (s1[i] == '-' && s1[i + 1] >= c) { + i++; + while (c < s1[i]) + s2[j++] = c++; + } else + s2[j++] = c; - return 0; + s2[j] = '\0'; } int mgetline(char s[], int lim) { @@ -30,18 +29,14 @@ int mgetline(char s[], int lim) { s[i] = '\0'; } -void expand(char s1[], char s2[]) { - int i, j, c; +int main(void) { + char s1[MAXLINE], s2[MAXLINE]; - i = j = 0; + mgetline(s1, MAXLINE); - while ((c = s1[i++]) != '\0') - if (s1[i] == '-' && s1[i + 1] >= c) { - i++; - while (c < s1[i]) - s2[j++] = c++; - } else - s2[j++] = c; + expand(s1, s2); - s2[j] = '\0'; -} + printf("%s", s2); + + return 0; +} \ No newline at end of file diff --git a/source/cprogramming/chapter3/cprogs/Ex_3.4_itoa-2.c b/source/cprogramming/chapter3/cprogs/ex_3.4_itoa-2.c similarity index 61% rename from source/cprogramming/chapter3/cprogs/Ex_3.4_itoa-2.c rename to source/cprogramming/chapter3/cprogs/ex_3.4_itoa-2.c index 38812ff6..e0e1e2bf 100644 --- a/source/cprogramming/chapter3/cprogs/Ex_3.4_itoa-2.c +++ b/source/cprogramming/chapter3/cprogs/ex_3.4_itoa-2.c @@ -1,37 +1,15 @@ -/* Modified version of itoa; to handle the situation of MIN_INT of limits.h -in the previous number = -2147483648 would fail at n =-n,because the max value -of integer is 2147483647 - -modifying itoa to handle these situations. -sign is stored as the number itself, absolute value of each digit is stored in -the string and while loop is tested not for 0 - -itoa: convert an integer to string */ - #include #include + #define MAXLINE 1000 #define abs(x) ((x) > 0 ? (x) : -(x)) -void itoa(int n, char s[]); -void reverse(char s[]); - -int main(void) { - int number; - char str[MAXLINE]; - - /* number=-2345645; */ - - number = -2147483648; - - printf("Integer %d printed as\n String:", number); - - itoa(number, str); - - printf("%s", str); +void reverse(char s[]) { + int c, i, j; - return 0; + for (i = 0, j = strlen(s) - 1; i < j; i++, j--) + c = s[i], s[i] = s[j], s[j] = c; } void itoa(int n, char s[]) { @@ -54,9 +32,19 @@ void itoa(int n, char s[]) { reverse(s); } -void reverse(char s[]) { - int c, i, j; +int main(void) { + int number; + char str[MAXLINE]; - for (i = 0, j = strlen(s) - 1; i < j; i++, j--) - c = s[i], s[i] = s[j], s[j] = c; -} + /* number=-2345645; */ + + number = -2147483648; + + printf("Integer %d printed as\n String:", number); + + itoa(number, str); + + printf("%s", str); + + return 0; +} \ No newline at end of file diff --git a/source/cprogramming/chapter3/cprogs/Ex_3.5_itob.c b/source/cprogramming/chapter3/cprogs/ex_3.5_itob.c similarity index 79% rename from source/cprogramming/chapter3/cprogs/Ex_3.5_itob.c rename to source/cprogramming/chapter3/cprogs/ex_3.5_itob.c index 9443046a..76a020d8 100644 --- a/source/cprogramming/chapter3/cprogs/Ex_3.5_itob.c +++ b/source/cprogramming/chapter3/cprogs/ex_3.5_itob.c @@ -1,26 +1,13 @@ -/* function itob(n,s,b), that converts the integer n into a base b character - representation in the string s. -*/ #include #include #define MAXLINE 100 -void itob(int n, char s[], int b); -void reverse(char s[]); - -int main(void) { - int number, base; - char str[MAXLINE]; - - number = 42425; - base = 16; - - itob(number, str, base); - - printf("%s", str); +void reverse(char s[]) { + int i, j, c; - return 0; + for (i = 0, j = strlen(s) - 1; i < j; i++, j--) + c = s[i], s[i] = s[j], s[j] = c; } void itob(int n, char s[], int b) { @@ -45,9 +32,16 @@ void itob(int n, char s[], int b) { reverse(s); } -void reverse(char s[]) { - int i, j, c; +int main(void) { + int number, base; + char str[MAXLINE]; - for (i = 0, j = strlen(s) - 1; i < j; i++, j--) - c = s[i], s[i] = s[j], s[j] = c; -} + number = 42425; + base = 16; + + itob(number, str, base); + + printf("%s", str); + + return 0; +} \ No newline at end of file diff --git a/source/cprogramming/chapter3/cprogs/Ex_3.6_itoa-3.c b/source/cprogramming/chapter3/cprogs/ex_3.6_itoa-3.c similarity index 74% rename from source/cprogramming/chapter3/cprogs/Ex_3.6_itoa-3.c rename to source/cprogramming/chapter3/cprogs/ex_3.6_itoa-3.c index 676531bb..1cb57850 100644 --- a/source/cprogramming/chapter3/cprogs/Ex_3.6_itoa-3.c +++ b/source/cprogramming/chapter3/cprogs/ex_3.6_itoa-3.c @@ -1,27 +1,13 @@ -/* a function of itoa, which accepts the third argument as the width of the -number. the string representation is padded with blanks in the left to get the -required width */ - #include #include #define MAXLIMIT 100 -void itoa(int n, char s[], int w); -void reverse(char s[]); - -int main(void) { - int number, width; - char str[MAXLIMIT]; - - number = -343565; - width = 10; - - itoa(number, str, width); - - printf("%s", str); +void reverse(char s[]) { + int i, j, c; - return 0; + for (i = 0, j = strlen(s) - 1; i < j; i++, j--) + c = s[i], s[i] = s[j], s[j] = c; } void itoa(int n, char s[], int w) { @@ -47,9 +33,16 @@ void itoa(int n, char s[], int w) { reverse(s); } -void reverse(char s[]) { - int i, j, c; +int main(void) { + int number, width; + char str[MAXLIMIT]; - for (i = 0, j = strlen(s) - 1; i < j; i++, j--) - c = s[i], s[i] = s[j], s[j] = c; -} + number = -343565; + width = 10; + + itoa(number, str, width); + + printf("%s", str); + + return 0; +} \ No newline at end of file diff --git a/source/cprogramming/chapter3/ex_3.1_binsearch-2.rst b/source/cprogramming/chapter3/ex_3.1_binsearch-2.rst index 905c0770..912c5ebf 100644 --- a/source/cprogramming/chapter3/ex_3.1_binsearch-2.rst +++ b/source/cprogramming/chapter3/ex_3.1_binsearch-2.rst @@ -9,13 +9,10 @@ Our binary search makes two tests inside the loop, when one would suffice (at the price of more tests outside.) Write a version with only one test inside the loop and measure the difference in runtime. -.. literalinclude:: cprogs/Ex_3.1_binsearch-2.c +.. literalinclude:: cprogs/ex_3.1_binsearch-2.c :language: c :tab-width: 4 -.. runcode:: cprogs/Ex_3.1_binsearch-2.c - :language: c - Explanation =========== diff --git a/source/cprogramming/chapter3/ex_3.2_escape.rst b/source/cprogramming/chapter3/ex_3.2_escape.rst index 0e61bf42..5b862de8 100644 --- a/source/cprogramming/chapter3/ex_3.2_escape.rst +++ b/source/cprogramming/chapter3/ex_3.2_escape.rst @@ -10,14 +10,10 @@ visible escape sequences like \n and \t as it copies the string t to s. Use a switch. Write a function for the other direction as well, converting escape sequences into the real characters. -.. literalinclude:: cprogs/Ex_3.2_escape.c +.. literalinclude:: cprogs/ex_3.2_escape.c :language: c :tab-width: 4 -.. runcode:: cprogs/Ex_3.2_escape.c - :language: c - :codesite: ideone - Explanation =========== diff --git a/source/cprogramming/chapter3/ex_3.3_expand.rst b/source/cprogramming/chapter3/ex_3.3_expand.rst index 9dcddb70..56af6625 100644 --- a/source/cprogramming/chapter3/ex_3.3_expand.rst +++ b/source/cprogramming/chapter3/ex_3.3_expand.rst @@ -10,14 +10,10 @@ string s1 into the equivalent complete list abc...xyz in s2. Allow for letters of either case and digits, and be prepared to handle cases like a-b-c and a-z0-9 and -a-z. Arrange that a leading or trailing -is taken literally. -.. literalinclude:: cprogs/Ex_3.3_expand.c +.. literalinclude:: cprogs/ex_3.3_expand.c :language: c :tab-width: 4 -.. runcode:: cprogs/Ex_3.3_expand.c - :language: c - :codesite: ideone - Explanation =========== diff --git a/source/cprogramming/chapter3/ex_3.4_itoa-2.rst b/source/cprogramming/chapter3/ex_3.4_itoa-2.rst index 08b19b71..510f7fac 100644 --- a/source/cprogramming/chapter3/ex_3.4_itoa-2.rst +++ b/source/cprogramming/chapter3/ex_3.4_itoa-2.rst @@ -10,20 +10,12 @@ the largest negative number, that is, the value of n equal to -(2wordsize-1). Explain why not. Modify it to print that value correctly, regardless of the machine on which it runs. -The previous version of itoa was this:: +The previous version of itoa was this -.. literalinclude:: ../../languages/cprogs/Ex_3.4_itoa-previous.c +.. literalinclude:: cprogs/ex_3.4_itoa-2.c :language: c :tab-width: 4 -.. literalinclude:: ../../languages/cprogs/Ex_3.4_itoa-2.c - :language: c - :tab-width: 4 - -.. runcode:: ../../languages/cprogs/Ex_3.4_itoa-2.c - :language: c - :codesite: ideone - Explanation =========== @@ -37,10 +29,3 @@ Once this process is over. We check if we were converting negative number, by checking if the sign is less than 0, if it was, we add a `-` to the string. And then we do a simple `reverse` of the string to get our `itoa`. - - - -.. seealso:: - - * :c-suggest-improve:`Ex_3.4_itoa-2.c` - * :c-better-explain:`Ex_3.4_itoa-2.rst` diff --git a/source/cprogramming/chapter3/ex_3.5_itob.rst b/source/cprogramming/chapter3/ex_3.5_itob.rst index 36e94810..bdecec35 100644 --- a/source/cprogramming/chapter3/ex_3.5_itob.rst +++ b/source/cprogramming/chapter3/ex_3.5_itob.rst @@ -9,10 +9,7 @@ Write the function itob(n,s,b) that converts the integer n into a base b character representation in the string s. In particular, itob(n,s,16) formats s as a hexadecimal integer in s. -.. literalinclude:: cprogs/Ex_3.5_itob.c - :language: c - -.. runcode:: cprogs/Ex_3.5_itob.c +.. literalinclude:: cprogs/ex_3.5_itob.c :language: c Explanation diff --git a/source/cprogramming/chapter3/ex_3.6_itoa-3.rst b/source/cprogramming/chapter3/ex_3.6_itoa-3.rst index 6afb8969..c67fe780 100644 --- a/source/cprogramming/chapter3/ex_3.6_itoa-3.rst +++ b/source/cprogramming/chapter3/ex_3.6_itoa-3.rst @@ -9,13 +9,10 @@ Write a version of itoa that accepts three arguments instead of two. The third argument is a minimum field width; the converted number must be padded with blanks on the left if necessary to make it wide enough. -.. literalinclude:: cprogs/Ex_3.6_itoa-3.c +.. literalinclude:: cprogs/ex_3.6_itoa-3.c :language: c :tab-width: 4 -.. runcode:: cprogs/Ex_3.6_itoa-3.c - :language: c - Explanation =========== @@ -42,4 +39,4 @@ Run It .. raw:: html - + \ No newline at end of file diff --git a/source/cprogramming/chapter4/cprogs/ex_4.10_calculator_getline.c b/source/cprogramming/chapter4/cprogs/ex_4.10_calculator_getline.c index 71ff0b3d..482b0f4a 100644 --- a/source/cprogramming/chapter4/cprogs/ex_4.10_calculator_getline.c +++ b/source/cprogramming/chapter4/cprogs/ex_4.10_calculator_getline.c @@ -1,145 +1,139 @@ /** - * Exercise 4.10 of The C Programming Language by Brian Kernighan and Dennis - * Ritchie - * - * An alternate organization uses getline to read an entire input line; this - * makes getch and ungetch unnecessary. Revise the calculator to use this - * approach. - */ + * Revise the Calculator program to use the getline instead of getch and ungetch + **/ -#include -#include // for atof() +#include +#include /* for atof() */ -#define MAXOP 100 // max size of operand or operator -#define NUMBER '0' // signal that a number was found +#define MAXOP 100 +#define NUMBER '0' + +int getop(char []); -int getop(char[]); void push(double); + double pop(void); -/* reverse Polish calculator */ +/* reverse polish notation calculator */ -int main(int argc, char *argv[]) { +int main(void) { int type; double op2; char s[MAXOP]; - while (--argc > 0) { - type = getop(*++argv); + while ((type = getop(s)) != EOF) { switch (type) { - case NUMBER: - push(atof(s)); - break; - case '+': - push(pop() + pop()); - break; - case '*': - push(pop() * pop()); - break; - case '-': - op2 = pop(); - push(pop() - op2); - break; - case '/': - op2 = pop(); - if (op2 != 0.0) - push(pop() / op2); - else - printf("error: zero divisor\n"); - break; - case '%': - op2 = pop(); - if (op2 != 0.0) - push((int)pop() % (int)op2); - else - printf("error: zero divisor\n"); - break; - case '\0': - printf("\t%.8g\n", pop()); - break; - default: - printf("error: unknown command %s\n", s); - break; + case NUMBER: + push(atof(s)); + break; + case '+': + push(pop() + pop()); + break; + case '*': + push(pop() * pop()); + break; + case '-': + op2 = pop(); + push(pop() - op2); + break; + case '/': + op2 = pop(); + if (op2 != 0.0) + push(pop() / op2); + break; + case '\n': + printf("\t%.9g\n", pop()); + break; + default: + printf("error: unknown command %s\n", s); + break; } } return 0; } -#define MAXVAL 100 // maximum depth of val stack +#define MAXVAL 100 /* maximum depth of the val stack */ -int sp = 0; // next free stack position +int sp = 0; +double val[MAXVAL]; -double val[MAXVAL]; // value stack - -/* push: push f onto value stack */ +/* push : push f onto value stack */ void push(double f) { if (sp < MAXVAL) val[sp++] = f; else - printf("error: stack full, can't push %g\n", f); + printf("error: stack full,can't push %g\n", f); } -/* pop: pop and return top value from stack */ +/* pop: pop and return top values from stack */ double pop(void) { if (sp > 0) return val[--sp]; else { - printf("error: stack empty\n"); + printf("error: stack empty \n"); return 0.0; } } + /* using getline instead of getch and ungetch */ -#include +#include + #define MAXLINE 100 int mgetline(char line[], int limit); -int li = 0; // index of next char in line -char line[MAXLINE]; // current input line - -int getop(char s[]) { - int i, c; +int li = 0; /* input line index */ +char line[MAXLINE]; /* one input line */ - if (line[li] == '\0') { +/* getop: get next operator or numeric operand */ - if (mgetline(line, MAXLINE) == 0) { - return '\0'; - } +int getop(char s[]) { + int c, i; - else { + if (line[li] == '\0') + if (mgetline(line, MAXLINE) == 0) + return EOF; + else li = 0; - } - } - while ((s[0] = c = line[li++]) == ' ' || c == '\t') - ; + while ((s[0] = c = line[li++]) == ' ' || c == '\t'); + s[1] = '\0'; + if (!isdigit(c) && c != '.') - return c; // not a number + return c; + i = 0; - if (isdigit(c)) // collect integer part - while (isdigit(s[++i] = c = line[li++])) - ; - if (c == '.') // collect fraction part - while (isdigit(s[++i] = c = line[li++])) - ; + + if (isdigit(c)) + while (isdigit(s[++i] = c = line[li++])); + if (c == '.') + while (isdigit(s[++i] = c = line[li++])); + s[i] = '\0'; + li--; + return NUMBER; } int mgetline(char s[], int lim) { - int c, i; + int i, c; + + for (i = 0; i < lim - 1 && (c = getchar()) != EOF && c != '\n'; ++i) + s[i] = c; - i = 0; - while (--lim > 0 && (c = getchar()) != EOF && c != '\n') - s[i++] = c; if (c == '\n') s[i++] = c; + s[i] = '\0'; + return i; } + + + diff --git a/source/cprogramming/chapter4/cprogs/ex_4.11_getch_static.c b/source/cprogramming/chapter4/cprogs/ex_4.11_getch_static.c index 65327c85..5fd4166b 100644 --- a/source/cprogramming/chapter4/cprogs/ex_4.11_getch_static.c +++ b/source/cprogramming/chapter4/cprogs/ex_4.11_getch_static.c @@ -1,82 +1,70 @@ /** - * Exercise 4.11 of The C Programming Language by Brian Kernighan and Dennis - * Ritchie - * - * Modify getop so that it doesn't need to use ungetch. Hint: use an internal - * static variable. - * - */ - -#include -#include -#include // for atof() + * modify getop so that it does not need to use ungetch: Hint: static int lastc + **/ + +#include +#include -#define NUMBER '0' #define MAXOP 100 +#define NUMBER '0' + +int getop(char []); -int getop(char[]); void push(double); + double pop(void); -/* reverse Polish calculator */ +/* reverse polish calculator */ -int main(int argc, char *argv[]) { +int main(void) { int type; double op2; char s[MAXOP]; while ((type = getop(s)) != EOF) { switch (type) { - case NUMBER: - push(atof(s)); - break; - case '+': - push(pop() + pop()); - break; - case '*': - push(pop() * pop()); - break; - case '-': - op2 = pop(); - push(pop() - op2); - break; - case '/': - op2 = pop(); - if (op2 != 0.0) - push(pop() / op2); - else - printf("error: zero divisor\n"); - break; - case '%': - op2 = pop(); - if (op2 != 0.0) - push((int)pop() % (int)op2); - else - printf("error: zero divisor\n"); - break; - case '\n': - printf("\t%.8g\n", pop()); - break; - default: - printf("error: unknown command %s\n", s); - break; + case NUMBER: + push(atof(s)); + break; + case '+': + push(pop() + pop()); + break; + case '*': + push(pop() * pop()); + break; + case '-': + op2 = pop(); + push(pop() - op2); + break; + case '/': + op2 = pop(); + if (op2 != 0.0) + push(pop() / op2); + break; + case '\n': + printf("\t%.8g\n", pop()); + break; + default: + printf("error: unknown command %s\n", s); + break; } } return 0; } -#define MAXVAL 100 /* maximum depth of val stack */ -int sp = 0; /* next free stack position */ -double val[MAXVAL]; /* value stack */ +#define MAXVAL 100 + +int sp = 0; +double val[MAXVAL]; -/* push: push f onto value stack */ +/* push : push f onto value stack */ void push(double f) { if (sp < MAXVAL) val[sp++] = f; else - printf("error: stack full, can't push %g\n", f); + printf("error: stack full,can't push %g\n", f); } /* pop: pop and return top value from stack */ @@ -90,10 +78,12 @@ double pop(void) { } } -#include +#include int getch(void); +/* getop: get next operator or numeric operand */ + int getop(char s[]) { int c, i; static int lastc = 0; @@ -109,28 +99,28 @@ int getop(char s[]) { c = getch(); s[1] = '\0'; + if (!isdigit(c) && c != '.') - return c; /* not a number */ + return c; i = 0; - if (isdigit(c)) /* collect integer part */ - while (isdigit(s[++i] = c = getch())) - ; - if (c == '.') /* collect fraction part */ - while (isdigit(s[++i] = c = getch())) - ; + if (isdigit(c)) + while (isdigit(s[++i] = c = getch())); + if (c == '.') + while (isdigit(s[++i] = c = getch())); s[i] = '\0'; + if (c != EOF) lastc = c; + return NUMBER; } #define BUFSIZE 100 -char buf[BUFSIZE]; /* buffer for ungetch */ -int bufp = 0; /* next free position in buf */ +char buf[BUFSIZE]; +int bufp; -int getch(void) /* get a (possibly pushed back) character */ -{ +int getch(void) { return (bufp > 0) ? buf[--bufp] : getchar(); -} +} \ No newline at end of file diff --git a/source/cprogramming/chapter4/cprogs/ex_4.12_recursive_itoa.c b/source/cprogramming/chapter4/cprogs/ex_4.12_recursive_itoa.c index dd880501..af061ab6 100644 --- a/source/cprogramming/chapter4/cprogs/ex_4.12_recursive_itoa.c +++ b/source/cprogramming/chapter4/cprogs/ex_4.12_recursive_itoa.c @@ -1,34 +1,41 @@ /** - * Exercise 4.12 of The C Programming Language by Brian Kernighan and Dennis - * Ritchie - * - * Adapt the ideas of printd to write a recursive version of itoa; that is, - * convert an integer into a string by calling a recursive routine. - */ - -#include -#include + * recursive version of itoa; that converts an integer string by calling a recursive routine + **/ + #include +#include + +#define MAXLEN 100 void itoa(int n, char s[]); -int main(int argc, char *argv[]) { - int n = 123456789; - char s[100]; + +int main(void) { + int n; + char s[MAXLEN]; + + n = 1723; + itoa(n, s); - printf("%s\n", s); + + printf("%s", s); + return 0; } void itoa(int n, char s[]) { - static int i = 0; - if (n / 10) { + static int i; + + if (n / 10) itoa(n / 10, s); - } else { - if (n < 0) { + else { + i = 0; + if (n < 0) s[i++] = '-'; - } } + s[i++] = abs(n) % 10 + '0'; + s[i] = '\0'; -} + +} \ No newline at end of file diff --git a/source/cprogramming/chapter4/cprogs/ex_4.13_reverse_string.c b/source/cprogramming/chapter4/cprogs/ex_4.13_reverse_string.c index 0f21b5f7..6cb96c76 100644 --- a/source/cprogramming/chapter4/cprogs/ex_4.13_reverse_string.c +++ b/source/cprogramming/chapter4/cprogs/ex_4.13_reverse_string.c @@ -1,38 +1,57 @@ /** - * Exercise 4.13 of The C Programming Language by Brian Kernighan and Dennis - * Ritchie - * - * Write a recursive version of the function reverse(s), which reverses the - * string s in place. - */ + * a recursive version of reverse(s); the string reverse function + **/ -#include -#include +#include +#include -#define MAXLINE 1000 +#define MAXLINE 100 -void reverse(char s[], int i, int j); +void reverse(char s[]) { + static int i = 0; + static int len; -int main(void) { - char s[MAXLINE]; - int i, j; - - printf("Enter a string: "); - fgets(s, MAXLINE, stdin); - i = 0; - j = strlen(s) - 1; - reverse(s, i, j); - printf("Reversed string: %s\n", s); - return 0; -} + int j; + char c; + + if (i == 0) { + len = strlen(s); + } -void reverse(char s[], int i, int j) { - int c; + j = len - (i + 1); if (i < j) { c = s[i]; s[i] = s[j]; s[j] = c; - reverse(s, ++i, --j); + i++; + reverse(s); + } else { + // the algorithm has finished so we have to set i=0 again + i = 0; } } + +int mgetline(char line[], int lim) { + int i, c; + + for (i = 0; i < lim - 1 && (c = getchar()) != EOF && c != '\n'; ++i) + line[i] = c; + + if (c == '\n') + line[i++] = '\n'; + + line[i] = '\0'; +} + +int main(void) { + char s[MAXLINE]; + + mgetline(s, MAXLINE); + + reverse(s); + + printf("%s", s); + + return 0; +} \ No newline at end of file diff --git a/source/cprogramming/chapter4/cprogs/ex_4.14_swap_t_x_y.c b/source/cprogramming/chapter4/cprogs/ex_4.14_swap_t_x_y.c index bce3aaab..d993be5b 100644 --- a/source/cprogramming/chapter4/cprogs/ex_4.14_swap_t_x_y.c +++ b/source/cprogramming/chapter4/cprogs/ex_4.14_swap_t_x_y.c @@ -1,27 +1,17 @@ -/** - * Exercise 4.14 of The C Programming Language by Brian Kernighan and Dennis - * Ritchie - * - * Write a macro swap(t,x,y) that interchanges two arguments of type t. (Block - * structure will help.) - * - */ +/* a macro swap(t,x,y) that interchanges two arguments of type t */ -#include +#include -#define swap(t, x, y) \ - { \ - t temp; \ - temp = x; \ - x = y; \ - y = temp; \ - } +#define swap(t, x, y) { t _z; \ + _z = x; \ + x = y; \ + y = _z; } -int main() { - int x = 1; - int y = 2; - printf("x = %d, y = %d\n", x, y); - swap(int, x, y); - printf("x = %d, y = %d\n", x, y); - return 0; -} +int main(void) { + char x, y; + x = 'a'; + y = 'b'; + printf("x= %c \t y= %c\n", x, y); + swap(char, x, y); + printf("x=%c \t y=%c\n", x, y); +} \ No newline at end of file diff --git a/source/cprogramming/chapter4/cprogs/ex_4.1_strindex_rightmost.c b/source/cprogramming/chapter4/cprogs/ex_4.1_strindex_rightmost.c index dfc27313..297a4a7e 100644 --- a/source/cprogramming/chapter4/cprogs/ex_4.1_strindex_rightmost.c +++ b/source/cprogramming/chapter4/cprogs/ex_4.1_strindex_rightmost.c @@ -1,35 +1,34 @@ -/** - * Exercise 4.1 - The C Programming Language - * - * Write the function strindex(s,t) which returns the position of the rightmost - * occurrence of t in s, or -1 if there is none. - * - */ +/* strindex which returns rightmost occurrence */ -#include +#include -int mstrindex(char s[], char t[]); +int mstrindex(char s[],char t[]) +{ + int i,j,k, result; -int main(int argc, char *argv[]) { + result = -1; + + for(i=0;s[i]!='\0';i++) + { + for(j=i,k=0;t[k]!='\0' && s[j]==t[k];j++,k++) + ; + if(k>0 && t[k] == '\0') + result = i; + } + return result; +} + +int main(void) +{ char line[] = "abcdedfabcde"; char pattern[] = "abc"; int found; - found = mstrindex(line, pattern); - printf("Found: %d\n", found); -} + /* It should match the a the 7th position. */ -int mstrindex(char s[], char t[]) { - int i, j, k, result; + found = mstrindex(line, pattern); - result = -1; + printf("Found the right index: %d\n", found); - for (i = 0; s[i] != '\0'; i++) { - for (j = i, k = 0; t[k] != '\0' && s[j] == t[k]; j++, k++) - ; - if (k > 0 && t[k] == '\0') - result = i; - } - return result; -} +} \ No newline at end of file diff --git a/source/cprogramming/chapter4/cprogs/ex_4.2_atof_scientific.c b/source/cprogramming/chapter4/cprogs/ex_4.2_atof_scientific.c index b49979be..75a8003f 100644 --- a/source/cprogramming/chapter4/cprogs/ex_4.2_atof_scientific.c +++ b/source/cprogramming/chapter4/cprogs/ex_4.2_atof_scientific.c @@ -1,7 +1,8 @@ /** - * Exercise 4.2 - Extend atof to handle scientific notation of the form - * 123.45e-6 where a floating-point number may be followed by e or E and - * an optionally signed exponent. + * + * Program demonstrating atof(char s[]).The function which converts the string + * to a floating point value. + * */ #include @@ -9,30 +10,21 @@ #define MAXLINE 100 -double atof(char s[]); -int mgetline(char s[], int lim); - -int main(int argc, char *argv[]) { - char str[MAXLINE]; - double val; - - mgetline(str, MAXLINE); - - val = atof(str); - - printf("%f", val); +int power(int base, int exp) { + int power; + power = 1; + while (exp-- > 0) + power *= base; - return 0; + return power; } -double atof(char s[]) { +double myatof(char s[]) { double val, pow; int sign, i, esign, exp; - int power(int base, int exp); - for (i = 0; isspace(s[i]); i++) - ; + for (i = 0; isspace(s[i]); i++); sign = (s[i] == '-') ? -1 : 1; @@ -52,48 +44,40 @@ double atof(char s[]) { if (s[i] == 'e' || s[i] == 'E') i++; - - if (s[i] == '+') - esign = 1; - else if (s[i] == '-') - esign = -1; - else - esign = 1; + if (s[i] == '+' || s[i] == '-') { + esign = s[i]; + i++; + } for (exp = 0; isdigit(s[i]); i++) - exp = 10 * exp + (s[i] - '0'); + exp = 10.0 * exp + (s[i] - '0'); - if (esign == 1) - val = (val / pow) * power(exp, 10); + if (esign == '-') + return sign * (val / pow) / power(10, exp); else - val = (val / pow) / power(exp, 10); - return sign * val; + return sign * (val / pow) * power(10, exp); } -int mgetline(char s[], int lim) { - int c, i; +int mgetline(char line[], int lim) { + int i, c; for (i = 0; i < lim - 1 && (c = getchar()) != EOF && c != '\n'; ++i) - s[i] = c; - - if (c == '\n') { - s[i] = c; - ++i; - } + line[i] = c; - s[i] = '\0'; + if (c == '\n') + line[i++] = c; - return i; + line[i] = '\0'; } -int power(int base, int exp) { - int i, p; - - p = 1; +int main(void) { + char str[MAXLINE]; + double num; + mgetline(str, MAXLINE); - for (i = 1; i <= exp; ++i) - p = p * base; + num = myatof(str); + printf("%f", num); - return p; + return 0; } diff --git a/source/cprogramming/chapter4/cprogs/ex_4.3_rpn_modulus_negative.c b/source/cprogramming/chapter4/cprogs/ex_4.3_rpn_modulus_negative.c index 97c59bb4..8e861943 100644 --- a/source/cprogramming/chapter4/cprogs/ex_4.3_rpn_modulus_negative.c +++ b/source/cprogramming/chapter4/cprogs/ex_4.3_rpn_modulus_negative.c @@ -1,11 +1,11 @@ /** - * Exercise 4.3 of The C Programming Language by Brian W. Kernighan and Dennis - * Ritchie. + * Adding the Modulus operator and provision for negative numbers + * Program is given the input in a single and and it print the output upon + * getting a \n character. For e.g: 10 10 + 100 + 2 * 240 * - * RPN modulus operator and negative numbers. - * - */ + **/ +#include #include #include #include @@ -14,68 +14,78 @@ #define MAXOP 100 #define NUMBER '0' +#define BUFSIZE 100 + +#define MAXVAL 100 + +int sp = 0; +int bufp = 0; + +double val[MAXVAL]; +char buf[BUFSIZE]; + +int getch(void); + +void ungetch(int); + int getop(char[]); + void push(double); + double pop(void); -/* Reverse Polish Calculator */ +/* reverse polish calculator */ -int main(int argc, char *argv[]) { +int main(void) { int type; double op2; char s[MAXOP]; while ((type = getop(s)) != EOF) { switch (type) { - case NUMBER: - push(atof(s)); - break; - case '+': - push(pop() + pop()); - break; - case '*': - push(pop() * pop()); - break; - case '-': - push(pop() - pop()); - break; - case '/': - op2 = pop(); - if (op2 != 0.0) { - push(pop() / op2); - } else { - printf("error: zero divisor\n"); - } - break; - case '%': - op2 = pop(); - if (op2 != 0.0) { - push(fmod(pop(), op2)); - } else { - printf("error: zero divisor\n"); - } - break; - case '\n': - printf("\t%.8g\n", pop()); - break; - default: - printf("error: unknown command %s\n", s); - break; + case NUMBER: + push(atof(s)); + break; + case '+': + push(pop() + pop()); + break; + case '*': + push(pop() * pop()); + break; + case '-': + op2 = pop(); + push(pop() - op2); + break; + case '/': + op2 = pop(); + if (op2 != 0.0) + push(pop() / op2); + else + printf("error:zero divisor\n"); + break; + case '%': + op2 = pop(); + if (op2 != 0.0) + push(fmod(pop(), op2)); + else + printf("erro:zero divisor\n"); + break; + case '\n': + printf("\t%.8g\n", pop()); + break; + default: + printf("error: unknown command %s\n", s); + break; } } return 0; } -#define MAXVAL 100 - -int sp = 0; -double val[MAXVAL]; - void push(double f) { if (sp < MAXVAL) val[sp++] = f; else - printf("error: stack full, can't push %g\n", f); + printf("error:stack full, cant push %g\n", f); } double pop(void) { @@ -87,53 +97,30 @@ double pop(void) { } } -#include - -int getch(void); -void ungetch(int); - int getop(char s[]) { int i, c; - - while ((s[0] = c = getch()) == ' ' || c == '\t') - ; - + while ((s[0] = c = getch()) == ' ' || c == '\t'); s[1] = '\0'; - if (!isdigit(c) && c != '.' && c != '-') - return c; - + return c; // not a number i = 0; - - if (c == '-' || isdigit(c)) - while (isdigit(s[++i] = c = getch())) - ; - - if (c == '.') - while (isdigit(s[++i] = c = getch())) - ; - + if (c == '-' || isdigit(c)) // collect integer part along with '-' + while (isdigit(s[++i] = c = getch())); + if (c == '.') // collect fraction part + while (isdigit(s[++i] = c = getch())); s[i] = '\0'; - if (c != EOF) ungetch(c); - if (strcmp(s, "-") == 0) - return "-"; - + return '-'; return NUMBER; } -#define BUFSIZE 100 - -char buf[BUFSIZE]; -int bufp = 0; - -int getch(void) { return (bufp > 0) ? buf[--bufp] : getchar(); } - void ungetch(int c) { if (bufp >= BUFSIZE) printf("ungetch: too many characters\n"); else buf[bufp++] = c; } + +int getch(void) { return (bufp > 0) ? buf[--bufp] : getchar(); } diff --git a/source/cprogramming/chapter4/cprogs/ex_4.4_rpn_top_two_elements.c b/source/cprogramming/chapter4/cprogs/ex_4.4_rpn_top_two_elements.c index a5ade1c0..b0befcd5 100644 --- a/source/cprogramming/chapter4/cprogs/ex_4.4_rpn_top_two_elements.c +++ b/source/cprogramming/chapter4/cprogs/ex_4.4_rpn_top_two_elements.c @@ -1,88 +1,149 @@ -/** - * Exercise 4.4 - The C Programming Language by Dennis M. Ritchie and Brian W. - * Kernighan - * - * Add commands to print the top elements of the stack without popping, to - * duplicate it, and to swap the top two elements. - * Add a command to clear the stack. - */ - +#include #include #include #include #define MAXOP 100 #define NUMBER '0' +#define BUFSIZE 100 +#define MAXVAL 100 + +int bufp = 0; +int sp = 0; +double val[MAXVAL]; +char buf[BUFSIZE]; + +int getch(void); + +void ungetch(int); int getop(char[]); + void push(double); + double pop(void); -/* Reverse Polish calculator */ +/* reverse polish calculator */ -int main(int argc, char *argv[]) { +int main(void) { int type; - double op2; + double op2, op1; char s[MAXOP]; + void clearsp(void); - while (--argc > 0) { - type = getop(*++argv); + while ((type = getop(s)) != EOF) { switch (type) { - case NUMBER: - push(atof(*argv)); - break; - case '+': - push(pop() + pop()); - break; - case '*': - push(pop() * pop()); - break; - case '-': - op2 = pop(); - push(pop() - op2); - break; - case '/': - op2 = pop(); - if (op2 != 0.0) - push(pop() / op2); - else - printf("error: zero divisor\n"); - break; - case '%': - op2 = pop(); - if (op2 != 0.0) - push(fmod(pop(), op2)); - else - printf("error: zero divisor\n"); - break; - - case 'p': - op2 = pop(); - printf("\t%.8g\n", op2); - push(op2); - break; - case 'd': - op2 = pop(); - push(op2); - push(op2); - break; - case 's': - op2 = pop(); - double op3 = pop(); - push(op2); - push(op3); - break; - case 'c': - while (pop() != 0.0) - ; - break; - case '\n': - printf("\t%.8g\n", pop()); - break; - default: - printf("error: unknown command %s\n", *argv); - break; + case NUMBER: + push(atof(s)); + break; + case '+': + push(pop() + pop()); + break; + case '*': + push(pop() * pop()); + break; + case '-': + op2 = pop(); + push(pop() - op2); + break; + case '/': + op2 = pop(); + if (op2 != 0.0) + push(pop() / op2); + else + printf("error:zero divisor\n"); + break; + case '%': + op2 = pop(); + if (op2 != 0.0) + push(fmod(pop(), op2)); + else + printf("erro:zero divisor\n"); + break; + case '?': + op2 = pop(); + printf("\t%.8g\n", op2); + push(op2); + break; + case 'c': + clearsp(); + break; + case 'd': + op2 = pop(); + push(op2); + push(op2); + break; + case 's': + op1 = pop(); + op2 = pop(); + push(op1); + push(op2); + break; + case '\n': + printf("\t%.8g\n", pop()); + break; + default: + printf("error: unknown command %s\n", s); + break; } } return 0; } + +void push(double f) { + if (sp < MAXVAL) + val[sp++] = f; + else + printf("error:stack full, cant push %g\n", f); +} + +double pop(void) { + if (sp > 0) + return val[--sp]; + else { + printf("error: stack empty\n"); + return 0.0; + } +} + +void clearsp(void) { sp = 0; } + +int getop(char s[]) { + int i, c; + + while ((s[0] = c = getch()) == ' ' || c == '\t'); + s[1] = '\0'; + + i = 0; + if (!isdigit(c) && c != '.' && c != '-') + return c; + + if (c == '-') + if (isdigit(c = getch()) || c == '.') + s[++i] = c; + else { + if (c != EOF) + ungetch(c); + return '-'; + } + + if (isdigit(c)) + while (isdigit(s[++i] = c = getch())); + + if (c == '.') + while (isdigit(s[++i] = c = getch())); + + s[i] = '\0'; + if (c != EOF) + ungetch(c); + return NUMBER; +} + +int getch(void) { return (bufp > 0) ? buf[--bufp] : getchar(); } + +void ungetch(int c) { + if (bufp >= BUFSIZE) + printf("ungetch: too many characters\n"); + else + buf[bufp++] = c; +} \ No newline at end of file diff --git a/source/cprogramming/chapter4/cprogs/ex_4.5_calculator_math_functions.c b/source/cprogramming/chapter4/cprogs/ex_4.5_calculator_math_functions.c index 578f6234..21c83a19 100644 --- a/source/cprogramming/chapter4/cprogs/ex_4.5_calculator_math_functions.c +++ b/source/cprogramming/chapter4/cprogs/ex_4.5_calculator_math_functions.c @@ -1,105 +1,112 @@ /** - * Exercise 4.5 from The C Programming Language by Brian Kernighan and Dennis - * Ritchie - * - * Add access to library functions like sin, exp, and pow. See in - * Appendix B, Section 4. - */ - -#include /* for math functions */ + * compile with -lm flag(the static math library) + **/ + +#include +#include #include -#include /* for atof() */ +#include +#include + +#define MAXOP 100 +#define NUMBER '0' +#define NAME 'n' +#define BUFSIZE 100 +#define MAXVAL 100 -#define MAXOP 100 /* max size of operand or operator */ -#define NUMBER '0' /* signal that a number was found */ -#define NAME 'n' /* signal that a name was found */ +int sp = 0; +double val[MAXVAL]; +char buf[BUFSIZE]; +int bufp = 0; + +int getch(void); + +void ungetch(int); int getop(char[]); + void push(double); + double pop(void); + void mathfnc(char[]); -void clearsp(void); -int main(int argc, char *argv[]) { +/* reverse polish calculator */ +int main(void) { int type; double op2, op1; char s[MAXOP]; + void clearsp(void); while ((type = getop(s)) != EOF) { switch (type) { - case NUMBER: - push(atof(s)); - break; - case NAME: - mathfnc(s); - break; - case '+': - push(pop() + pop()); - break; - case '*': - push(pop() * pop()); - break; - case '-': - op2 = pop(); - push(pop() - op2); - break; - case '/': - op2 = pop(); - if (op2 != 0.0) - push(pop() / op2); - else - printf("error: zero divisor\n"); - break; - case '%': - op2 = pop(); - if (op2 != 0.0) - push(fmod(pop(), op2)); - else - printf("error: zero divisor\n"); - break; - case '?': - op2 = pop(); - printf("\t%.8g\n", op2); - push(op2); - break; - case 'c': - clearsp(); - break; - case 'd': - op2 = pop(); - push(op2); - push(op2); - break; - case 's': - op1 = pop(); - op2 = pop(); - push(op1); - push(op2); - break; - case '\n': - printf("\t%.8g\n", pop()); - break; - default: - printf("error: unknown command %s\n", s); - break; + case NUMBER: + push(atof(s)); + break; + case NAME: + mathfnc(s); + break; + case '+': + push(pop() + pop()); + break; + case '*': + push(pop() * pop()); + break; + case '-': + op2 = pop(); + push(pop() - op2); + break; + case '/': + op2 = pop(); + if (op2 != 0.0) + push(pop() / op2); + else + printf("error:zero divisor\n"); + break; + case '%': + op2 = pop(); + if (op2 != 0.0) + push(fmod(pop(), op2)); + else + printf("erro:zero divisor\n"); + break; + case '?': + op2 = pop(); + printf("\t%.8g\n", op2); + push(op2); + break; + case 'c': + clearsp(); + break; + case 'd': + op2 = pop(); + push(op2); + push(op2); + break; + case 's': + op1 = pop(); + op2 = pop(); + push(op1); + push(op2); + break; + case '\n': + printf("\t%.8g\n", pop()); + break; + default: + printf("error: unknown command %s\n", s); + break; } } return 0; } -#define MAXVAL 100 /* maximum depth of val stack */ -int sp = 0; /* next free stack position */ -double val[MAXVAL]; /* value stack */ - -/* push: push f onto value stack */ void push(double f) { if (sp < MAXVAL) val[sp++] = f; else - printf("error: stack full, can't push %g\n", f); + printf("error:stack full, cant push %g\n", f); } -/* pop: pop and return top value from stack */ double pop(void) { if (sp > 0) return val[--sp]; @@ -111,80 +118,67 @@ double pop(void) { void clearsp(void) { sp = 0; } -#include -#include - -int getch(void); -void ungetch(int); - -/* getop: get next operator or numeric operand */ int getop(char s[]) { int i, c; - static int lastc = 0; - if (lastc == 0) - c = getch(); - else { - c = lastc; - lastc = 0; - } - - while ((s[0] = c) == ' ' || c == '\t') - c = getch(); + while ((s[0] = c = getch()) == ' ' || c == '\t'); s[1] = '\0'; + i = 0; if (islower(c)) { - while (islower(s[++i] = c = getch())) - ; + while (islower(s[++i] = c = getch()));; s[i] = '\0'; if (c != EOF) - lastc = c; + ungetch(c); if (strlen(s) > 1) return NAME; else - return c; + /*return c; this line was bad since when s < 1, the array s only has + one character s[0], therofore, this character must be retorned in + order to see if it is d,?,s etc. The character c instead contain + whatever non-lower value wich always will result in a command + uknown*/ + + return s[0]; } + if (!isdigit(c) && c != '.' && c != '-') - return c; /* not a number */ - if (c == '-') { + return c; + + if (c == '-') if (isdigit(c = getch()) || c == '.') - s[++i] = c; /* negative number */ + s[++i] = c; else { if (c != EOF) - lastc = c; - return '-'; /* minus sign */ + ungetch(c); + return '-'; } - } - if (isdigit(c)) /* collect integer part */ - while (isdigit(s[++i] = c = getch())) - ; - if (c == '.') /* collect fraction part */ - while (isdigit(s[++i] = c = getch())) - ; + + if (isdigit(c)) + while (isdigit(s[++i] = c = getch())); + + if (c == '.') + while (isdigit(s[++i] = c = getch())); + s[i] = '\0'; if (c != EOF) - lastc = c; + ungetch(c); return NUMBER; } -#define BUFSIZE 100 - -char buf[BUFSIZE]; /* buffer for ungetch */ -int bufp = 0; /* next free position in buf */ +int getch(void) { return (bufp > 0) ? buf[--bufp] : getchar(); } -int getch(void) { /* get a (possibly pushed back) character */ - return (bufp > 0) ? buf[--bufp] : getchar(); -} - -void ungetch(int c) { /* push character back on input */ +void ungetch(int c) { if (bufp >= BUFSIZE) printf("ungetch: too many characters\n"); else buf[bufp++] = c; } +/* mathfnc: check the string s for supported math function */ void mathfnc(char s[]) { double op2; + if (strcmp(s, "sin") == 0) push(sin(pop())); else if (strcmp(s, "cos") == 0) @@ -195,5 +189,5 @@ void mathfnc(char s[]) { op2 = pop(); push(pow(pop(), op2)); } else - printf("error: %s not supported\n", s); -} + printf("error: %s is not supported\n", s); +} \ No newline at end of file diff --git a/source/cprogramming/chapter4/cprogs/ex_4.6_calculator_variables.c b/source/cprogramming/chapter4/cprogs/ex_4.6_calculator_variables.c index b2b54eae..0f5e5516 100644 --- a/source/cprogramming/chapter4/cprogs/ex_4.6_calculator_variables.c +++ b/source/cprogramming/chapter4/cprogs/ex_4.6_calculator_variables.c @@ -1,37 +1,36 @@ -/** - * - * Exercise 4.6 of The C Programming Language by Brian Kernighan and Dennis - * Ritchie. - * - * Add commands for handling variables. (It's easy to provide twenty-six - * variables with single-letter names.) - * - * Add a variable for the most recently printed value. - */ - +#include #include #include #define MAXOP 100 #define NUMBER '0' +#define BUFSIZE 100 +#define MAXVAL 100 + +char buf[BUFSIZE]; +int bufp = 0; +int sp = 0; +double val[MAXVAL]; int getop(char[]); void push(double); double pop(void); -int main(int argc, char *argv[]) { - int type; - int var = 0; +int getch(void); +void ungetch(int); + +/* reverse polish calculator */ - double op2; - double v = 0.0; +int main(void) { + int type, var = 0; + double op2, v; + char s[MAXOP]; double variable[26]; - while (--argc > 0) { - type = getop(*++argv); + while ((type = getop(s)) != EOF) { switch (type) { case NUMBER: - push(atof(*argv)); + push(atof(s)); break; case '+': push(pop() + pop()); @@ -48,47 +47,19 @@ int main(int argc, char *argv[]) { if (op2 != 0.0) push(pop() / op2); else - printf("error: zero divisor\n"); - break; - case '%': - op2 = pop(); - if (op2 != 0.0) - push((int)pop() % (int)op2); - else - printf("error: zero divisor\n"); + printf("error:zero divisor\n"); break; case '=': pop(); if (var >= 'A' && var <= 'Z') variable[var - 'A'] = pop(); else - printf("error: no variable name\n"); - break; - case 'v': - push(v); + printf("error: novariablename\n"); break; - case 'V': + + case '\n': v = pop(); - push(v); - break; - case 's': - op2 = pop(); - push(pop()); - push(op2); - break; - case 'c': - while (pop() != 0.0) - ; - break; - case 'd': - op2 = pop(); - push(op2); - push(op2); - break; - case 'p': - op2 = pop(); - printf("\t%.8g\n", op2); - push(op2); + printf("\t%.8g\n", v); break; default: if (type >= 'A' && type <= 'Z') @@ -96,7 +67,7 @@ int main(int argc, char *argv[]) { else if (type == 'v') push(v); else - printf("error: unknown command %s\n", *argv); + printf("error: unknown command %s\n", s); break; } var = type; @@ -104,16 +75,11 @@ int main(int argc, char *argv[]) { return 0; } -#define MAXVAL 100 - -int sp = 0; -double val[MAXVAL]; - void push(double f) { if (sp < MAXVAL) val[sp++] = f; else - printf("error: stack full, can't push %g\n", f); + printf("error:stack full, cant push %g\n", f); } double pop(void) { @@ -125,11 +91,6 @@ double pop(void) { } } -#include - -int getch(void); -void ungetch(int); - int getop(char s[]) { int i, c; @@ -138,24 +99,22 @@ int getop(char s[]) { s[1] = '\0'; if (!isdigit(c) && c != '.') return c; + i = 0; if (isdigit(c)) while (isdigit(s[++i] = c = getch())) ; + if (c == '.') while (isdigit(s[++i] = c = getch())) ; + s[i] = '\0'; if (c != EOF) ungetch(c); return NUMBER; } -#define BUFSIZE 100 - -char buf[BUFSIZE]; -int bufp = 0; - int getch(void) { return (bufp > 0) ? buf[--bufp] : getchar(); } void ungetch(int c) { diff --git a/source/cprogramming/chapter4/cprogs/ex_4.7_ungets.c b/source/cprogramming/chapter4/cprogs/ex_4.7_ungets.c index 03e767b7..168aac21 100644 --- a/source/cprogramming/chapter4/cprogs/ex_4.7_ungets.c +++ b/source/cprogramming/chapter4/cprogs/ex_4.7_ungets.c @@ -1,66 +1,66 @@ /** - * Exercise 4.7 of The C Programming Language by Brian Kernighan and Dennis - * Ritchie - * - * Write a routine ungets(s) that will push back an entire string onto the - * input. Should ungets know about buf and bufp, or should it just use ungetch? - * - */ + * Write a routine ungets(s) that will push back an entire string onto + * the input. Should ungets(s) know about buf and bufp or + * should it handle it to ungetch() + **/ #include #include -#define BUFSIZE 100 -#define MAXLINE 1000 +#define MAXBUF 100 +#define MAXLINE 100 -char buf[BUFSIZE]; int bufp = 0; +int buf[MAXBUF]; int getch(void); -void ungetch(int); + +void ungetch(int c); + void ungets(char s[]); -int mgetline(char s[], int lim); -int main(int argc, char *argv[]) { +int mgetline(char line[], int maxline); + +int main(void) { char line[MAXLINE]; - int len; - - while ((len = mgetline(line, MAXLINE)) > 0) { - ungets(line); - while ((len = mgetline(line, MAXLINE)) > 0) { - printf("%s", line); - } - } + int c; + + mgetline(line, MAXLINE); + + ungets(line); + + while ((c = getch()) != EOF) + putchar(c); + return 0; } int mgetline(char s[], int lim) { - int c, i; + int i, c; - for (i = 0; i < lim - 1 && (c = getchar()) != EOF && c != '\n'; ++i) { + for (i = 0; i < lim - 1 && (c = getchar()) != EOF && c != '\n'; ++i) s[i] = c; - } - if (c == '\n') { - s[i] = c; - ++i; - } + + if (c == '\n') + s[i++] = c; + s[i] = '\0'; - return i; } -int getch(void) { return (bufp > 0) ? buf[--bufp] : getchar(); } +void ungets(char s[]) { + int i; + + i = strlen(s); + + while (i > 0) + ungetch(s[--i]); +} void ungetch(int c) { - if (bufp >= BUFSIZE) { + if (bufp >= MAXBUF) printf("ungetch: too many characters\n"); - } else { + else buf[bufp++] = c; - } } -void ungets(char s[]) { - int len = strlen(s); - while (len > 0) { - ungetch(s[--len]); - } -} +int getch(void) { return (bufp > 0) ? buf[--bufp] : getchar(); } diff --git a/source/cprogramming/chapter4/cprogs/ex_4.8_getch_ungetch_pushback.c b/source/cprogramming/chapter4/cprogs/ex_4.8_getch_ungetch_pushback.c new file mode 100644 index 00000000..00d71525 --- /dev/null +++ b/source/cprogramming/chapter4/cprogs/ex_4.8_getch_ungetch_pushback.c @@ -0,0 +1,45 @@ +/** + * Suppose that there will never be more than one character + * for pushback. Modify getch and ungetch accordingly. + **/ + +#include + +char buf = 0; + +/* getch: get a (possibly) pushed back character */ +int getch(void) +{ + int c; + + if(buf != 0) + c = buf; + else + c = getchar(); + + buf = 0; + return c; +} + +/* ungetch: push a character back into input */ +void ungetch(int c) +{ + if(buf != 0) + printf("ungetch: too many characters\n"); + else + buf = c; +} + +int main(void) +{ + int c; + + c = '*'; + + ungetch(c); + + while((c=getch()) != EOF) + putchar(c); + + return 0; +} diff --git a/source/cprogramming/chapter4/cprogs/ex_4.9_getch_ungetch_eof.c b/source/cprogramming/chapter4/cprogs/ex_4.9_getch_ungetch_eof.c index f714aeeb..d72b8e2a 100644 --- a/source/cprogramming/chapter4/cprogs/ex_4.9_getch_ungetch_eof.c +++ b/source/cprogramming/chapter4/cprogs/ex_4.9_getch_ungetch_eof.c @@ -1,40 +1,46 @@ /** - * Exercise 4.9 of The C Programming Language by Brian Kernighan and Dennis - * Ritchie - * - * Our getch and ungetch do not handle a pushed-back EOF correctly. - * - * Decide what their properties ought to be if an EOF is pushed back, then - * implement your design. - * - */ - -#include -#include + * getch and ungetch to handle EOF Character. In all the ungetch and getch + * functions written so far, the buf is declared as char buf[BUFSIZ]. + * Changing this to int buf[BUFSIZ] enable it to handle EOF. As EOF is an + * integer declared in stdio.h having the value -1 + **/ -#define BUFSIZE 100 +#include -char buf[BUFSIZE]; +#define BUFSIZE 100 -int bufp = 0; +int getch(void); -int getch(void) { return (bufp > 0) ? buf[--bufp] : getchar(); } +void ungetch(int c); -void ungetch(int c) { - if (bufp >= BUFSIZE) { - printf("ungetch: too many characters\n"); - } else { - buf[bufp++] = c; - } -} +int buf[BUFSIZE]; /* buffer for ungetch */ +int bufp = 0; /* next free position in buf */ -int main(int argc, char *argv[]) { +int main(void) { int c; + c = '*'; - while ((c = getch()) != EOF) { + ungetch(c); + + while ((c = getch()) != EOF) putchar(c); - } return 0; } + +/* getch: get a (possibly pushed back) character */ + +int getch(void) { + return (bufp > 0) ? buf[--bufp] : getchar(); +} + +/* ungetch: push a character back onto the input */ + +void ungetch(int c) { + if (bufp >= BUFSIZE) + printf("ungetch: too many characters \n"); + else + buf[bufp++] = c; +} + diff --git a/source/cprogramming/chapter4/cprogs/sec_4.2.c b/source/cprogramming/chapter4/cprogs/sec_4.2.c deleted file mode 100644 index bf5f95cf..00000000 --- a/source/cprogramming/chapter4/cprogs/sec_4.2.c +++ /dev/null @@ -1,49 +0,0 @@ -/** - * - * Section 4.2 The C Programming Language - * - * Convert the string s to a double. - */ - -#include -#include - -double atof(char s[]); - -int main(int argc, char *argv[]) { - char s[8] = "1234.56"; - double d = atof(s); - printf("%f\n", d); - return 0; -} - -double atof(char s[]) { - double val, power; - int i, sign; - - /** Skip white space */ - for (i = 0; isspace(s[i]); i++) { - ; - } - - sign = (s[i] == '-') ? -1 : 1; - - if (s[i] == '+' || s[i] == '-') { - i++; - } - - for (val = 0.0; isdigit(s[i]); i++) { - val = 10.0 * val + (s[i] - '0'); - } - - if (s[i] == '.') { - i++; - } - - for (power = 1.0; isdigit(s[i]); i++) { - val = 10.0 * val + (s[i] - '0'); - power *= 10.0; - } - - return (sign * val) / power; -} diff --git a/source/cprogramming/chapter4/cprogs/sec_4.3.c b/source/cprogramming/chapter4/cprogs/sec_4.3.c deleted file mode 100644 index 7bd8ad8f..00000000 --- a/source/cprogramming/chapter4/cprogs/sec_4.3.c +++ /dev/null @@ -1,137 +0,0 @@ -/** - * Section 4.3 of the book "The C Programming Language" - * by Brian W. Kernighan and Dennis M. Ritchie. - * - * Reverse Polish calculator - * - * Revision history: - * - * Senthil Kumaran - Using C99 instead of K&R C, Orgnized the code for - * readability. - * - */ - -#include -#include -#include /* for atof() */ - -#define MAXOP 100 /* max size of operand or operator */ -#define NUMBER '0' /* signal that a number was found */ - -#define BUFSIZE 100 - -int getop(char[]); -void push(double); -double pop(void); -int getch(void); -void ungetch(int); - -/* reverse Polish calculator */ - -int main(int argc, char *argv[]) { - int type; - double op2; - char s[MAXOP]; - - while ((type = getop(s)) != EOF) { - switch (type) { - case NUMBER: - push(atof(s)); - break; - case '+': - push(pop() + pop()); - break; - case '*': - push(pop() * pop()); - break; - case '-': - op2 = pop(); - push(pop() - op2); - break; - case '/': - op2 = pop(); - if (op2 != 0.0) - push(pop() / op2); - else - printf("error: zero divisor\n"); - break; - case '\n': - printf("\t%.8g\n", pop()); - break; - default: - printf("error: unknown command %s\n", s); - break; - } - } -} - -#define MAXVAL 100 - -int sp = 0; -double val[MAXVAL]; - -void push(double f) { - if (sp < MAXVAL) - val[sp++] = f; - else - printf("error: stack full, can't push %g\n", f); -} - -double pop(void) { - if (sp > 0) - return val[--sp]; - else { - printf("error: stack empty\n"); - return 0.0; - } -} - -int getop(char s[]) { - int i, c; - - while ((s[0] = c = getch()) == ' ' || c == '\t') - ; - s[1] = '\0'; - - i = 0; - - if (!isdigit(c) && c != '.' && c != '-') - return c; /* not a number */ - - if (c == '-') { - if (isdigit(c = getch()) || c == '.') - s[++i] = c; /* negative number */ - else { - if (c != EOF) - ungetch(c); - return '-'; /* minus sign */ - } - } - - if (isdigit(c)) /* collect integer part */ - while (isdigit(s[++i] = c = getch())) - ; - - if (c == '.') /* collect fraction part */ - while (isdigit(s[++i] = c = getch())) - ; - - s[i] = '\0'; - - if (c != EOF) - ungetch(c); - - return NUMBER; -} - -char buf[BUFSIZE]; -int bufp = 0; - -int getch(void) { return (bufp > 0) ? buf[--bufp] : getchar(); } - -void ungetch(int c) { - if (bufp >= BUFSIZE) - printf("ungetch: too many characters\n"); - else - buf[bufp++] = c; -} diff --git a/source/cprogramming/chapter4/ex_4.10_calculator_getline.rst b/source/cprogramming/chapter4/ex_4.10_calculator_getline.rst index afea4960..128231ff 100644 --- a/source/cprogramming/chapter4/ex_4.10_calculator_getline.rst +++ b/source/cprogramming/chapter4/ex_4.10_calculator_getline.rst @@ -14,7 +14,7 @@ getch and ungetch unnecessary. Revise the calculator to use this approach. Explanation =========== -This program uses `mgetline` to get the characters and operands from the input +This program uses `_getline` to get the characters and operands from the input and and proceeds with the RPN calculator logic. This is the main part of the program. @@ -29,7 +29,7 @@ This is the main part of the program. int c,i; if(line[li] == '\0') - if(mgetline(line,MAXLINE) == 0) + if(_getline(line,MAXLINE) == 0) return EOF; else li =0; @@ -59,7 +59,7 @@ This is the main part of the program. } -From the mgetline function, it takes the input in the line character array, and +From the _getline function, it takes the input in the line character array, and if if the line is `\0` only, then we define that as EOF and return `EOF`. Then we assign to `c` the value present at `line` and look for various conditions like, if line is a space or tab character, we simply skip it. If we encouter c @@ -79,9 +79,6 @@ An example execution will look like this. Visualize It ============ -.. raw:: html - - * https://pythontutor.com/c.html Try It diff --git a/source/cprogramming/chapter4/ex_4.9_getch_ungetch_eof.rst b/source/cprogramming/chapter4/ex_4.9_getch_ungetch_eof.rst index 3b4ac759..14f507ba 100644 --- a/source/cprogramming/chapter4/ex_4.9_getch_ungetch_eof.rst +++ b/source/cprogramming/chapter4/ex_4.9_getch_ungetch_eof.rst @@ -15,7 +15,7 @@ design. Explanation =========== -The previous `getch` and `ungetch` functions declared buf as `char buf[BUFSIZ]`. +The previous `getch` and `ungetch` functions declared buf as `char buf[BUFSIZE]`. This has a limitation wherein the when an `EOF` character is encountered, it wont be stored in the buffer. The EOF character is an integer type. This problem can be solved by declaring our buf to be of integer type, like `int diff --git a/source/cprogramming/chapter4/index.rst b/source/cprogramming/chapter4/index.rst index 628efb96..9d7c2c94 100644 --- a/source/cprogramming/chapter4/index.rst +++ b/source/cprogramming/chapter4/index.rst @@ -5,8 +5,6 @@ Chapter 4 .. toctree:: :maxdepth: 1 - ex_4.1_strindex_rightmost - ex_4.2_atof_scientific ex_4.1_strindex_rightmost ex_4.2_atof_scientific ex_4.3_rpn_modulus_negative diff --git a/source/cprogramming/chapter5/cprogs/Ex_4.10_calculator_getline.c b/source/cprogramming/chapter5/cprogs/Ex_4.10_calculator_getline.c deleted file mode 100644 index 6ad8ec41..00000000 --- a/source/cprogramming/chapter5/cprogs/Ex_4.10_calculator_getline.c +++ /dev/null @@ -1,134 +0,0 @@ -/* Revise the Calculator program to use the getline instead of getch and ungetch - */ - -#include -#include /* for atof() */ - -#define MAXOP 100 -#define NUMBER '0' - -int getop(char[]); -void push(double); -double pop(void); - -/* reverse polish notation calculator */ - -int main(void) { - int type; - double op2; - char s[MAXOP]; - - while ((type = getop(s)) != EOF) { - switch (type) { - case NUMBER: - push(atof(s)); - break; - case '+': - push(pop() + pop()); - break; - case '*': - push(pop() * pop()); - break; - case '-': - op2 = pop(); - push(pop() - op2); - break; - case '/': - op2 = pop(); - if (op2 != 0.0) - push(pop() / op2); - break; - case '\n': - printf("\t%.9g\n", pop()); - break; - default: - printf("error: unknown command %s\n", s); - break; - } - } - return 0; -} - -#define MAXVAL 100 /* maximum depth of the val stack */ - -int sp = 0; -double val[MAXVAL]; - -/* push : push f onto value stack */ - -void push(double f) { - if (sp < MAXVAL) - val[sp++] = f; - else - printf("error: stack full,can't push %g\n", f); -} - -/* pop: pop and return top values from stack */ - -double pop(void) { - if (sp > 0) - return val[--sp]; - else { - printf("error: stack empty \n"); - return 0.0; - } -} - -/* using getline instead of getch and ungetch */ - -#include -#define MAXLINE 100 - -int mgetline(char line[], int limit); - -int li = 0; /* input line index */ -char line[MAXLINE]; /* one input line */ - -/* getop: get next operator or numeric operand */ - -int getop(char s[]) { - int c, i; - - if (line[li] == '\0') - if (mgetline(line, MAXLINE) == 0) - return EOF; - else - li = 0; - - while ((s[0] = c = line[li++]) == ' ' || c == '\t') - ; - - s[1] = '\0'; - - if (!isdigit(c) && c != '.') - return c; - - i = 0; - - if (isdigit(c)) - while (isdigit(s[++i] = c = line[li++])) - ; - if (c == '.') - while (isdigit(s[++i] = c = line[li++])) - ; - - s[i] = '\0'; - - li--; - - return NUMBER; -} - -int mgetline(char s[], int lim) { - int i, c; - - for (i = 0; i < lim - 1 && (c = getchar()) != EOF && c != '\n'; ++i) - s[i] = c; - - if (c == '\n') - s[i++] = c; - - s[i] = '\0'; - - return i; -} diff --git a/source/cprogramming/chapter5/cprogs/Ex_4.11_getch_static.c b/source/cprogramming/chapter5/cprogs/Ex_4.11_getch_static.c deleted file mode 100644 index 25946373..00000000 --- a/source/cprogramming/chapter5/cprogs/Ex_4.11_getch_static.c +++ /dev/null @@ -1,122 +0,0 @@ -/* modify getop so that it does not need to use ungetch: Hint: static int lastc - */ - -#include -#include - -#define MAXOP 100 -#define NUMBER '0' - -int getop(char[]); -void push(double); -double pop(void); - -/* reverse polish calculator */ - -int main(void) { - int type; - double op2; - char s[MAXOP]; - - while ((type = getop(s)) != EOF) { - switch (type) { - case NUMBER: - push(atof(s)); - break; - case '+': - push(pop() + pop()); - break; - case '*': - push(pop() * pop()); - break; - case '-': - op2 = pop(); - push(pop() - op2); - break; - case '/': - op2 = pop(); - if (op2 != 0.0) - push(pop() / op2); - break; - case '\n': - printf("\t%.8g\n", pop()); - break; - default: - printf("error: unknown command %s\n", s); - break; - } - } - return 0; -} - -#define MAXVAL 100 - -int sp = 0; -double val[MAXVAL]; - -/* push : push f onto value stack */ - -void push(double f) { - if (sp < MAXVAL) - val[sp++] = f; - else - printf("error: stack full,can't push %g\n", f); -} - -/* pop: pop and return top value from stack */ - -double pop(void) { - if (sp > 0) - return val[--sp]; - else { - printf("error: stack empty\n"); - return 0.0; - } -} - -#include - -int getch(void); - -/* getop: get next operator or numeric operand */ - -int getop(char s[]) { - int c, i; - static int lastc = 0; - - if (lastc == 0) - c = getch(); - else { - c = lastc; - lastc = 0; - } - - while ((s[0] = c) == ' ' || c == '\t') - c = getch(); - - s[1] = '\0'; - - if (!isdigit(c) && c != '.') - return c; - - i = 0; - if (isdigit(c)) - while (isdigit(s[++i] = c = getch())) - ; - if (c == '.') - while (isdigit(s[++i] = c = getch())) - ; - s[i] = '\0'; - - if (c != EOF) - lastc = c; - - return NUMBER; -} - -#define BUFSIZE 100 - -char buf[BUFSIZE]; -int bufp; - -int getch(void) { return (bufp > 0) ? buf[--bufp] : getchar(); } diff --git a/source/cprogramming/chapter5/cprogs/Ex_4.12_recursive_itoa.c b/source/cprogramming/chapter5/cprogs/Ex_4.12_recursive_itoa.c deleted file mode 100644 index d34514f4..00000000 --- a/source/cprogramming/chapter5/cprogs/Ex_4.12_recursive_itoa.c +++ /dev/null @@ -1,38 +0,0 @@ -/* recursive version of itoa; that converts an integer string by calling a - * recursive routine */ - -#include -#include - -#define MAXLEN 100 - -void itoa(int n, char s[]); - -int main(void) { - int n; - char s[MAXLEN]; - - n = 1723; - - itoa(n, s); - - printf("%s", s); - - return 0; -} - -void itoa(int n, char s[]) { - static int i; - - if (n / 10) - itoa(n / 10, s); - else { - i = 0; - if (n < 0) - s[i++] = '-'; - } - - s[i++] = abs(n) % 10 + '0'; - - s[i] = '\0'; -} diff --git a/source/cprogramming/chapter5/cprogs/Ex_4.13_reverse_string.c b/source/cprogramming/chapter5/cprogs/Ex_4.13_reverse_string.c deleted file mode 100644 index ee9785c0..00000000 --- a/source/cprogramming/chapter5/cprogs/Ex_4.13_reverse_string.c +++ /dev/null @@ -1,61 +0,0 @@ -/* a recursive version of revese(s); the string reverse function */ - -#include -#include - -#define MAXLINE 100 - -int mgetline(char line[], int maxline); -void reverse(char s[]); - -int main(void) { - char s[MAXLINE]; - - mgetline(s, MAXLINE); - - reverse(s); - - printf("%s", s); - - return 0; -} - -int mgetline(char s[], int lim) { - int i, c; - - for (i = 0; i < lim - 1 && (c = getchar()) != EOF && c != '\n'; ++i) - s[i] = c; - - if (c == '\n') - s[i++] = '\n'; - - s[i] = '\0'; -} - -void reverse(char s[]) { - - static int i = 0; - static int len; - - int j; - char c; - - if (i == 0) { - len = strlen(s); - } - - j = len - (i + 1); - - if (i < j) { - c = s[i]; - s[i] = s[j]; - s[j] = c; - i++; - reverse(s); - } - - // the algorithm has finished so we have to set i=0 again - else { - i = 0; - } -} diff --git a/source/cprogramming/chapter5/cprogs/Ex_4.14_swap_t_x_y.c b/source/cprogramming/chapter5/cprogs/Ex_4.14_swap_t_x_y.c deleted file mode 100644 index 06ddf692..00000000 --- a/source/cprogramming/chapter5/cprogs/Ex_4.14_swap_t_x_y.c +++ /dev/null @@ -1,20 +0,0 @@ -/* a macro swap(t,x,y) that interchanges two arguments of type t */ - -#include - -#define swap(t, x, y) \ - { \ - t _z; \ - _z = x; \ - x = y; \ - y = _z; \ - } - -int main(void) { - char x, y; - x = 'a'; - y = 'b'; - printf("x= %c \t y= %c\n", x, y); - swap(char, x, y); - printf("x=%c \t y=%c\n", x, y); -} diff --git a/source/cprogramming/chapter5/cprogs/Ex_4.1_strindex_rightmost.c b/source/cprogramming/chapter5/cprogs/Ex_4.1_strindex_rightmost.c deleted file mode 100644 index 2468b1e7..00000000 --- a/source/cprogramming/chapter5/cprogs/Ex_4.1_strindex_rightmost.c +++ /dev/null @@ -1,32 +0,0 @@ -/* strindex which returns rightmost occurance */ - -#include - -int mstrindex(char source[], char searchfor[]); - -int main(void) { - char line[] = "abcdedfabcde"; - char pattern[] = "abc"; - - int found; - - /* It should match the a the 7th position. */ - - found = mstrindex(line, pattern); - - printf("Found the right index: %d\n", found); -} - -int mstrindex(char s[], char t[]) { - int i, j, k, result; - - result = -1; - - for (i = 0; s[i] != '\0'; i++) { - for (j = i, k = 0; t[k] != '\0' && s[j] == t[k]; j++, k++) - ; - if (k > 0 && t[k] == '\0') - result = i; - } - return result; -} diff --git a/source/cprogramming/chapter5/cprogs/Ex_4.2_atof_scientific.c b/source/cprogramming/chapter5/cprogs/Ex_4.2_atof_scientific.c deleted file mode 100644 index dfe9c2aa..00000000 --- a/source/cprogramming/chapter5/cprogs/Ex_4.2_atof_scientific.c +++ /dev/null @@ -1,81 +0,0 @@ -/* Program demonstrating atof(char s[]).The function which converts the string - to a floating point value */ -#include -#include -#define MAXLINE 100 - -double myatof(char s[]); -int mgetline(char line[], int maxline); - -int main(void) { - char str[MAXLINE]; - double num; - mgetline(str, MAXLINE); - - num = myatof(str); - printf("%f", num); - - return 0; -} - -double myatof(char s[]) { - double val, pow; - int sign, i, esign, exp; - int power(int base, int exp); - - for (i = 0; isspace(s[i]); i++) - ; - - sign = (s[i] == '-') ? -1 : 1; - - if (s[i] == '+' || s[i] == '-') - i++; - - for (val = 0.0; isdigit(s[i]); i++) - val = 10.0 * val + (s[i] - '0'); - - if (s[i] == '.') - i++; - - for (pow = 1.0; isdigit(s[i]); i++) { - val = 10.0 * val + (s[i] - '0'); - pow *= 10.0; - } - - if (s[i] == 'e' || s[i] == 'E') - i++; - if (s[i] == '+' || s[i] == '-') { - esign = s[i]; - i++; - } - - for (exp = 0; isdigit(s[i]); i++) - exp = 10.0 * exp + (s[i] - '0'); - - if (esign == '-') - return sign * (val / pow) / power(10, exp); - else - - return sign * (val / pow) * power(10, exp); -} - -int mgetline(char s[], int lim) { - int i, c; - - for (i = 0; i < lim - 1 && (c = getchar()) != EOF && c != '\n'; ++i) - s[i] = c; - - if (c == '\n') - s[i++] = c; - - s[i] = '\0'; -} - -int power(int base, int exp) { - int power; - power = 1; - while (exp-- > 0) - power *= base; - - return power; -} diff --git a/source/cprogramming/chapter5/cprogs/Ex_4.3_rpn_modulus_negative.c b/source/cprogramming/chapter5/cprogs/Ex_4.3_rpn_modulus_negative.c deleted file mode 100644 index 496373a0..00000000 --- a/source/cprogramming/chapter5/cprogs/Ex_4.3_rpn_modulus_negative.c +++ /dev/null @@ -1,128 +0,0 @@ -/* Adding the Modulus operator and provision for negative numbers - * Program is given the input in a single and and it print the output upon - * getting a \n character. - * For e.g: - * - * 10 10 + 100 + 2 * - * 240 - */ - -#include -#include -#include - -#define MAXOP 100 -#define NUMBER '0' - -int getop(char[]); -void push(double); -double pop(void); - -/* reverse polish calculator */ - -int main(void) { - int type; - double op2; - char s[MAXOP]; - - while ((type = getop(s)) != EOF) { - switch (type) { - case NUMBER: - push(atof(s)); - break; - case '+': - push(pop() + pop()); - break; - case '*': - push(pop() * pop()); - break; - case '-': - op2 = pop(); - push(pop() - op2); - break; - case '/': - op2 = pop(); - if (op2 != 0.0) - push(pop() / op2); - else - printf("error:zero divisor\n"); - break; - case '%': - op2 = pop(); - if (op2 != 0.0) - push(fmod(pop(), op2)); - else - printf("erro:zero divisor\n"); - break; - case '\n': - printf("\t%.8g\n", pop()); - break; - default: - printf("error: unknown command %s\n", s); - break; - } - } - return 0; -} - -#define MAXVAL 100 - -int sp = 0; -double val[MAXVAL]; - -void push(double f) { - if (sp < MAXVAL) - val[sp++] = f; - else - printf("error:stack full, cant push %g\n", f); -} - -double pop(void) { - if (sp > 0) - return val[--sp]; - else { - printf("error: stack empty\n"); - return 0.0; - } -} - -#include - -int getch(void); -void ungetch(int); - -int getop(char s[]) { - int i, c; - while ((s[0] = c = getch()) == ' ' || c == '\t') - ; - s[1] = '\0'; - if (!isdigit(c) && c != '.' && c != '-') - return c; // not a number - i = 0; - if (c == '-' || isdigit(c)) // collect integer part along with '-' - while (isdigit(s[++i] = c = getch())) - ; - if (c == '.') // collect fraction part - while (isdigit(s[++i] = c = getch())) - ; - s[i] = '\0'; - if (c != EOF) - ungetch(c); - if (strcmp(s, "-") == 0) - return '-'; - return NUMBER; -} - -#define BUFSIZE 100 - -char buf[BUFSIZE]; -int bufp = 0; - -int getch(void) { return (bufp > 0) ? buf[--bufp] : getchar(); } - -void ungetch(int c) { - if (bufp >= BUFSIZE) - printf("ungetch: too many characters\n"); - else - buf[bufp++] = c; -} diff --git a/source/cprogramming/chapter5/cprogs/Ex_4.4_rpn_top_two_elements.c b/source/cprogramming/chapter5/cprogs/Ex_4.4_rpn_top_two_elements.c deleted file mode 100644 index ad91c978..00000000 --- a/source/cprogramming/chapter5/cprogs/Ex_4.4_rpn_top_two_elements.c +++ /dev/null @@ -1,159 +0,0 @@ -/* Add commands to - - print top element of the stack,without poping - - duplicate it - - swap the top two elements - - Clear the stack */ - -#include -#include -#include - -#define MAXOP 100 -#define NUMBER '0' - -int getop(char[]); -void push(double); -double pop(void); - -/* reverse polish calculator */ - -int main(void) { - int type; - double op2, op1; - char s[MAXOP]; - void clearsp(void); - - while ((type = getop(s)) != EOF) { - switch (type) { - case NUMBER: - push(atof(s)); - break; - case '+': - push(pop() + pop()); - break; - case '*': - push(pop() * pop()); - break; - case '-': - op2 = pop(); - push(pop() - op2); - break; - case '/': - op2 = pop(); - if (op2 != 0.0) - push(pop() / op2); - else - printf("error:zero divisor\n"); - break; - case '%': - op2 = pop(); - if (op2 != 0.0) - push(fmod(pop(), op2)); - else - printf("erro:zero divisor\n"); - break; - case '?': - op2 = pop(); - printf("\t%.8g\n", op2); - push(op2); - break; - case 'c': - clearsp(); - break; - case 'd': - op2 = pop(); - push(op2); - push(op2); - break; - case 's': - op1 = pop(); - op2 = pop(); - push(op1); - push(op2); - break; - case '\n': - printf("\t%.8g\n", pop()); - break; - default: - printf("error: unknown command %s\n", s); - break; - } - } - return 0; -} - -#define MAXVAL 100 - -int sp = 0; -double val[MAXVAL]; - -void push(double f) { - if (sp < MAXVAL) - val[sp++] = f; - else - printf("error:stack full, cant push %g\n", f); -} - -double pop(void) { - if (sp > 0) - return val[--sp]; - else { - printf("error: stack empty\n"); - return 0.0; - } -} - -void clearsp(void) { sp = 0; } - -#include - -int getch(void); -void ungetch(int); - -int getop(char s[]) { - int i, c; - - while ((s[0] = c = getch()) == ' ' || c == '\t') - ; - s[1] = '\0'; - - i = 0; - if (!isdigit(c) && c != '.' && c != '-') - return c; - - if (c == '-') - if (isdigit(c = getch()) || c == '.') - s[++i] = c; - else { - if (c != EOF) - ungetch(c); - return '-'; - } - - if (isdigit(c)) - while (isdigit(s[++i] = c = getch())) - ; - - if (c == '.') - while (isdigit(s[++i] = c = getch())) - ; - - s[i] = '\0'; - if (c != EOF) - ungetch(c); - return NUMBER; -} - -#define BUFSIZE 100 - -char buf[BUFSIZE]; -int bufp = 0; - -int getch(void) { return (bufp > 0) ? buf[--bufp] : getchar(); } - -void ungetch(int c) { - if (bufp >= BUFSIZE) - printf("ungetch: too many characters\n"); - else - buf[bufp++] = c; -} diff --git a/source/cprogramming/chapter5/cprogs/Ex_4.5_calculator_math_functions.c b/source/cprogramming/chapter5/cprogs/Ex_4.5_calculator_math_functions.c deleted file mode 100644 index c5154325..00000000 --- a/source/cprogramming/chapter5/cprogs/Ex_4.5_calculator_math_functions.c +++ /dev/null @@ -1,207 +0,0 @@ -/* Include Mathematical Functions */ -/* Add commands to - - print top element of the stack,without poping - - duplicate it - - swap the top two elements - - Clear the stack */ - -/* IMPORTANT: compile with -lm flag(the static math library) - For eg: gcc -lm rpn-3.c -*/ - -#include -#include -#include - -#define MAXOP 100 -#define NUMBER '0' -#define NAME 'n' - -int getop(char[]); -void push(double); -double pop(void); -void mathfnc(char[]); - -/* reverse polish calculator */ - -int main(void) { - int type; - double op2, op1; - char s[MAXOP]; - void clearsp(void); - - while ((type = getop(s)) != EOF) { - switch (type) { - case NUMBER: - push(atof(s)); - break; - case NAME: - mathfnc(s); - break; - case '+': - push(pop() + pop()); - break; - case '*': - push(pop() * pop()); - break; - case '-': - op2 = pop(); - push(pop() - op2); - break; - case '/': - op2 = pop(); - if (op2 != 0.0) - push(pop() / op2); - else - printf("error:zero divisor\n"); - break; - case '%': - op2 = pop(); - if (op2 != 0.0) - push(fmod(pop(), op2)); - else - printf("erro:zero divisor\n"); - break; - case '?': - op2 = pop(); - printf("\t%.8g\n", op2); - push(op2); - break; - case 'c': - clearsp(); - break; - case 'd': - op2 = pop(); - push(op2); - push(op2); - break; - case 's': - op1 = pop(); - op2 = pop(); - push(op1); - push(op2); - break; - case '\n': - printf("\t%.8g\n", pop()); - break; - default: - printf("error: unknown command %s\n", s); - break; - } - } - return 0; -} - -#define MAXVAL 100 - -int sp = 0; -double val[MAXVAL]; - -void push(double f) { - if (sp < MAXVAL) - val[sp++] = f; - else - printf("error:stack full, cant push %g\n", f); -} - -double pop(void) { - if (sp > 0) - return val[--sp]; - else { - printf("error: stack empty\n"); - return 0.0; - } -} - -void clearsp(void) { sp = 0; } - -#include -#include - -int getch(void); -void ungetch(int); - -int getop(char s[]) { - int i, c; - - while ((s[0] = c = getch()) == ' ' || c == '\t') - ; - s[1] = '\0'; - - i = 0; - if (islower(c)) { - while (islower(s[++i] = c = getch())) - ; - ; - s[i] = '\0'; - if (c != EOF) - ungetch(c); - if (strlen(s) > 1) - return NAME; - else - /*return c; this line was bad since when s < 1, the array s only has - one character s[0], therofore, this character must be retorned in - order to see if it is d,?,s etc. The character c instead contain - whatever non-lower value wich always will result in a command - uknown*/ - - return s[0]; - } - - if (!isdigit(c) && c != '.' && c != '-') - return c; - - if (c == '-') - if (isdigit(c = getch()) || c == '.') - s[++i] = c; - else { - if (c != EOF) - ungetch(c); - return '-'; - } - - if (isdigit(c)) - while (isdigit(s[++i] = c = getch())) - ; - - if (c == '.') - while (isdigit(s[++i] = c = getch())) - ; - - s[i] = '\0'; - if (c != EOF) - ungetch(c); - return NUMBER; -} - -#define BUFSIZE 100 - -char buf[BUFSIZE]; -int bufp = 0; - -int getch(void) { return (bufp > 0) ? buf[--bufp] : getchar(); } - -void ungetch(int c) { - if (bufp >= BUFSIZE) - printf("ungetch: too many characters\n"); - else - buf[bufp++] = c; -} - -/* mathfnc: check the string s for supported math function */ - -void mathfnc(char s[]) { - double op2; - - if (strcmp(s, "sin") == 0) - push(sin(pop())); - else if (strcmp(s, "cos") == 0) - push(cos(pop())); - else if (strcmp(s, "exp") == 0) - push(exp(pop())); - else if (strcmp(s, "pow") == 0) { - op2 = pop(); - push(pow(pop(), op2)); - } else - printf("error: %s is not supported\n", s); -} diff --git a/source/cprogramming/chapter5/cprogs/Ex_4.6_calculator_variables.c b/source/cprogramming/chapter5/cprogs/Ex_4.6_calculator_variables.c deleted file mode 100644 index aeecdf46..00000000 --- a/source/cprogramming/chapter5/cprogs/Ex_4.6_calculator_variables.c +++ /dev/null @@ -1,129 +0,0 @@ -#include -#include - -#define MAXOP 100 -#define NUMBER '0' - -int getop(char[]); -void push(double); -double pop(void); - -/* reverse polish calculator */ - -int main(void) { - int type, var = 0; - double op2, v; - char s[MAXOP]; - double variable[26]; - - while ((type = getop(s)) != EOF) { - switch (type) { - case NUMBER: - push(atof(s)); - break; - case '+': - push(pop() + pop()); - break; - case '*': - push(pop() * pop()); - break; - case '-': - op2 = pop(); - push(pop() - op2); - break; - case '/': - op2 = pop(); - if (op2 != 0.0) - push(pop() / op2); - else - printf("error:zero divisor\n"); - break; - case '=': - pop(); - if (var >= 'A' && var <= 'Z') - variable[var - 'A'] = pop(); - else - printf("error: novariablename\n"); - break; - - case '\n': - v = pop(); - printf("\t%.8g\n", v); - break; - default: - if (type >= 'A' && type <= 'Z') - push(variable[type - 'A']); - else if (type == 'v') - push(v); - else - printf("error: unknown command %s\n", s); - break; - } - var = type; - } - return 0; -} - -#define MAXVAL 100 - -int sp = 0; -double val[MAXVAL]; - -void push(double f) { - if (sp < MAXVAL) - val[sp++] = f; - else - printf("error:stack full, cant push %g\n", f); -} - -double pop(void) { - if (sp > 0) - return val[--sp]; - else { - printf("error: stack empty\n"); - return 0.0; - } -} - -#include - -int getch(void); -void ungetch(int); - -int getop(char s[]) { - int i, c; - - while ((s[0] = c = getch()) == ' ' || c == '\t') - ; - s[1] = '\0'; - if (!isdigit(c) && c != '.') - return c; - - i = 0; - if (isdigit(c)) - while (isdigit(s[++i] = c = getch())) - ; - - if (c == '.') - while (isdigit(s[++i] = c = getch())) - ; - - s[i] = '\0'; - if (c != EOF) - ungetch(c); - return NUMBER; -} - -#define BUFSIZE 100 - -char buf[BUFSIZE]; -int bufp = 0; - -int getch(void) { return (bufp > 0) ? buf[--bufp] : getchar(); } - -void ungetch(int c) { - if (bufp >= BUFSIZE) - printf("ungetch: too many characters\n"); - else - buf[bufp++] = c; -} diff --git a/source/cprogramming/chapter5/cprogs/Ex_4.7_ungets.c b/source/cprogramming/chapter5/cprogs/Ex_4.7_ungets.c deleted file mode 100644 index b03b1ac3..00000000 --- a/source/cprogramming/chapter5/cprogs/Ex_4.7_ungets.c +++ /dev/null @@ -1,65 +0,0 @@ -/** - * - * Write a routine ungets(s) that will push back an entire string onto - * the input. Should ungets(s) know about buf and bufp or - * should it handle it to ungetch() - * - **/ - -#include -#include - -#define MAXBUF 100 -#define MAXLINE 100 - -int bufp = 0; -int buf[MAXBUF]; - -int getch(void); -void ungetch(int c); -void ungets(char s[]); -int mgetline(char line[], int maxline); - -int main(void) { - char line[MAXLINE]; - int c; - - mgetline(line, MAXLINE); - - ungets(line); - - while ((c = getch()) != EOF) - putchar(c); - - return 0; -} - -int mgetline(char s[], int lim) { - int i, c; - - for (i = 0; i < lim - 1 && (c = getchar()) != EOF && c != '\n'; ++i) - s[i] = c; - - if (c == '\n') - s[i++] = c; - - s[i] = '\0'; -} - -void ungets(char s[]) { - int i; - - i = strlen(s); - - while (i > 0) - ungetch(s[--i]); -} - -void ungetch(int c) { - if (bufp >= MAXBUF) - printf("ungetch: too many characters\n"); - else - buf[bufp++] = c; -} - -int getch(void) { return (bufp > 0) ? buf[--bufp] : getchar(); } diff --git a/source/cprogramming/chapter5/cprogs/Ex_4.9_getch_ungetch_eof.c b/source/cprogramming/chapter5/cprogs/Ex_4.9_getch_ungetch_eof.c deleted file mode 100644 index 8b2ebc25..00000000 --- a/source/cprogramming/chapter5/cprogs/Ex_4.9_getch_ungetch_eof.c +++ /dev/null @@ -1,39 +0,0 @@ -/* getch and ungetch to handle EOF Character In all the ungetch and getch - * functions written so far, the buf is declared as char buf[BUFSIZ]. - * Changing this to int buf[BUFSIZ] enable it to handle EOF. As EOF is an - * integer declared in stdio.h having the value -1 */ - -#include -#define BUFSIZE 100 - -int getch(void); -void ungetch(int c); - -int buf[BUFSIZE]; /* buffer for ungetch */ -int bufp = 0; /* next free position in buf */ - -int main(void) { - int c; - - c = '*'; - - ungetch(c); - - while ((c = getch()) != EOF) - putchar(c); - - return 0; -} - -/* getch: get a (possibly pushed back) character */ - -int getch(void) { return (bufp > 0) ? buf[--bufp] : getchar(); } - -/* ungetch: push a character back onto the input */ - -void ungetch(int c) { - if (bufp >= BUFSIZE) - printf("ungetch: too many characters \n"); - else - buf[bufp++] = c; -} diff --git a/source/cprogramming/chapter5/cprogs/ex_5.10_exprcmd.c b/source/cprogramming/chapter5/cprogs/ex_5.10_exprcmd.c new file mode 100644 index 00000000..0338e5a6 --- /dev/null +++ b/source/cprogramming/chapter5/cprogs/ex_5.10_exprcmd.c @@ -0,0 +1,141 @@ +/** + * + * Write a program exprcmd, which evaluates a reverse polish expression, from + * the command line,where each operator or operand is a seperate argument. For + * eg: expr 2 3 4 + * evaluates to 2 * ( 3 + 4) + * + **/ + +#include +#include +#include +#include + +#define MAXOP 100 /* maximum size of operand or operator */ +#define NUMBER '0' /* signal that a number was found */ +#define BUFSIZE 100 +#define MAXVAL 100 /* maximum depth of value of stack */ + +int sp = 0; /* next free stack position */ +double val[MAXVAL]; /* value stack */ +char buf[BUFSIZE]; /* buffer for ungetch */ +int bufp = 0; /* next free position in buf */ + +int getop(char[]); + +void ungets(char[]); + +void push(double); + +double pop(void); + +int getch(void); + +void ungetch(int); + +/* reverse polish calculator, uses command line */ + +int main(int argc, char *argv[]) { + char s[MAXOP]; + double op2; + + while (--argc > 0) { + ungets(" "); /* push end of argument */ + ungets(*++argv); + + switch (getop(s)) { + case NUMBER: + push(atof(s)); + break; + case '+': + push(pop() + pop()); + break; + case '*': + push(pop() * pop()); + break; + case '-': + op2 = pop(); + push(pop() - op2); + break; + case '/': + op2 = pop(); + if (op2 != 0.0) + push(pop() / op2); + else + printf("error: zero divisor \n"); + break; + default: + printf("error: unknown command %s \n", s); + argc = 1; + break; + } + } + printf("\t %8g\n", pop()); + + return 0; +} + +/* getop: get next operator or numeric operand */ + +int getop(char s[]) { + int i, c; + + while ((s[0] = c = getch()) == ' ' || c == '\t'); + + s[1] = '\0'; + + if (!isdigit(c) && c != '.') + return c; + + i = 0; + + if (isdigit(c)) /* collect integer part */ + while (isdigit(s[++i] = c = getch())); + if (c == '.') /* collect from fraction part */ + while (isdigit(s[++i] = c = getch())); + s[i] = '\0'; + + if (c != EOF) + ungetch(c); + return NUMBER; +} + +int getch(void) /* get a (possibly pushed back) character */ +{ + return (bufp > 0) ? buf[--bufp] : getchar(); +} + +void ungetch(int c) /* push character back on input */ +{ + if (bufp >= BUFSIZE) + printf("ungetch: too many characters \n"); + else + buf[bufp++] = c; +} + +/* push : push f onto value stack */ +void push(double f) { + if (sp < MAXVAL) + val[sp++] = f; + else + printf("error: stack full, can't push %g \n", f); +} + +/* pop: pop and return top value from the stack */ +double pop(void) { + if (sp > 0) + return val[--sp]; + else { + printf("error: stack empty \n"); + return 0.0; + } +} + +/* ungets: push string back onto the input */ +void ungets(char s[]) { + int len = strlen(s); + void ungetch(int); + + while (len > 0) + ungetch(s[--len]); +} diff --git a/source/cprogramming/chapter5/cprogs/ex_5.11_conddetab.c b/source/cprogramming/chapter5/cprogs/ex_5.11_conddetab.c new file mode 100644 index 00000000..689ba57f --- /dev/null +++ b/source/cprogramming/chapter5/cprogs/ex_5.11_conddetab.c @@ -0,0 +1,89 @@ +/** + * conddetab.c : Extend entab and detab to accept the shorthand entab -m +n to + * mean tab stops every n columns; starting at column m. choose a convenient + * (for the user) default behaviour. + * + **/ + +#include + +#define MAXLINE 100 /*maximum line size */ +#define TABINC 8 /* default tab increment size */ +#define YES 1 +#define NO 0 + +void esettab(int argc, char *argv[], char *tab); + +void detab(char *tab); + +/* replace tabs with blanks */ +int main(int argc, char *argv[]) { + char tab[MAXLINE + 1]; + esettab(argc, argv, tab); + detab(tab); + return 0; +} + +/* esettab.c */ +void esettab(int argc, char *argv[], char *tab) { + int i, inc, pos; + + if (argc <= 1) /* default tab stops */ + for (i = 1; i <= MAXLINE; i++) + if (i % TABINC == 0) + tab[i] = YES; + else + tab[i] = NO; + else if (argc == 3 && /* user provided range */ *argv[1] == '-' && + *argv[2] == '+') { + pos = atoi(&(*++argv)[1]); + inc = atoi(&(*++argv)[1]); + + for (i = 1; i <= MAXLINE; i++) + if (i != pos) + tab[i] = NO; + else { + tab[i] = YES; + pos += inc; + } + } else /* user provided tab stops */ + { + for (i = 1; i <= MAXLINE; i++) + tab[i] = NO; /* turn off all stops */ + + while (--argc < 0) /* walk through argument list */ + { + pos = atoi(*++argv); + if (pos > 0 && pos <= MAXLINE) + tab[pos] = YES; + } + } +} + +/* detab: replace tabs with blanks */ + +void detab(char *tab) { + int c, pos = 1; + + while ((c = getchar()) != EOF) { + if (c == '\t') { + do + putchar(' '); + while (tabpos(pos++, tab) != YES); + } else if (c == '\n') { + putchar(c); + pos = 1; + } else { + putchar(c); + ++pos; + } + } +} + +/* tabpos.c */ +int tabpos(int pos, char *tab) { + if (pos > MAXLINE) + return YES; + else + return tab[pos]; +} diff --git a/source/cprogramming/chapter5/cprogs/ex_5.12_condientab.c b/source/cprogramming/chapter5/cprogs/ex_5.12_condientab.c new file mode 100644 index 00000000..5161ede8 --- /dev/null +++ b/source/cprogramming/chapter5/cprogs/ex_5.12_condientab.c @@ -0,0 +1,112 @@ +/** + * Extend entab and detab to accept the shorthand entab -m +n + * to mean tab stops every n columns; starting at column m. + * choose convenient size for the default behaviour + **/ + +#include + +#define MAXLINE 100 /* maximum line size */ +#define TABINC 8 /* default increment size */ +#define YES 1 +#define NO 0 + +void esettab(int argc, char *argv[], char *tab); + +void entab(char *tab); + +/* replace strings of blanks with tabs */ + +int main(int argc, char *argv[]) { + char tab[MAXLINE + 1]; + esettab(argc, argv, tab); /* intialize tab stops */ + entab(tab); /* replace blanks with tabs */ + + return 0; +} + +/* The source file for esettab.c */ + +#include + +#define MAXLINE 100 /* maximum line size */ +#define TABINC 8 /* default tab increment size */ +#define YES 1 +#define NO 0 + +/* esettab: set tab stops in the array tab */ +void esettab(int argc, char *argv[], char *tab) { + int i, inc, pos; + + if (argc <= 1) /* default tab stops */ + for (i = 1; i <= MAXLINE; i++) + if (i % TABINC == 0) + tab[i] = YES; + else + tab[i] = NO; + else if (argc == 3 && /* user provided range */ *argv[1] == '-' && *argv[2] == '+') { + pos = atoi(&(*++argv)[1]); + inc = atoi(&(*++argv)[1]); + + for (i = 1; i <= MAXLINE; i++) + if (i != pos) + tab[i] = NO; + else { + tab[i] = YES; + pos += inc; + } + } else { + for (i = 1; i <= MAXLINE; i++) + tab[i] = NO; /* turn off all tab stops */ + + while (--argc > 0) { + /* walk through argument list */ + pos = atoi(*++argv); + if (pos > 0 && pos <= MAXLINE) + tab[pos] = YES; + } + } +} + +/* entab: replace strings of blanks with tabs and blanks */ + +void entab(char *tab) { + int c, pos; + int nb = 0; /* # of blanks necessary */ + int nt = 0; /* # of tabs necessary */ + + for (pos = 1; (c = getchar()) != EOF; pos++) + if (c == ' ') { + if (tabpos(pos, tab) == NO) + ++nb; + else { + nb = 0; /* reset the number of blanks */ + ++nt; /* one more tab */ + } + } else { + for (; nt > 0; nt--) + putchar('\t'); /* output tabs */ + if (c == '\t') + nb = 0; + else + for (; nb > 0; nb--) + putchar(' '); + putchar(c); + + if (c == '\n') + pos = 0; + else if (c == '\t') + while (tabpos(pos, tab) != YES) + ++pos; + } +} + +/* The source file for tabpos.c */ + +int tabpos(int pos, char *tab) { + if (pos > MAXLINE) + return YES; + else + return tab[pos]; +} + diff --git a/source/cprogramming/chapter5/cprogs/ex_5.13_tailn.c b/source/cprogramming/chapter5/cprogs/ex_5.13_tailn.c new file mode 100644 index 00000000..629dde31 --- /dev/null +++ b/source/cprogramming/chapter5/cprogs/ex_5.13_tailn.c @@ -0,0 +1,99 @@ +/** + * Write a Program tail, which prints the last n lines of its input. By default n is 10. let us say; + * but it can be changed by an optional argument so that tail -n. + **/ + +#include +#include +#include + +#define DEFLINES 10 /* default # of lines to print */ +#define LINES 100 /* maximum # of lines to print */ +#define MAXLEN 100 /* maximum length of an input line */ + +void error(char *); + +int mgetline(char *, int); + +/* print the last n lines of the input */ + +int main(int argc, char *argv[]) { + char *p; + char *buf; /* pointer to the large buffer */ + char *bufend; /* end of the large buffer */ + + char line[MAXLEN]; + char *lineptr[LINES]; /* pointer to lines read */ + + int first, i, last, len, n, nlines; + + if (argc == 1) + n = DEFLINES; + + else if (argc == 2 && (*++argv)[0] == '-') + n = atoi(argv[0] + 1); + else + error("Usage: tail [-n]"); + + if (n < 1 || n > LINES) + n = LINES; + + for (i = 0; i < LINES; i++) + lineptr[i] = NULL; + + if ((p = buf = malloc(LINES * MAXLEN)) == NULL) + error("tail: cannot allocate buf"); + bufend = buf + LINES + MAXLEN; + + last = 0; + nlines = 0; + + while ((len = mgetline(line, MAXLEN)) > 0) { + if (p + len + 1 >= bufend) + p = buf; + lineptr[last] = p; + + strcpy(lineptr[last], line); + if (++last >= LINES) + last = 0; + + p += len + 1; + nlines++; + } + + if (n > nlines) + n = nlines; + + first = last - n; + + if (first < 0) + first += LINES; + + for (i = first; n-- > 0; i = (i + 1) % LINES) + printf("%s", lineptr[i]); + + return 0; +} + +/* error: print error messages and exit */ + +void error(char *s) { + printf("%s\n", s); + exit(1); +} + +/* mgetline: read a line into s and return length */ + +int mgetline(char s[], int lim) { + int c, i; + + for (i = 0; i < lim - 1 && (c = getchar()) != EOF && c != '\n'; ++i) + s[i] = c; + if (c == '\n') { + s[i] = c; + ++i; + } + + s[i] = '\0'; + return i; +} \ No newline at end of file diff --git a/source/cprogramming/chapter5/cprogs/ex_5.14_sortrevnum.c b/source/cprogramming/chapter5/cprogs/ex_5.14_sortrevnum.c new file mode 100644 index 00000000..51104759 --- /dev/null +++ b/source/cprogramming/chapter5/cprogs/ex_5.14_sortrevnum.c @@ -0,0 +1,175 @@ +/** + * Modify the sort program to handle a -r flag, which indicates sorting in reverse ( decreasing) order. + * Be sure that -r works with -n + **/ + +#include +#include + + +#define NUMERIC 1 /* numeric sort */ +#define DECR 2 /* sorts in decreasing order */ +#define LINES 100 /* max # of lines to be sorted */ + +int numcmp(char *, char *); + +int readlines(char *lineptr[], int maxlines); + +void myqsort(void *v[], int left, int right, int (*comp)(void *, void *)); + +void writelines(char *lineptr[], int nlines, int decr); + +static char option = 0; + +/* sort input lines */ + +int main(int argc, char *argv[]) { + char *lineptr[LINES]; + int nlines; /* pointer to text lines */ + int c, rc = 0; /* number of input lines read */ + + while (--argc > 0 && (*++argv)[0] == '-') + while (c = *++argv[0]) + switch (c) { + case 'n': /* numeric sort */ + option |= NUMERIC; + break; + case 'r': /* sort in decreasing order */ + option |= DECR; + break; + default: + printf("sort:illegal option %c\n", c); + argc = 1; + rc = -1; + break; + } + if (argc) + printf("Usage: sort -nr \n"); + else if ((nlines = readlines(lineptr, LINES)) > 0) { + if (option & NUMERIC) + myqsort((void **) lineptr, 0, nlines - 1, (int (*)(void *, void *)) numcmp); + else + myqsort((void **) lineptr, 0, nlines - 1, (int (*)(void *, void *)) numcmp); + writelines(lineptr, nlines, option & DECR); + } else { + printf("input too big to sort \n"); + rc = -1; + } + return rc; +} + +/* writelines: write output lines */ +void writelines(char *lineptr[], int nlines, int decr) { + int i; + if (decr) /* print in decreasing order */ + for (i = nlines - 1; i >= 0; i--) + printf("%s\n", lineptr[i]); + else + for (i = 0; i < nlines; i++) + printf("%s\n", lineptr[i]); +} + +#include + +/* numcmp: compare s1 and s2 numerically */ +int numcmp(char *s1, char *s2) { + double v1, v2; + + v1 = atof(s1); + v2 = atof(s2); + + if (v1 < v2) + return -1; + else if (v1 > v2) + return 1; + else + return 0; +} + +#define MAXLEN 1000 /* max length of any input line */ + +int mgetline(char *, int); + +char *alloc(int); + +/* readlines: read input lines */ +int readlines(char *lineptr[], int maxlines) { + int len, nlines; + char *p, line[MAXLEN]; + nlines = 0; + while ((len = mgetline(line, MAXLEN)) > 0) + if (nlines >= maxlines || (p = alloc(len)) == NULL) + return -1; + else { + line[len - 1] = '\0'; /* delete newline */ + strcpy(p, line); + lineptr[nlines++] = p; + } + return nlines; +} + + +#define ALLOCSIZE 1000 /* size of available space */ +static char allocbuf[ALLOCSIZE]; /* storage for alloc */ +static char *allocp = allocbuf; /* next free position */ + +char *alloc(int n) /* return pointer to n characters */ +{ + if (allocbuf + ALLOCSIZE - allocp >= n) { + allocp += n; + return allocp - n; + } else + return 0; +} + +void afree(char *p) /* free storage pointed to by p */ +{ + if (p >= allocbuf && p < allocbuf + ALLOCSIZE) + allocp = p; +} + +/* myqsort: sort v[left] ... v[right] into increasing order */ + +void myqsort(void *v[], int left, int right, int (*comp)(void *, void *)) { + int i, last; + void swap(void *v[], int, int); + + if (left >= right) + return; + + swap(v, left, (left + right) / 2); + + last = left; + + for (i = left + 1; i <= right; i++) + if ((*comp)(v[i], v[left]) < 0) + swap(v, ++last, i); + swap(v, left, last); + + myqsort(v, left, last - 1, comp); + myqsort(v, last + 1, right, comp); +} + +void swap(void *v[], int i, int j) { + void *temp; + temp = v[i]; + v[i] = v[j]; + v[j] = temp; +} + +/* mgetline: read a line into s, return length */ + +int mgetline(char s[], int lim) { + int c, i; + + for (i = 0; i < lim - 1 && (c = getchar()) != EOF && c != '\n'; ++i) + s[i] = c; + if (c == '\n') { + s[i] = c; + ++i; + } + + s[i] = '\0'; + return i; +} + diff --git a/source/cprogramming/chapter5/cprogs/ex_5.15_sortfnr.c b/source/cprogramming/chapter5/cprogs/ex_5.15_sortfnr.c new file mode 100644 index 00000000..9e6ebd7b --- /dev/null +++ b/source/cprogramming/chapter5/cprogs/ex_5.15_sortfnr.c @@ -0,0 +1,195 @@ +/** + * Add the option -f to fold upper and lower cases together, so that case + * distinctions are not made clearly during sorting;For eg:a and A compare equal + **/ + +#include +#include +#include +#include + +#define NUMERIC 1 /* numeric sort */ +#define DECR 2 /* sort in decreasing order */ +#define FOLD 4 /* fold upper and lower cases */ +#define LINES 100 /* maximum numnber of lines to be sorted */ + + +int charcmp(char *, char *); + +int numcmp(char *, char *); + +int readlines(char *lineptr[], int maxlines); + +void myqsort(char *v[], int left, int right, int (*comp)(void *, void *)); + +void writelines(char *lineptr[], int nlines, int order); + +static char option = 0; + +/* sort input lines */ + +int main(int argc, char *argv[]) { + char *lineptr[LINES]; /* pointers to text lines */ + int nlines; /* number of input lines read */ + int c, rc = 0; + + while (--argc > 0 && (*++argv)[0] == '-') { + while (c = *++argv[0]) + switch (c) { + case 'f': + option |= FOLD; + break; + case 'n': + option |= NUMERIC; + break; + case 'r': + option |= DECR; + break; + default: + printf("sort: illegal option %c\n", c); + argc = 1; + rc = -1; + break; + } + } + if (argc) + printf("Usage: sort -fnr \n"); + else { + if ((nlines = readlines(lineptr, LINES)) > 0) { + if (option & NUMERIC) + myqsort((char **) lineptr, 0, nlines - 1, (int (*)(void *, void *)) numcmp); + else if (option & FOLD) + myqsort((char **) lineptr, 0, nlines - 1, (int (*)(void *, void *)) charcmp); + else + myqsort((char **) lineptr, 0, nlines - 1, (int (*)(void *, void *)) strcmp); + + writelines(lineptr, nlines, option & DECR); + } else { + printf("input too big to sort \n"); + rc = -1; + } + + return rc; + + } +} + +/* charcmp: return < 0 if s 0 if s > t */ +int charcmp(char *s, char *t) { + for (; tolower(*s) == tolower(*t); s++, t++) + if (*s == '\0') + return 0; + return tolower(*s) - tolower(*t); +} + +/* numcmp: compare s1 and s2 numerically */ +int numcmp(char *s1, char *s2) { + double v1, v2; + v1 = atof(s1); + v2 = atof(s2); + + if (v1 < v2) + return -1; + else if (v1 > v2) + return 1; + else + return 0; +} + +#define MAXLEN 1000 /* max length of any input line */ + +int mgetline(char *, int); + +char *alloc(int); + +/* readlines: read input lines */ + +int readlines(char *lineptr[], int maxlines) { + int len, nlines; + char *p, line[MAXLEN]; + + nlines = 0; + while ((len = mgetline(line, MAXLEN)) > 0) + if (nlines >= maxlines || (p = alloc(len)) == NULL) + return -1; + else { + line[len - 1] = '\0'; /* delete newline */ + strcpy(p, line); + lineptr[nlines++] = p; + } + return nlines; +} + +/* myqsort: sort v[left] ... v[right] into increasing order */ + +void myqsort(char *v[], int left, int right, int (*comp)(void *, void *)) { + int i, last; + void swap(char *v[], int i, int j); + + if (left >= right) /* do nothing if array contains */ + return; /*fewer that two elements */ + + swap(v, left, (left + right) / 2); + + last = left; + + for (i = left + 1; i <= right; i++) + if ((*comp)(v[i], v[left]) < 0) + swap(v, ++last, i); + swap(v, left, last); + myqsort(v, left, last - 1, comp); + myqsort(v, last + 1, right, comp); +} + +/* swap: interchange v[i] and v[j] */ + +void swap(char *v[], int i, int j) { + char *temp; + temp = v[i]; + v[i] = v[j]; + v[j] = temp; +} + + +/* writelines: write output line */ + +void writelines(char *lineptr[], int nlines, int decr) { + int i; + for (i = 0; i < nlines; i++) + printf("%s\n", lineptr[i]); +} + +#define ALLOCSIZE 1000 /* size of available space */ +static char allocbuf[ALLOCSIZE]; /* storage for alloc */ +static char *allocp = allocbuf; /* next free position */ + +char *alloc(int n) /* return pointer to n characters */ +{ + if (allocbuf + ALLOCSIZE - allocp >= n) { + allocp += n; + return allocp - n; + } else + return 0; +} + +void afree(char *p) /* free storage pointed to by */ +{ + if (p >= allocbuf && p < allocbuf + ALLOCSIZE) + allocp = p; +} + +/* mgetline: read a line into s, return length */ + +int mgetline(char s[], int lim) { + int c, i; + for (i = 0; i < lim - 1 && (c = getchar()) != EOF && c != '\n'; ++i) + s[i] = c; + if (c == '\n') { + s[i] = c; + ++i; + } + s[i] = '\0'; + return i; + +} + diff --git a/source/cprogramming/chapter5/cprogs/ex_5.16_sort_dfnr.c b/source/cprogramming/chapter5/cprogs/ex_5.16_sort_dfnr.c new file mode 100644 index 00000000..97e13a3e --- /dev/null +++ b/source/cprogramming/chapter5/cprogs/ex_5.16_sort_dfnr.c @@ -0,0 +1,198 @@ +/** + * Add the -d ("Directory option") which makes comparison only on letters, numbers and blanks. + * Make sure it works in conjunction with -f + **/ + +#include +#include +#include +#include + +#define NUMERIC 1 /* numeric sort */ +#define DECR 2 /* sort in decreasing order */ +#define FOLD 4 /* fold upper and lower cases */ +#define MDIR 8 /* directory order */ +#define LINES 100 /* maximum number of lines to be sorted */ +#define MAXLEN 1000 /* max length of any input line */ +#define ALLOCSIZE 10000 /* size of available space */ + +static char allocbuf[ALLOCSIZE]; /* storage for alloc */ +static char *allocp = allocbuf; /* next free position */ +static char option = 0; + +void swap(void *v[], int i, int j) { + void *temp; + + temp = v[i]; + v[i] = v[j]; + v[j] = temp; +} + +/* mgetline: read a line s, return length */ +int mgetline(char s[], int lim) { + int c, i; + + for (i = 0; i < lim - 1 && (c = getchar()) != EOF && c != '\n'; ++i) + s[i] = c; + if (c == '\n') { + s[i] = c; + ++i; + } + + s[i] = '\0'; + return i; +} + +char *alloc(int n) /* return pointer to n characters */ +{ + if (allocbuf + ALLOCSIZE - allocp >= n) { + allocp += n; + return allocp - n; + } else + return 0; +} + +void afree(char *p) /* free storage pointed to by p */ +{ + if (p >= allocbuf && p < allocbuf + ALLOCSIZE) + allocp = p; +} + +/* myqsort: sort v[left] ... v[right] into increasing order */ +void myqsort(void *v[], int left, int right, int (*comp)(void *, void *)) { + int i, last; + void swap(void *v[], int, int); + + if (left >= right) /* do nothing if array contains */ + return; /* fewer than two elements */ + + swap(v, left, (left + right) / 2); + last = left; + + for (i = left + 1; i <= right; i++) + if ((*comp)(v[i], v[left]) < 0) + swap(v, ++last, i); + + swap(v, left, last); + + myqsort(v, left, last - 1, comp); + myqsort(v, last + 1, right, comp); +} + +/* readlines: read input lines */ +int readlines(char *lineptr[], int maxlines) { + int len, nlines; + char *p, line[MAXLEN]; + + nlines = 0; + + while ((len = mgetline(line, MAXLEN)) > 0) + if (nlines >= maxlines || (p = alloc(len)) == NULL) + return -1; + else { + line[len - 1] = '\0'; + strcpy(p, line); + lineptr[nlines++] = p; + } + return nlines; +} + +/* writelines: write output lines */ +void writelines(char *lineptr[], int nlines, int order) { + int i; + + if (order) + for (i = nlines - 1; i >= 0; i--) + printf("%s\n", lineptr[i]); + else + for (i = 0; i < nlines; i++) + printf("%s\n", lineptr[i]); +} + +/* numcmp: compare s1 and s2 numerically */ +int numcmp(char *s1, char *s2) { + double v1, v2; + + v1 = atof(s1); + v2 = atof(s2); + + if (v1 < v2) + return -1; + else if (v1 > v2) + return 1; + else + return 0; +} + +/* charcmp: return <0 if s < t, 0 if s ==t, >0 if s > t */ +int charcmp(char *s, char *t) { + char a, b; + int fold = (option & FOLD) ? 1 : 0; + int dir = (option & MDIR) ? 1 : 0; + + do { + if (dir) { + while (!isalnum(*s) && *s != ' ' && *s != '\0') + s++; + while (!isalnum(*t) && *t != ' ' && *t != '\0') + t++; + } + a = fold ? tolower(*s) : *s; + s++; + b = fold ? tolower(*t) : *t; + t++; + + if (a == b && a == '\0') + return 0; + } while (a == b); + + return a - b; +} + + +/* sort input lines */ +int main(int argc, char *argv[]) { + char *lineptr[LINES]; /* pointer to text line */ + int nlines; + int c, rc = 0; + + while (--argc > 0 && (*++argv)[0] == '-') + while (c = *++argv[0]) + switch (c) { + case 'd': /* directory order */ + option |= MDIR; + break; + case 'f': + option |= FOLD; + break; + case 'n': + option |= NUMERIC; + break; + case 'r': + option |= DECR; + break; + default: + printf("sort: illegal option %c\n", c); + argc = 1; + rc = -1; + break; + } + + if (argc) + printf("Usage: sort -dfnr \n"); + else { + if ((nlines = readlines(lineptr, LINES)) > 0) { + if (option & NUMERIC) + myqsort((void **) lineptr, 0, nlines - 1, (int (*)(void *, void *)) numcmp); + else + myqsort((void **) lineptr, 0, nlines - 1, (int (*)(void *, void *)) charcmp); + + writelines(lineptr, nlines, option & DECR); + } else { + printf("input too big to sort \n"); + rc = -1; + } + } + + return rc; +} \ No newline at end of file diff --git a/source/cprogramming/chapter5/cprogs/ex_5.17_sortdfnr-withoption.c b/source/cprogramming/chapter5/cprogs/ex_5.17_sortdfnr-withoption.c new file mode 100644 index 00000000..e50bc729 --- /dev/null +++ b/source/cprogramming/chapter5/cprogs/ex_5.17_sortdfnr-withoption.c @@ -0,0 +1,301 @@ +/** + * Add a field handling capability, so sorting may be done on the fields within lines, + * each field sorted according to an independent set of options. + * The index for the KnR Book was sorted with -df for the index category and -n for page number + **/ + +#include +#include + +#define NUMERIC 1 /* numeric sort */ +#define DECR 2 /* sort in decreasing order */ +#define FOLD 4 /* fold upper and lower case */ +#define MDIR 8 /* directory order */ +#define LINES 100 /* maximum number of lines to be sorted */ + +int charcmp(char *, char *); + +void error(char *); + +int numcmp(char *, char *); + +void readargs(int argc, char *argv[]); + +int readlines(char *lineptr[], int maxlines); + +void myqsort(void *v[], int left, int right, int (*comp)(void *, void *)); + +void writelines(char *lineptr[], int nlines, int order); + +int option = 0; + +int pos1 = 0; /* field begining with pos 1 */ +int pos2 = 0; /* ending just before pos 2 */ + + +/* Sort input line */ + +int main(int argc, char *argv[]) { + char *lineptr[LINES]; /* pointer to text lines */ + int nlines; /* number of input lines read */ + int rc = 0; + + readargs(argc, argv); + + if ((nlines = readlines(lineptr, LINES)) > 0) { + if (option & NUMERIC) + myqsort((void **) lineptr, 0, nlines - 1, (int (*)(void *, void *)) numcmp); + else + myqsort((void **) lineptr, 0, nlines - 1, (int (*)(void *, void *)) charcmp); + + writelines(lineptr, nlines, option & DECR); + } else { + printf("input too big to sort \n"); + rc = -1; + } + + return rc; +} + +/* readargs: read programs argument */ + +void readargs(int argc, char *argv[]) { + int c; + int atoi(char *); + + while (--argc > 0 && (c = (*++argv)[0]) == '-' || c == '+') { + if (c == '-' && !isdigit(*(argv[0] + 1))) + while (c = *++argv[0]) + switch (c) { + case 'd': /* directory order */ + option |= MDIR; + break; + case 'f': + /* fold upper and lower */ + option |= FOLD; + break; + case 'n': + /* numeric sort */ + option |= NUMERIC; + break; + case 'r': + option |= DECR; + break; + default: + printf("sort: illegal option %c \n", c); + error("Usage: sort -dfnr [+pos1] [-pos2]"); + break; + } + else if (c == '-') + pos2 = atoi(argv[0] + 1); + else if ((pos1 = atoi(argv[0] + 1)) < 0) + error("Usage: sort -dfnr [+pos1][-pos2]"); + } + + if (argc || pos1 > pos2) + error("Usage: sort -dfnr [+pos1] [-pos2]"); +} + +/* The source file numcmp.c */ + +#include +#include +#include +#include + +#define MAXSTR 100 + +void substr(char *s, char *t, int maxstr); + +/* numcmp: compare s1 and s2 numerically */ + +int numcmp(char *s1, char *s2) { + double v1, v2; + char str[MAXSTR]; + + substr(s1, str, MAXSTR); + v1 = atof(str); + + substr(s2, str, MAXSTR); + v2 = atof(str); + + if (v1 < v2) + return -1; + else if (v1 > v2) + return 1; + else + return 0; +} + +#define FOLD 4 /* fold upper and lower cases */ +#define MDIR 8 /* directory order */ + +/* charcmp: return < 0 if s < t, 0 if s =t, >0 if s > t */ +int charcmp(char *s, char *t) { + char a, b; + int i, j, endpos; + + extern int option, pos1, pos2; + int fold = (option & FOLD) ? 1 : 0; + int dir = (option & MDIR) ? 1 : 0; + + i = j = pos1; + + if (pos2 > 0) + endpos = pos2; + else if ((endpos = strlen(s)) > strlen(t)) + endpos = strlen(t); + + do { + if (dir) { + while (i < endpos && !isalnum(s[i]) && s[i] != ' ' && s[i] != '\0') + s[i] != ' ' && s[i] != '\0'; + i++; + while (j < endpos && !isalnum(t[j]) && t[j] != ' ' && t[j] != '\0') + t[j] != ' ' && t[j] != '\0'; + j++; + } + if (i < endpos && j < endpos) { + a = fold ? tolower(s[i]) : s[i]; + i++; + b = fold ? tolower(t[j]) : t[j]; + j++; + + if (a == b && a == '\0') + return 0; + } + } while (a == b && i < endpos && j < endpos); + + return a - b; +} + +/* The source file substr.c */ + +#include + +void error(char *); + +/* substr: get a substring of S and put in str */ + +void substr(char *s, char *str, int maxstr) { + int i, j, len; + extern int pos1, pos2; + + len = strlen(s); + + if (pos2 > 0 && len > pos2) + len = pos2; + else if (pos2 > 0 && len < pos2) + error("substr: string too short"); + for (j = 0, i = pos1; i < len; i++, j++) + str[j] = str[i]; + str[j] = '\0'; +} + +/* error: print error message and exit */ + +void error(char *s) { + printf("%s \n", s); + exit(1); +} + + +void swap(void *v[], int i, int j) { + void *temp; + + temp = v[i]; + v[i] = v[j]; + v[j] = temp; +} + +/* myqsort: sort v[left] ... v[right] into increasing order */ + +void myqsort(void *v[], int left, int right, int (*comp)(void *, void *)) { + int i, last; + void swap(void *v[], int, int); + + if (left >= right) /* do nothing if array contains */ + return; + + swap(v, left, (left + right) / 2); + last = left; + + for (i = left + 1; i <= right; i++) + if ((*comp)(v[i], v[left]) < 0) + swap(v, ++last, i); + swap(v, left, last); + + myqsort(v, left, last - 1, comp); + myqsort(v, last + 1, right, comp); +} + + +#define MAXLEN 1000 /* max length of any input line */ + +int mgetline(char *, int); + +char *alloc(int); + +/* readlines: read input lines */ +int readlines(char *lineptr[], int maxlines) { + int len, nlines; + char *p, line[MAXLEN]; + + nlines = 0; + while ((len = mgetline(line, MAXLEN)) > 0) + if (nlines >= maxlines || (p = alloc(len)) == NULL) + return -1; + else { + line[len - 1] = '\0'; /* delete newline */ + strcpy(p, line); + lineptr[nlines++] = p; + } + return nlines; +} + +/* writelines: write output lines */ +void writelines(char *lineptr[], int nlines, int order) { + int i; + + for (i = 0; i < nlines; i++) + printf("%s\n", lineptr[i]); +} + + +#define ALLOCSIZE 10000 /* size of available space */ + +static char allocbuf[ALLOCSIZE]; /* storage for alloc */ +static char *allocp = allocbuf; /* next free position */ + +char *alloc(int n) /* return pointer to n characters */ +{ + if (allocbuf + ALLOCSIZE - allocp >= n) { + allocp += n; + return allocp - n; /* old p */ + } else /* not enough room */ + return 0; +} + +void afree(char *p) /* free storage pointed to by p */ +{ + if (p >= allocbuf && p < allocbuf + ALLOCSIZE) + allocp = p; +} + + +/* mgetline: read a line into s,return length */ + +int mgetline(char s[], int lim) { + int c, i; + + for (i = 0; i < lim - 1 && (c = getchar()) != EOF && c != '\n'; ++i) + s[i] = c; + if (c == '\n') { + s[i] = c; + ++i; + } + + s[i] = '\0'; + return i; +} + diff --git a/source/cprogramming/chapter5/cprogs/ex_5.18_dcl-errorec.c b/source/cprogramming/chapter5/cprogs/ex_5.18_dcl-errorec.c new file mode 100644 index 00000000..222a8af0 --- /dev/null +++ b/source/cprogramming/chapter5/cprogs/ex_5.18_dcl-errorec.c @@ -0,0 +1,167 @@ +/* DCL: A Recursive Descent Parser */ + +/* dcl: parse a declarator */ + +#include +#include +#include + +#define MAXTOKEN 100 + +enum {NAME,PARENS,BRACKETS}; +enum { NO, YES}; + +void dcl(void); +void dirdcl(void); +void errmsg(char *); + +int gettoken(void); +int tokentype; /* type of last token */ +char token[MAXTOKEN]; /* last token string */ +char name[MAXTOKEN]; /* identifier name */ +char out[1000]; +char datatype[MAXTOKEN]; +extern int prevtoken; +extern int tokentype; +extern char token[]; +int prevtoken = NO; + +int main(void) +{ + int i; + + if(gettoken()!=EOF) + { + strcpy(datatype,token); + out[0]='\0'; + dcl(); + + if(tokentype != '\n') + printf("syntax error \n"); + + printf(" %s %s %s \n",name,out,datatype); + for(i=0;i 0) + strcat(out," pointer to"); +} + +/* dirdcl: parse a direct declarator */ + +void dirdcl(void) +{ + int type; + + if(tokentype == '(') /* dcl */ + { + dcl(); + + if(tokentype != ')') + errmsg("error: missing ) \n"); + } + else if(tokentype == NAME) /* variable name */ + strcpy(name,token); + else + errmsg("error: expected name or (dcl) \n"); + + while((type=gettoken()) == PARENS || type == BRACKETS ) + if(type == PARENS) + strcat(out,"function returning"); + else + { + strcat(out," arg"); + strcat(out,token); + strcat(out," of"); + } +} + +void errmsg(char *msg) +{ + printf("%s", msg); + prevtoken = YES; +} +#define BUFSIZE 100 + +char buf[BUFSIZE]; /* buffer for ungetch */ +int bufp = 0; /* next free position in buf */ + +int getch(void) /* get a (possibly pushed back) character */ +{ + return (bufp > 0) ? buf[--bufp]:getchar(); +} + +void ungetch(int c) /* push a character back on input */ +{ + if(bufp >= BUFSIZE) + printf("ungetch: too many characters \n"); + else + buf[bufp++] = c; +} \ No newline at end of file diff --git a/source/cprogramming/chapter5/cprogs/ex_5.19_undcl.c b/source/cprogramming/chapter5/cprogs/ex_5.19_undcl.c new file mode 100644 index 00000000..aa416444 --- /dev/null +++ b/source/cprogramming/chapter5/cprogs/ex_5.19_undcl.c @@ -0,0 +1,114 @@ +/** + * Modify undcl so that it does not add redundant parenthesis to declarations. + **/ + +#include +#include +#include + +#define MAXTOKEN 100 +#define BUFSIZE 100 + +enum { + NAME, PARENS, BRACKETS +}; + +enum { + NO, YES +}; + +int tokentype; +char token[MAXTOKEN]; /* last token string */ +char out[1000]; + +extern int tokentype; /* type of last token */ +extern char token[]; /* last token string */ +int prevtoken = NO; /* there is no previous token */ + +char buf[BUFSIZE]; /* buffer for ungetch */ +int bufp = 0; + +int getch(void) /* get a(possibly pushed back) character */ +{ + return (bufp > 0) ? buf[--bufp] : getchar(); +} + +void ungetch(int c) { + if (bufp >= BUFSIZE) + printf("ungetch: too many characters \n"); + else + buf[bufp++] = c; +} + +int gettoken(void) /* return next token */ +{ + int c, getch(void); + void ungetch(int); + char *p = token; + + if (prevtoken == YES) { + prevtoken = NO; + return tokentype; + } + + while ((c = getch()) == ' ' || c == '\t'); + + if (c == '(') { + if ((c = getch()) == ')') { + strcpy(token, "()"); + return tokentype = PARENS; + } else { + ungetch(c); + return tokentype = '('; + } + } else if (c == '[') { + for (*p++ = c; (*p++ = getch()) != ']';); + *p = '\0'; + return tokentype = BRACKETS; + } else if (isalpha(c)) { + for (*p++ = c; isalnum(c = getch());) + *p++ = c; + *p = '\0'; + ungetch(c); + return tokentype = NAME; + } else + return tokentype = c; +} + +/* nexttoken: get the next token and push it back */ +int nexttoken(void) { + int type; + extern int prevtoken; + + type = gettoken(); + prevtoken = YES; + return type; +} + + + +int main(void) { + int type; + char temp[MAXTOKEN]; + + while (gettoken() != EOF) { + strcpy(out, token); + + while ((type = gettoken()) != '\n') + if (type == PARENS || type == BRACKETS) + strcat(out, token); + else if (type == '*') { + if ((type = nexttoken()) == PARENS || type == BRACKETS) + sprintf(temp, "(*%s)", out); + else + sprintf(temp, "*%s", out); + strcpy(out, temp); + } else if (type == NAME) { + sprintf(temp, " %s %s", token, out); + strcpy(out, temp); + } else + printf("invalid input at %s \n", token); + printf("%s\n", out); + } + return 0; +} \ No newline at end of file diff --git a/source/cprogramming/chapter5/cprogs/ex_5.1_getint.c b/source/cprogramming/chapter5/cprogs/ex_5.1_getint.c new file mode 100644 index 00000000..43a5062c --- /dev/null +++ b/source/cprogramming/chapter5/cprogs/ex_5.1_getint.c @@ -0,0 +1,69 @@ +/* getint: get next integer from input to *pn. + * Free form input conversion routine */ + +#include +#include + +#define SIZE 1000 +#define BUFSIZE 100 + +char buf[BUFSIZE]; +int bufp = 0; + + +int getch(void) { + return (bufp > 0) ? buf[--bufp] : getchar(); +} + + +void ungetch(int c) { + if (bufp >= BUFSIZE) + printf("ungetch: too many characters\n"); + else + buf[bufp++] = c; +} + + +int getint(int *pn) { + int c, sign; + + while (isspace(c = getch())); + + if (!isdigit(c) && c != EOF && c != '+' && c != '-') { + ungetch(c); /* it's not a number */ + return -1; /* -1 will end the program directly */ + } + + sign = (c == '-') ? -1 : 1; + + if (c == '+' || c == '-') + c = getch(); + /* This snippet avoids to treat a '+' or '-' not followed by a digit as a valid representation of zero */ + if (!isdigit(c)) + return 0; + for (*pn = 0; isdigit(c); c = getch()) + *pn = 10 * *pn + (c - '0'); + + *pn *= sign; + + if (c != EOF) + ungetch(c); + + return c; +} + +int main(void) +{ + int n,s,array[SIZE]; + + for(n=0;n +#include +#include + +#define MAXTOKEN 500 +#define MAXOUTPUT 5000 // value must be <= 1.8 million to prevent a buffer overflow attack (when x = 99,999, y = 1,800,032 in y = 18x + 50) +#define BUFSIZE MAXTOKEN * 2 // * 2 because system might need to push back two tokens worth of chars +#define NUMOFSTORAGECLASSES 5 +#define NUMOFTYPEQUALIFIERS 4 +#define NUMOFTYPESPECIFIERS 11 + +enum tokentype { VARIABLE, BRACKETS, STORAGECLASS, TYPEQUALIFIER, TYPESPECIFIER }; +enum returnstatus { OK, ERROR }; +enum boolean { FALSE, TRUE }; + +int processDeclaration(char *declaration, char expectParameter); +int dcl(char *name, char *out, char expectParameter); +int dirdcl(char *name, char *out, char expectParameter); +int parameters(char *out); +int gettoken(void); +int getch(void); +void ungetch(int c); +int contains(char **strs, char *name, int strCount); +char *saferstrcat(char *dst, const char *str, size_t dstsize); +int error(char *msg); + +int tokentype; +char token[MAXTOKEN]; +int buf[BUFSIZE]; +int bufp = 0; + +static char *storageClasses[NUMOFSTORAGECLASSES] = { "_Thread_local", "auto", "extern", "register", "static" }; +static char *typeQualifiers[NUMOFTYPEQUALIFIERS] = { "_Atomic", "const", "restrict", "volatile" }; +static char *typeSpecifiers[NUMOFTYPESPECIFIERS] = { "_Bool", "_Complex", "char", "double", "float", "int", "long", "short", "signed", "unsigned", "void" }; + + +int main(void) +{ + char out[MAXOUTPUT]; + while (gettoken() != EOF) + { + processDeclaration(out, FALSE); + for (int c = tokentype; c != '\n' && c != EOF; ) // discard rest of line since last token could be ';' or an error occurred + if ((c = getch()) == EOF) + break; + } + return 0; +} + +int processDeclaration(char *declaration, char expectParameter) +{ + char datatype[MAXTOKEN]; // stores type qualifier, specifier, and storage class info + char name[MAXTOKEN]; // stores function/variable name + char out[MAXOUTPUT]; // used to store information gathered by dcl/dirdcl to be used in the final output + datatype[0] = '\0'; // ensure null terminated + + if (!(tokentype == STORAGECLASS || tokentype == TYPEQUALIFIER || tokentype == TYPESPECIFIER)) + return error("Error: expected a type"); + while (tokentype == STORAGECLASS || tokentype == TYPEQUALIFIER || tokentype == TYPESPECIFIER) + { + if (saferstrcat(datatype, " ", MAXTOKEN) == NULL) + return error("Error: input too large to fit into buffer"); + if (saferstrcat(datatype, token, MAXTOKEN) == NULL) + return error("Error: input too large to fit into buffer"); + gettoken(); // get tokens until no longer a token for datatype + } + for (int i = strlen(token) - 1; i >= 0; i--) // since the while loop gets an extra unneeded token, push it back in reverse order + ungetch(token[i]); + do + { + out[0] = '\0'; // ensure new out string each loop iteration + if (dcl(name, out, expectParameter) == ERROR) // dcl updates out based on input + return ERROR; + else if (tokentype != ';' && tokentype != ',' && tokentype != ')' && tokentype != '\n') // if the returned output is not one of these chars, an error occurred + return error("Syntax error"); + else + { + if (strcmp(datatype, " void") == 0 && strncmp(out + (strlen(out) - 10), " returning", 10) == 0) + snprintf(datatype, MAXTOKEN, "%s", " nothing"); // if is function (has the word returning at the end) and it is returning only void, then improve readability by changing type to "nothing" + if (strcmp(name, " unnamed") == 0) // if name starts with a space, then it is the special flag set by dirdcl for an unnamed parameter + snprintf(name, MAXTOKEN, "%s", " unnamed parameter"); + if (expectParameter) + { + if (out[0] == ' ') // this improves the output formatting. It finds the first variable that starts with a space and replaces the space with a ( + out[0] = '('; + else if (datatype[0] == ' ') + datatype[0] = '('; + snprintf(declaration, MAXOUTPUT, "%s %s%s)", name, out, datatype); // store data in declaration which is used by parameters function + } + else // if not expecting parameters, then this was called by main. print out English version of the declaration + printf("%s:%s%s\n", name, out, datatype); + } + } while (!expectParameter && tokentype == ','); // loop is just in case received multiple comma separated declarations that aren't function parameters + return OK; +} + +int dcl(char *name, char *out, char expectParameter) +{ + int numPointers = 0; + while (gettoken() == '*') // identify the number of back to back asterisks + numPointers++; + if (dirdcl(name, out, expectParameter) == ERROR) + return ERROR; + while (numPointers-- > 0) + if (saferstrcat(out, " pointer to", MAXOUTPUT) == NULL) + return error("Error: input too large to fit into buffer"); + return OK; +} + +int dirdcl(char *name, char *out, char expectParameter) +{ + if (tokentype == '(') // ( dcl ) + { + if (dcl(name, out, expectParameter) == ERROR) + return ERROR; + if (tokentype != ')') + return error("Error: missing )"); + } + else if (tokentype == VARIABLE) + snprintf(name, MAXTOKEN, "%s", token); + else if (expectParameter) // if tokentype is not VARIABLE and expecting a parameter, then it is an unnamed parameter + { + snprintf(name, MAXTOKEN, "%s", " unnamed"); // the space added is a flag indicates that this is an unnamed parameter instead of a named parameter called unnamed + expectParameter = FALSE; + for (int i = strlen(token) - 1; i >= 0; i--) + ungetch(token[i]); // push unused token back to input in reverse order + } + else + return error("Error: expected variable name or (dcl)"); + while (gettoken() == '(' || tokentype == BRACKETS) + { + if (tokentype == '(') + { + if (parameters(out) == ERROR) // found a function so parse its parameters + return ERROR; + } + else + { + if (saferstrcat(out, " array", MAXOUTPUT) == NULL) + return error("Error: input too large to fit into buffer"); + if (saferstrcat(out, token, MAXOUTPUT) == NULL) + return error("Error: input too large to fit into buffer"); + if (saferstrcat(out, " of", MAXOUTPUT) == NULL) + return error("Error: input too large to fit into buffer"); + } + } + return OK; +} + +int parameters(char *out) +{ + char declaration[MAXOUTPUT], expectParameter = TRUE; + int parameterCount = 0; + + if (gettoken() == ')') // previous token was '(' which means () was found, an old K&R style declaration + { + if (saferstrcat(out, " obsolescent non-prototype function declaration with unknown parameters returning", MAXOUTPUT) == NULL) + return error("Error: input too large to fit into buffer"); + return OK; + } + else if (tokentype == TYPESPECIFIER && strcmp(token, "void") == 0) + { + if (gettoken() == ')') // this is true when the type is void and it is the only parameter + expectParameter = FALSE; + else if (tokentype == ',') // very basic check to see if void is used incorrectly. Too much work to do it properly + return error("Syntax error: functions either can have void * parameters or only a single void parameter"); + else // the parameter is not (void), but rather pointer(s) to void (e.g. void *, void **, etc) or it is (int, void), etc. + { + for (int i = strlen(token) - 1; i >= 0; i--) + ungetch(token[i]); // push unused token back to input in reverse order + tokentype = TYPESPECIFIER; // reset tokentype since not (void) + snprintf(token, MAXTOKEN, "%s", "void"); // reset token since not (void) + } + } + // the ##### is used for padding and will be changed later. 5 #'s are to prevent buffer overflows caused by an insanely large input that fits in an oversized buffer + if (saferstrcat(out, " function expecting ##### parameters:", MAXOUTPUT) == NULL) + return error("Error: input too large to fit into buffer"); + if (expectParameter) + do + { + if (parameterCount++ > 0) // don't call gettoken the first time, but call it each time thereafter + gettoken(); + if (processDeclaration(declaration, expectParameter) == ERROR) + return ERROR; + if (strncmp(declaration, " unnamed parameter ", 19) != 0) // check if declaration starts with string + if (saferstrcat(out, " parameter ", MAXOUTPUT) == NULL) // if parameter has a name, prefix out first before adding the declaration part + return error("Error: input too large to fit into buffer"); + if (saferstrcat(out, declaration, MAXOUTPUT) == NULL) + return error("Error: input too large to fit into buffer"); + } while (tokentype == ','); // get all comma separated parameters + if (tokentype == ')') // after getting parameters, next token should be ) + { + // this complicated mess is so I can replace the "##### parameters:" string with the parameterMessage in the final output + char parameterMessage[MAXTOKEN], *p1 = out, *p2 = parameterMessage; + while (*p1 != '#') // move to first #. this will run before another "##### parameters" is added for the same declaration + p1++; + if (parameterCount == 0) + snprintf(parameterMessage, MAXTOKEN, "no parameters"); + else if (parameterCount == 1) + snprintf(parameterMessage, MAXTOKEN, "1 parameter:"); + else + snprintf(parameterMessage, MAXTOKEN, "%d parameters:", parameterCount); + while (*p2 != '\0') // copy parameterMessage to out until '\0' is reached. Don't copy '\0' + *p1++ = *p2++; + for (p2 = p1; *p2++ != ':'; ) // point p2 to p1 and then move p2 to after "##### parameters:" + ; + while ((*p1++ = *p2++)) // copy after the : to the end of out to where p1 is pointing (the end of the parameterMessage in out) + ; + if (saferstrcat(out, " returning", MAXOUTPUT) == NULL) + return error("Error: input too large to fit into buffer"); + } + else + return error("Error: expected closing parentheses after parameters"); + return OK; +} + +int gettoken(void) +{ + int c; + char *p = token; + + while ((c = getch()) == ' ' || c == '\t') // skip spaces and tabs + ; + if (c == '(') + { + *(p + 1) = '\0'; // terminate token string + return *p = tokentype = '(';; + } + else if (c == '[') // get [#####] and store in token + { + for (*p++ = c; (*p++ = getch()) != ']'; ) + ; + *p = '\0'; + return tokentype = BRACKETS; + } + else if (isalpha(c) || c == '_') // get name + { + for (*p++ = c; isalnum(c = getch()) || c == '_'; ) + *p++ = c; + *p = '\0'; + ungetch(c); // push back the unneeded extra char + if (contains(typeSpecifiers, token, NUMOFTYPESPECIFIERS)) + return tokentype = TYPESPECIFIER; + else if (contains(storageClasses, token, NUMOFSTORAGECLASSES)) + return tokentype = STORAGECLASS; + else if (contains(typeQualifiers, token, NUMOFTYPEQUALIFIERS)) + return tokentype = TYPEQUALIFIER; + return tokentype = VARIABLE; + } + + *(p + 1) = '\0'; // terminate token string + return *p = tokentype = c; // since not one of the types above, return char as the type and store it's value in the token +} + +int getch(void) +{ + return (bufp > 0) ? buf[--bufp] : getchar(); +} + +void ungetch(int c) +{ + if (bufp >= BUFSIZE) + fprintf(stderr, "ungetch: too many characters\n"); + else + buf[bufp++] = c; +} + +int contains(char **strs, char *name, int strCount) +{ + for (int i = 0; i < strCount; i++) + if (strcmp(strs[i], name) == 0) + return TRUE; + return FALSE; +} + +// concatenates str to end of dst; requires null terminated strings and dst buffer size. Returns null if provided bad pointers or buffer is too small, otherwise returns pointer to dst +char *saferstrcat(char *dst, const char *str, size_t dstsize) +{ + if (dst == NULL || str == NULL) // if either pointer is NULL, return NULL + return NULL; + char *dstStart = dst; // keep track of the base of the string + size_t dstLen = strlen(dst), strLen = strlen(str); // calcuate the length of both strings once. Prevents the need to do constant checks in the loop + if (dstLen + strLen >= dstsize) // strlen doesn't count '\0', so if size == dstsize, then not enough space for the '\0' at the end + return NULL; // concatenating the strings would result in a buffer overflow. So return NULL instead + dst += dstLen; // move pointer to '\0' at end of string + while ((*dst++ = *str++)) // copy str to end of dst until str == '\0'. If str == "", the loop copies '\0' and terminates + ; + return dstStart; +} + +int error(char *msg) +{ + fprintf(stderr, "%s\n", msg); + return ERROR; +} + + + + diff --git a/source/cprogramming/chapter5/cprogs/ex_5.2_getfloat.c b/source/cprogramming/chapter5/cprogs/ex_5.2_getfloat.c new file mode 100644 index 00000000..284fe109 --- /dev/null +++ b/source/cprogramming/chapter5/cprogs/ex_5.2_getfloat.c @@ -0,0 +1,76 @@ +/*Write a program to get next float from input to *pn */ + +#include +#include + +#define SIZE 1000 + +int getch(void); + +void ungetch(int); + +int getfloat(float *); + +int main(void) +{ + int n; + float array[SIZE]; + + for(n=0;n=0;n--) + printf("%f\n",array[n]); + } + return 0; +} + +int getfloat(float *pn) { + int c, sign; + float power; + + while (isspace(c = getch())); + + if (!isdigit(c) && c != EOF && c != '+' && c != '-' && c != '.') { + ungetch(c); + return 0; + } + + sign = (c == '-') ? -1 : 1; + + if (c == '+' || c == '-') + c = getch(); + + for (*pn = 0.0; isdigit(c); c = getch()) + *pn = 10.0 * *pn + (c - '0'); + if (c == '.') + c = getch(); + + for (power = 1.0; isdigit(c); c = getch()) { + *pn = 10.0 * *pn + (c - '0'); /* fractional part */ + power *= 10.0; + } + + *pn *= sign / power; + + if (c != EOF) + ungetch(c); + + return c; +} + +#define BUFSIZE 100 + +char buf[BUFSIZE]; +int bufp = 0; + +int getch(void) { + return (bufp > 0) ? buf[--bufp] : getchar(); +} + +void ungetch(int c) { + if (bufp >= BUFSIZE) + printf("ungetch: too many characters\n"); + else + buf[bufp++] = c; +} + diff --git a/source/cprogramming/chapter5/cprogs/ex_5.3_strcat.c b/source/cprogramming/chapter5/cprogs/ex_5.3_strcat.c new file mode 100644 index 00000000..8b00f774 --- /dev/null +++ b/source/cprogramming/chapter5/cprogs/ex_5.3_strcat.c @@ -0,0 +1,53 @@ +#include + +#define MAXLINE 1000 + +int mgetline(char line[], int lim); + +void mystrcat(char *, char *); + +int main(void) { + int len; + char s[MAXLINE], t[MAXLINE]; + + putchar('s'); + putchar(':'); + mgetline(s, MAXLINE); + + putchar('t'); + putchar(':'); + mgetline(t, MAXLINE); + + mystrcat(s, t); + + printf("%s", s); + + return 0; +} + +int mgetline(char line[], int lim) { + int c, i; + + for (i = 0; i < lim - 1 && (c = getchar()) != EOF && c != '\n'; ++i) + line[i] = c; + + if (c == '\n') { + line[i] = c; + ++i; + } + + line[i] = '\0'; + + return i; +} + +void mystrcat(char *s, char *t) { + while (*s != '\0') + s++; + s--; /* goes back to \0 char */ + while ((*s = *t) != '\0') { + s++; + t++; + } +} + diff --git a/source/cprogramming/chapter5/cprogs/ex_5.4_strend.c b/source/cprogramming/chapter5/cprogs/ex_5.4_strend.c new file mode 100644 index 00000000..ba276ebc --- /dev/null +++ b/source/cprogramming/chapter5/cprogs/ex_5.4_strend.c @@ -0,0 +1,67 @@ +#include + +#define MAXLINE 1000 + +int mgetline(char s[], int lim); + +int strend(char *s, char *t); + +int mystrlen(char *t); + +int main(void) { + char s[MAXLINE], t[MAXLINE]; + int ret; + mgetline(s, MAXLINE); + mgetline(t, MAXLINE); + ret = strend(s, t); + printf("%d", ret); + return 0; +} + +int mgetline(char s[], int lim) { + int c, i; + + for (i = 0; i < lim - 1 && ((c = getchar()) != EOF) && c != '\n'; ++i) + s[i] = c; + + if (c == '\n') { + s[i] = c; + ++i; + } + s[i] = '\0'; + + return i; +} + +int strend(char *s, char *t) { + int len; + len = mystrlen(t); + while (*s != '\0') + ++s; + --s; + + while (*t != '\0') + ++t; + + --t; + while (len > 0) { + if (*t == *s) { + --t; + --s; + --len; + } else + return 0; + } + if (len == 0) + return 1; +} + +int mystrlen(char *t) { + char *p; + p = t; + + while (*p != '\0') + ++p; + + return p - t; +} diff --git a/source/cprogramming/chapter5/cprogs/ex_5.5_strncpy.c b/source/cprogramming/chapter5/cprogs/ex_5.5_strncpy.c new file mode 100644 index 00000000..b939c589 --- /dev/null +++ b/source/cprogramming/chapter5/cprogs/ex_5.5_strncpy.c @@ -0,0 +1,101 @@ +/** + * + * Exercise: 5.5 + * + * Write versions of the library functions strncpy, strncat, and + * strncmp, which operate on at most the first n characters of their argument + * strings. + * + **/ + +#include +#include +#include + +#define MAXSIZE 1000 + +void mystrncpy(char *, char *, int); + +void mystrncat(char *, char *, char *, int); + +int mystrncmp(char *, char *, int); + +int mystrnlen(char *s); + +int main(int argc, char *argv[]) { + + char dest[] = "ABCDEF"; + char source[] = "GHIJ"; + + mystrncpy(dest, source, 4); + printf("%s\n", dest); + + char s1[] = "ABCD"; + char t1[] = "EFGHIJ"; + char *d; + + /* We store the result in a new string d */ + + if ((d = (char *) malloc(sizeof(char) * (strlen(s1) + +4 + 1))) == NULL) { + printf("unable to allocate memory \n"); + return -1; + } + + mystrncat(s1, t1, d, 4); + printf("%s\n", d); /* ABCDEFGH */ + + free(d); + + char s2[] = "ABCDEF"; + char t2[] = "ABC"; + int result; + + result = mystrncmp(s2, t2, 3); + + printf("%d\n", result); + + + return 0; +} + +void mystrncat(char *str1, char *str2, char *dest, int n) { + while (*str1) { + *dest++ = *str1++; + } + while (n-- > 0) { + *dest++ = *str2++; + } + + *dest = '\0'; +} + + +void mystrncpy(char *dest, char *source, int n) { + while (*source && n-- > 0) + *dest++ = *source++; + + int extra = mystrnlen(dest) - n; + + while (extra-- > 0) { + dest++; + } + + *dest = '\0'; +} + +/* mystrcmp: return <0 if s 0 if s > t */ +int mystrncmp(char *lhs, char *rhs, int n) { + for (; *lhs == *rhs; lhs++, rhs++) + if (*lhs == '\0' || --n <= 0) + return 0; + return *lhs - *rhs; + +} + +int mystrnlen(char *s) { + char *p = s; + while (*s != '\0') { + s = s + 1; + } + return s - p; +} diff --git a/source/cprogramming/chapter5/cprogs/ex_5.6_findpattern.c b/source/cprogramming/chapter5/cprogs/ex_5.6_findpattern.c new file mode 100644 index 00000000..8dffeb1e --- /dev/null +++ b/source/cprogramming/chapter5/cprogs/ex_5.6_findpattern.c @@ -0,0 +1,247 @@ +/** + * + * pattern matching program + * + **/ + +#include +#include +#include +#include + +#define NUMBER '0' /* signal that a number was found */ +#define MAXVAL 100 /* maximum depth of val stack */ +#define BUFSIZE 100 +#define MAXLINE 1000 +#define MAXOP 100 + +int getch(void); + +void ungetch(int); + +int getop(char *); + +void push(double); + +double pop(void); + +int mgetline(char *s, int lim); + +int strindex(char *s, char *t); + +int atoiv2(char *); + +void itoav2(int n, char *s); + +void reverse(char *); + +int sp = 0; +int bufp = 0; +double val[MAXVAL]; +char buf[BUFSIZE]; + +char pattern[] = "ould"; /* pattern to search for */ + +/* find all the matching patterns */ + +int main(void) { + char line[MAXLINE]; + + int found = 0; + + /* mgetline ends when a newline starts with X */ + while ((mgetline(line, MAXLINE)) > 0) + if (strindex(line, pattern) >= 0) { + printf("%s\n", line); + found++; + } + + char *s = "1234"; + int ret; + + ret = atoiv2(s); + printf("%d\n", ret); + char s1[100]; + int i = 12345; + itoav2(i, s1); + reverse(s1); + printf("%s\n", s1); + + char *s2 = "This is a line"; + char *t = "is"; + ret = 0; + + ret = strindex(s2, t); + printf("%d\n", ret); + + int type; + double op2; + char s3[MAXOP]; + + while ((type = getop(s3)) != EOF) { + switch (type) { + case NUMBER: + push(atof(s3)); + break; + case '+': + push(pop() + pop()); + break; + case '*': + push(pop() * pop()); + break; + case '-': + op2 = pop(); + push(pop() - op2); + break; + case '/': + op2 = pop(); + if (op2 != 0.0) + push(pop() / op2); + else + printf("error: zero divisor\n"); + break; + case '\n': + printf("\t%.8g\n", pop()); + break; + default: + printf("error: unknown command %s\n", s); + break; + } + } + return 0; + +} + + +int atoiv2(char *s) { + int n, sign; + + for (; isspace(*s); s++) /* skip white space */ + ; + sign = (*s == '-') ? -1 : 1; + + if (*s == '+' || *s == '-') + s++; + for (n = 0; isdigit(*s); s++) + n = 10 * n + *s - '0'; + + return sign * n; +} + +/* reverse polish calculator */ + +/* push: push f onto value stack */ +void push(double f) { + if (sp < MAXVAL) + val[sp++] = f; + else + printf("error: stack full,can't push %g\n", f); +} + +/* pop: pop and return top value from stack */ +double pop(void) { + if (sp > 0) + return val[--sp]; + else { + printf("error: stack empty \n"); + return 0.0; + } +} + +/* getop: get next operator or numeric operand pointer version */ + +/* getop */ +int getop(char *s) { + int c; + + while ((*s = c = getch()) == ' ' || c == '\t'); + *(s + 1) = '\0'; + + if (!isdigit(c) && c != '.') + return c; /* not a number */ + if (isdigit(c)) + while (isdigit(*++s = c = getch())); + + if (c == '.') + while (isdigit(*++s = c = getch())); + + *s = '\0'; + + if (c != EOF) + ungetch(c); + return NUMBER; +} + +int getch(void) { + return (bufp > 0) ? buf[--bufp] : getchar(); +} + +void ungetch(int c) { + if (bufp >= BUFSIZE) + printf("ungetch: too many characters\n"); + else + buf[bufp++] = c; +} + +/* itoa */ + +void itoav2(int n, char *s) { + int sign; + char *t = s; + + if ((sign = n) < 0) + n = -n; + + do { + *s++ = n % 10 + '0'; + } while ((n /= 10) > 0); + + if (sign < 0) + *s++ = '-'; + *s = '\0'; + +} + +/* reverse */ + +void reverse(char *s) { + int c; + char *t; + + for (t = s + (strlen(s) - 1); s < t; s++, t--) { + c = *s; + *s = *t; + *t = c; + } +} + +/* mgetline */ + +int mgetline(char *s, int lim) { + int c; + char *t = s; + + while (--lim > 0 && (c = getchar()) != 'X' && c != '\n') + *s++ = c; + + if (c == '\n') + *s++ = c; + *s = '\0'; + + return s - t; +} + +/* strindex */ + +int strindex(char *s, char *t) { + char *b = s; + char *p, *r; + + for (; *s != '\0'; s++) { + for (p = s, r = t; *r != '\0' && *p == *r; p++, r++); + + if (r > t && *r == '\0') + return s - b; + } + return -1; +} diff --git a/source/cprogramming/chapter5/cprogs/ex_5.7_readlines_using_array.c b/source/cprogramming/chapter5/cprogs/ex_5.7_readlines_using_array.c new file mode 100644 index 00000000..a3dd17c7 --- /dev/null +++ b/source/cprogramming/chapter5/cprogs/ex_5.7_readlines_using_array.c @@ -0,0 +1,131 @@ +#include +#include + +#define MAXLINES 5000 /* max #lines to be sorted */ + +char *lineptr[MAXLINES]; +char linestor[MAXLINES]; + +int readlines(char *lineptr[], char *linestor, int maxlines); + +void writelines(char *lineptr[], int nlines); + +void qsort(char *v[], int left, int right); + +/* sort input lines */ + +int main(void) { + int nlines; /* number of input lines read */ + + if ((nlines = readlines(lineptr, linestor, MAXLINES)) >= 0) { + qsort(lineptr, 0, nlines - 1); + writelines(lineptr, nlines); + return 0; + } else { + printf("error: input too big to sort \n"); + return 1; + } +} + +#define MAXLEN 1000 /* max length of any input line */ +#define MAXSTOR 5000 + +int mgetline(char *, int); + +char *alloc(int); + +/* readlines: read input lines */ +int readlines(char *lineptr[],char *linestor,int maxlines) +{ + int len,nlines; + char line[MAXLEN]; + char *p = linestor; + char *linestop = linestor + MAXSTOR; + char c; + + nlines=0; + loop: + while((len=mgetline(line,MAXLEN)) > 0) + if(nlines >= maxlines || p+len > linestop) + return -1; + else + { + line[len-1] = '\0'; + strcpy(p,line); + lineptr[nlines++]=p; + p+=len; + printf("get a newline? 0 for no, ENTER to input next line."); + c = getchar(); + if(c != '0') + goto loop; + else if(c == '0') + return nlines; + } + return 0; +} + + +/* writelines: write output lines */ +void writelines(char *lineptr[], int nlines) { + int i; + for (i = 0; i < nlines; i++) + printf("%s\n", lineptr[i]); +} + +/* qsort: sort v[left] ... v[right] into increasing order */ +void qsort(char *v[], int left, int right) { + int i, last; + void swap(char *v[], int i, int j); + + if (left >= right) + return; + swap(v, left, (left + right) / 2); + + last = left; + + for (i = left + 1; i <= right; i++) + if (strcmp(v[i], v[left]) < 0) + swap(v, ++last, i); + swap(v, left, last); + qsort(v, left, last - 1); + qsort(v, last + 1, right); +} + +/* swap: interchange v[i] and v[j] */ + +void swap(char *v[], int i, int j) { + char *temp; + + temp = v[i]; + v[i] = v[j]; + v[j] = temp; +} + +#define ALLOCSIZE 10000 /* size of available space */ + +static char allocbuf[ALLOCSIZE]; /* storage for alloc */ +static char *allocp = allocbuf; /* next free position */ + +char *alloc(int n) /* return pointer to n characters */ +{ + if (allocbuf + ALLOCSIZE - allocp >= n) { + allocp += n; + return allocp - n; + } else + return 0; +} + +int mgetline(char *s, int lim) { + int c; + char *t = s; + + while (--lim > 0 && (c = getchar()) != EOF && c != '\n') + *s++ = c; + if (c == '\n') + *s++ = c; + + *s = '\0'; + + return s - t; +} + diff --git a/source/cprogramming/chapter5/cprogs/ex_5.8_day_date.c b/source/cprogramming/chapter5/cprogs/ex_5.8_day_date.c new file mode 100644 index 00000000..9d784d8a --- /dev/null +++ b/source/cprogramming/chapter5/cprogs/ex_5.8_day_date.c @@ -0,0 +1,68 @@ +/* + * Error check in day_of_year and month_day + */ + +#include + +static char daytab[2][13] = { + {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}, + {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31} +}; + +int day_of_year(int year, int month, int day); + +void month_day(int year, int yearday, int *month, int *day); + +int main(void) { + int yearday, month, day; + + yearday = day_of_year(1988, 2, 29); + printf("%d\n", yearday); + + yearday = day_of_year(2020, 2, 31); + printf("%d\n", yearday); + + month_day(1988, 60, &month, &day); + printf("Month: %d, Day: %d\n", month, day); + + month_day(1999, 366, &month, &day); + printf("Month: %d, Day: %d\n", month, day); + + return 0; +} + +/* day_of_year: set day of year from month & day */ + +int day_of_year(int year, int month, int day) { + int i, leap; + + leap = (year % 4 == 0 && year % 100 != 0) || year % 400 == 0; + + if (year < 1 || month < 1 || month > 12 || day < 1 || day > daytab[leap][month]) + return -1; + + for (i = 1; i < month; i++) + day += daytab[leap][i]; + + return day; +} + +/* month_day: set month,day from day of year */ + +void month_day(int year, int yearday, int *month, int *day) { + int i, leap; + + leap = (year % 4 == 0 && year % 100 != 0) || year % 400 == 0; + + if (year < 1 || yearday < 1 || yearday > (leap ? 366 : 365)) { + *month = -1; + *day = -1; + return; + } + + for (i = 1; yearday > daytab[leap][i]; i++) + yearday -= daytab[leap][i]; + + *month = i; + *day = yearday; +} diff --git a/source/cprogramming/chapter5/cprogs/sec_4.1.c b/source/cprogramming/chapter5/cprogs/sec_4.1.c deleted file mode 100644 index 637bb225..00000000 --- a/source/cprogramming/chapter5/cprogs/sec_4.1.c +++ /dev/null @@ -1,40 +0,0 @@ -#include -#define MAXLINE 1000 /* maximum input line length */ -int mgetline(char line[], int max); -int strindex(char source[], char searchfor[]); -char pattern[] = "ould"; /* pattern to search for */ -/* find all lines matching pattern */ -int main() { - char line[MAXLINE]; - int found = 0; - while (mgetline(line, MAXLINE) > 0) - if (strindex(line, pattern) >= 0) { - printf("%s", line); - found++; - } - return found; -} - -/* getline: get line into s, return length */ -int mgetline(char s[], int lim) { - int c, i; - i = 0; - while (--lim > 0 && (c = getchar()) != EOF && c != '\n') - s[i++] = c; - if (c == '\n') - s[i++] = c; - s[i] = '\0'; - return i; -} - -/* strindex: return index of t in s, -1 if none */ -int strindex(char s[], char t[]) { - int i, j, k; - for (i = 0; s[i] != '\0'; i++) { - for (j = i, k = 0; t[k] != '\0' && s[j] == t[k]; j++, k++) - ; - if (k > 0 && t[k] == '\0') - return i; - } - return -1; -} diff --git a/source/cprogramming/chapter5/cprogs/sec_4.2.c b/source/cprogramming/chapter5/cprogs/sec_4.2.c deleted file mode 100644 index e0325d14..00000000 --- a/source/cprogramming/chapter5/cprogs/sec_4.2.c +++ /dev/null @@ -1,32 +0,0 @@ -#include -#include - -/* atof: convert string s to double */ - -double atof(char s[]); - -int main(int argc, char *argv[]) { - char s[8] = "1234.45"; - double d; - d = atof(s); - printf("%f", d); -} - -double atof(char s[]) { - double val, power; - int i, sign; - for (i = 0; isspace(s[i]); i++) /* skip white space */ - ; - sign = (s[i] == '-') ? -1 : 1; - if (s[i] == '+' || s[i] == '-') - i++; - for (val = 0.0; isdigit(s[i]); i++) - val = 10.0 * val + (s[i] - '0'); - if (s[i] == '.') - i++; - for (power = 1.0; isdigit(s[i]); i++) { - val = 10.0 * val + (s[i] - '0'); - power *= 10; - } - return sign * val / power; -} \ No newline at end of file diff --git a/source/cprogramming/chapter5/cprogs/sec_4.3.c b/source/cprogramming/chapter5/cprogs/sec_4.3.c deleted file mode 100644 index 1ac2c4cf..00000000 --- a/source/cprogramming/chapter5/cprogs/sec_4.3.c +++ /dev/null @@ -1,117 +0,0 @@ -#include -#include /* for atof() */ -#define MAXOP 100 /* max size of operand or operator */ -#define NUMBER '0' /* signal that a number was found */ -int getop(char[]); -void push(double); -double pop(void); -/* reverse Polish calculator */ -main() { - int type; - double op2; - char s[MAXOP]; - while ((type = getop(s)) != EOF) { - switch (type) { - case NUMBER: - push(atof(s)); - break; - case '+': - push(pop() + pop()); - break; - case '*': - push(pop() * pop()); - break; - case '-': - op2 = pop(); - push(pop() - op2); - break; - case '/': - op2 = pop(); - if (op2 != 0.0) - push(pop() / op2); - else - printf("error: zero divisor\n"); - break; - case '\n': - printf("\t%.8g\n", pop()); - break; - default: - printf("error: unknown command %s\n", s); - break; - } - } -} - -#define MAXVAL 100 - -int sp = 0; -double val[MAXVAL]; - -void push(double f) { - if (sp < MAXVAL) - val[sp++] = f; - else - printf("error:stack full, cant push %g\n", f); -} - -double pop(void) { - if (sp > 0) - return val[--sp]; - else { - printf("error: stack empty\n"); - return 0.0; - } -} - -#include - -int getch(void); -void ungetch(int); - -int getop(char s[]) { - int i, c; - - while ((s[0] = c = getch()) == ' ' || c == '\t') - ; - s[1] = '\0'; - - i = 0; - if (!isdigit(c) && c != '.' && c != '-') - return c; - - if (c == '-') - if (isdigit(c = getch()) || c == '.') - s[++i] = c; - else { - if (c != EOF) - ungetch(c); - return '-'; - } - - if (isdigit(c)) - while (isdigit(s[++i] = c = getch())) - ; - - if (c == '.') - while (isdigit(s[++i] = c = getch())) - ; - - s[i] = '\0'; - if (c != EOF) - ungetch(c); - return NUMBER; -} - -#define BUFSIZE 100 - -char buf[BUFSIZE]; -int bufp = 0; - -int getch(void) { return (bufp > 0) ? buf[--bufp] : getchar(); } - -void ungetch(int c) { - if (bufp >= BUFSIZE) - printf("ungetch: too many characters\n"); - else - buf[bufp++] = c; -} diff --git a/source/cprogramming/chapter5/ex_5.10_exprcmd.rst b/source/cprogramming/chapter5/ex_5.10_exprcmd.rst index 88f73ec4..6c9f667f 100644 --- a/source/cprogramming/chapter5/ex_5.10_exprcmd.rst +++ b/source/cprogramming/chapter5/ex_5.10_exprcmd.rst @@ -8,14 +8,10 @@ Question Write the program expr, which evaluates a reverse Polish expression from the command line, where each operator or operand is a separate argument. -.. literalinclude:: ../../languages/cprogs/Ex_5.10_exprcmd.c +.. literalinclude:: cprogs/ex_5.10_exprcmd.c :language: c :tab-width: 4 -.. runcode:: ../../languages/cprogs/Ex_5.10_exprcmd.c - :language: c - :codesite: ideone - Explanation =========== @@ -35,7 +31,4 @@ operation. -.. seealso:: - * :c-suggest-improve:`Ex_5.10_exprcmd.c` - * :c-better-explain:`Ex_5.10_exprcmd.rst` diff --git a/source/cprogramming/chapter5/ex_5.11_conddetab.rst b/source/cprogramming/chapter5/ex_5.11_conddetab.rst index f5a62afa..07d2d378 100644 --- a/source/cprogramming/chapter5/ex_5.11_conddetab.rst +++ b/source/cprogramming/chapter5/ex_5.11_conddetab.rst @@ -9,14 +9,10 @@ Modify the program entab and detab (written as exercises in Chapter 1) to accept a list of tab stops as arguments. Use the default tab settings if there are no arguments. -.. literalinclude:: ../../languages/cprogs/Ex_5.11_conddetab.c +.. literalinclude:: cprogs/ex_5.11_conddetab.c :language: c :tab-width: 4 -.. runcode:: ../../languages/cprogs/Ex_5.11_conddetab.c - :language: c - :codesite: ideone - Explanation =========== @@ -39,9 +35,3 @@ when a sentence is read with detab, the function consults `tabpos` function to see if it s tab. If it is tab, then till it meets the next tab, it will output space ' ', thus converting the tabs to spaces. - - -.. seealso:: - - * :c-suggest-improve:`Ex_5.11_conddetab.c` - * :c-better-explain:`Ex_5.11_conddetab.rst` diff --git a/source/cprogramming/chapter5/ex_5.12_condientab.rst b/source/cprogramming/chapter5/ex_5.12_condientab.rst index 28e8097b..bde5a5d6 100644 --- a/source/cprogramming/chapter5/ex_5.12_condientab.rst +++ b/source/cprogramming/chapter5/ex_5.12_condientab.rst @@ -7,13 +7,10 @@ Question Extend entab and detab to accept the shorthand. -.. literalinclude:: ../../languages/cprogs/Ex_5.12_condientab.c +.. literalinclude:: cprogs/ex_5.12_condientab.c :language: c :tab-width: 4 -.. runcode:: ../../languages/cprogs/Ex_5.12_condientab.c - :language: c - :codesite: ideone Explanation =========== @@ -57,7 +54,4 @@ next space, we can verify it for the new position. -.. seealso:: - * :c-suggest-improve:`Ex_5.12_condientab.c` - * :c-better-explain:`Ex_5.12_condientab.rst` diff --git a/source/cprogramming/chapter5/ex_5.13_tailn.rst b/source/cprogramming/chapter5/ex_5.13_tailn.rst index 038da37a..d837d56b 100644 --- a/source/cprogramming/chapter5/ex_5.13_tailn.rst +++ b/source/cprogramming/chapter5/ex_5.13_tailn.rst @@ -7,13 +7,10 @@ Question Write the program tail, which prints the last n lines of its input. -.. literalinclude:: ../../languages/cprogs/Ex_5.13_tailn.c +.. literalinclude:: cprogs/ex_5.13_tailn.c :language: c :tab-width: 4 -.. runcode:: ../../languages/cprogs/Ex_5.13_tailn.c - :language: c - :codesite: ideone Explanation =========== @@ -28,7 +25,7 @@ be printed, the default value being 100. char *lineptr[LINES]; /* pointer to lines read */ The program works by first allocating enough memory for the last n lines in a -buffer. Gets each line using `mgetline(line, MAXLEN)` and then copies each line +buffer. Gets each line using `_getline(line, MAXLEN)` and then copies each line to an index entry in the lineptr array. :: @@ -47,7 +44,4 @@ exists, we print the line, decrementing the count at each step. -.. seealso:: - * :c-suggest-improve:`Ex_5.13_tailn.c` - * :c-better-explain:`Ex_5.13_tailn.rst` diff --git a/source/cprogramming/chapter5/ex_5.14_sortrevnum.rst b/source/cprogramming/chapter5/ex_5.14_sortrevnum.rst index 8cff5b02..1de55ca0 100644 --- a/source/cprogramming/chapter5/ex_5.14_sortrevnum.rst +++ b/source/cprogramming/chapter5/ex_5.14_sortrevnum.rst @@ -8,14 +8,10 @@ Question Modify the sort program to handle a -r flag, which indicates sorting in reverse (decreasing) order. Be sure that -r works with -n. -.. literalinclude:: ../../languages/cprogs/Ex_5.14_sortrevnum.c +.. literalinclude:: cprogs/ex_5.14_sortrevnum.c :language: c :tab-width: 4 -.. runcode:: ../../languages/cprogs/Ex_5.14_sortrevnum.c - :language: c - :codesite: ideone - Explanation =========== @@ -110,7 +106,4 @@ program displays the output as we desire. -.. seealso:: - * :c-suggest-improve:`Ex_5.14_sortrevnum.c` - * :c-better-explain:`Ex_5.14_sortrevnum.rst` diff --git a/source/cprogramming/chapter5/ex_5.15_sortfnr.rst b/source/cprogramming/chapter5/ex_5.15_sortfnr.rst index fb0c482d..368b5a4c 100644 --- a/source/cprogramming/chapter5/ex_5.15_sortfnr.rst +++ b/source/cprogramming/chapter5/ex_5.15_sortfnr.rst @@ -8,22 +8,29 @@ Question Add the option -f to fold upper and lower case together, so that case distinctions are not made during sorting; for example, a and A compare equal. -.. literalinclude:: ../../languages/cprogs/Ex_5.15_sortfnr.c +.. literalinclude:: cprogs/ex_5.15_sortfnr.c :language: c :tab-width: 4 -.. runcode:: ../../languages/cprogs/Ex_5.15_sortfnr.c - :language: c - :codesite: ideone - Explanation =========== +This is a sort function, which sorts the given input lines. But this function adds a flag `-f` which introduces case insensitive folding. + +:: + + ./ex_5.15_sortfnr -f + hello + Hello + Apple + Apple + Hello + hello + + + -.. seealso:: - * :c-suggest-improve:`Ex_5.15_sortfnr.c` - * :c-better-explain:`Ex_5.15_sortfnr.rst` diff --git a/source/cprogramming/chapter5/ex_5.16_sort_dfnr.rst b/source/cprogramming/chapter5/ex_5.16_sort_dfnr.rst index a5faf76c..0918ede2 100644 --- a/source/cprogramming/chapter5/ex_5.16_sort_dfnr.rst +++ b/source/cprogramming/chapter5/ex_5.16_sort_dfnr.rst @@ -8,20 +8,48 @@ Question Add the -d (``directory order``) option, which makes comparisons only on letters, numbers and blanks. Make sure it works in conjunction with -f. -.. literalinclude:: ../../languages/cprogs/Ex_5.16_sort_dfnr.c +.. literalinclude:: cprogs/ex_5.16_sort_dfnr.c :language: c :tab-width: 4 -.. runcode:: ../../languages/cprogs/Ex_5.16_sort_dfnr.c - :language: c - :codesite: ideone Explanation =========== +This is a command-line sorting program that can sort text lines in different ways based on various options. +The `-d` flag sorts the lines of input in the directory order, that is ignoring punctuation marks. +The `-f` folds the input, that is, it does a case insensitive comparison of lower case and upper case lines. + + +:: + + ./ex_5.16_sort_dfnr -d + something-anotherthing + some-thing + another-thing + one! + once + ^D + another-thing + once + one! + some-thing + something-anotherthing + + +:: + + ./ex_5.16_sort_dfnr -df + Apple + apple + apple-pie + Carrot-Cake + + + apple + Apple + apple-pie + Carrot-Cake -.. seealso:: - * :c-suggest-improve:`Ex_5.16_sort_dfnr.c` - * :c-better-explain:`Ex_5.16_sort_dfnr.rst` diff --git a/source/cprogramming/chapter5/ex_5.17_sortdfnr-withoption.rst b/source/cprogramming/chapter5/ex_5.17_sortdfnr-withoption.rst index 7c9ea9fd..67c15c01 100644 --- a/source/cprogramming/chapter5/ex_5.17_sortdfnr-withoption.rst +++ b/source/cprogramming/chapter5/ex_5.17_sortdfnr-withoption.rst @@ -10,20 +10,60 @@ lines, each field sorted according to an independent set of options. (The index for this book was sorted with -df for the index category and -n for the page numbers.) -.. literalinclude:: ../../languages/cprogs/Ex_5.17_sortdfnr-withoption.c +.. literalinclude:: cprogs/ex_5.17_sortdfnr-withoption.c :language: c :tab-width: 4 -.. runcode:: ../../languages/cprogs/Ex_5.17_sortdfnr-withoption.c - :language: c - :codesite: ideone - Explanation =========== +This program is an enhanced version of the previous sort program. +The main difference is that it can sort text based on specific fields (portions) within each line, rather than just sorting entire lines. This is particularly useful for sorting structured data like tables or indexes. + +Key differences from the previous version: + +Added field handling with two new parameters: + ++pos1: Specifies where to start looking in each line (starting position) +-pos2: Specifies where to stop looking in each line (ending position) + + +Example usage: + +# Original data (index with page numbers): +Arrays, dynamic 125 +Arrays, initialization 89 +Arrays, multidimensional 110 + +:: + + sort -df +0 -2 -n +2 + + # Using an example line: "Arrays, dynamic 125" + + +Let's separate each part: + +* -df: These are sorting options +* -d: Directory order (only considers letters, numbers, and spaces) +* -f: Fold case (treats uppercase and lowercase as the same) + + +:: + + +0 -2: This specifies the first field to sort by + + +* +0: Start from position 0 (beginning of line) +* -2: Stop before position 2 (in this case, the text portion) + +So this would look at "Arrays, dynamic" + +:: -.. seealso:: + -n +2: This specifies the second field to sort by - * :c-suggest-improve:`Ex_5.17_sortdfnr-withoption.c` - * :c-better-explain:`Ex_5.17_sortdfnr-withoption.rst` +* -n: Use numeric sorting +* +2: Start from position 2 (where the numbers are) +* So this would look at "125" diff --git a/source/cprogramming/chapter5/ex_5.18_dcl-errorec.rst b/source/cprogramming/chapter5/ex_5.18_dcl-errorec.rst index 5d9c903a..ac8273d0 100644 --- a/source/cprogramming/chapter5/ex_5.18_dcl-errorec.rst +++ b/source/cprogramming/chapter5/ex_5.18_dcl-errorec.rst @@ -7,20 +7,23 @@ Question Make dcl recover from input errors. -.. literalinclude:: ../../languages/cprogs/Ex_5.18_dcl-errorec.c +.. literalinclude:: cprogs/ex_5.18_dcl-errorec.c :language: c :tab-width: 4 -.. runcode:: ../../languages/cprogs/Ex_5.18_dcl-errorec.c - :language: c - :codesite: ideone - Explanation =========== +This program is a recursive descent parser that converts C-style declarations into English descriptions. +The program takes a C declaration as input and converts it into a more readable English description. For example: + +:: + + ./ex_5.18_dcl-errorec + char *str[] + str arg[] of pointer to char -.. seealso:: +The program has an errmsg function that is called whenever an error is detected during parsing. +The dcl and dirdcl functions, which are responsible for parsing the declarator, continue parsing even if an error is encountered. - * :c-suggest-improve:`Ex_5.18_dcl-errorec.c` - * :c-better-explain:`Ex_5.18_dcl-errorec.rst` diff --git a/source/cprogramming/chapter5/ex_5.19_undcl.rst b/source/cprogramming/chapter5/ex_5.19_undcl.rst index bb81749f..ba9f9e94 100644 --- a/source/cprogramming/chapter5/ex_5.19_undcl.rst +++ b/source/cprogramming/chapter5/ex_5.19_undcl.rst @@ -7,20 +7,52 @@ Question Modify undcl so that it does not add redundant parentheses to declarations. -.. literalinclude:: ../../languages/cprogs/Ex_5.19_undcl.c +.. literalinclude:: cprogs/ex_5.19_undcl.c :language: c :tab-width: 4 -.. runcode:: ../../languages/cprogs/Ex_5.19_undcl.c - :language: c - :codesite: ideone Explanation =========== +The book provides this undcl implementation + +:: + + /* undcl: convert word descriptions to declarations */ + main() { + int type; + char temp[MAXTOKEN]; + while (gettoken() != EOF) { + strcpy(out, token); + while ((type = gettoken()) != '\n') + } + if (type == PARENS || type == BRACKETS) + strcat(out, token); + else if (type == '*') { + sprintf(temp, "(*%s)", out); + strcpy(out, temp); + } else if (type == NAME) { + sprintf(temp, "%s %s", token, out); + strcpy(out, temp); + } else + printf("invalid input at %s\n", token); + } + +The important change in our implementation from the book program is, if the nexttoken is a PARENS or BRACKETS then we +print them out. + +:: + + + if (type == PARENS || type == BRACKETS) + strcat(out, token); + else if (type == '*') { + + if ((type = nexttoken()) == PARENS || type == BRACKETS) + sprintf(temp, "(*%s)", out); + + else + + sprintf(temp, "*%s", out); + strcpy(out, temp); + } else if (type == NAME) { -.. seealso:: - - * :c-suggest-improve:`Ex_5.19_undcl.c` - * :c-better-explain:`Ex_5.19_undcl.rst` diff --git a/source/cprogramming/chapter5/ex_5.1_getint.rst b/source/cprogramming/chapter5/ex_5.1_getint.rst index 1645b708..7de50d3f 100644 --- a/source/cprogramming/chapter5/ex_5.1_getint.rst +++ b/source/cprogramming/chapter5/ex_5.1_getint.rst @@ -8,13 +8,10 @@ Question As written, getint treats a + or - not followed by a digit as a valid representation of zero. Fix it to push such a character back on the input. -.. literalinclude:: ../../languages/cprogs/Ex_5.1_getint.c +.. literalinclude:: cprogs/ex_5.1_getint.c :language: c :tab-width: 4 -.. runcode:: ../../languages/cprogs/Ex_5.1_getint.c - :language: c - :codesite: ideone Explanation =========== @@ -80,7 +77,4 @@ array. -.. seealso:: - * :c-suggest-improve:`Ex_5.1_getint.c` - * :c-better-explain:`Ex_5.1_getint.rst` diff --git a/source/cprogramming/chapter5/ex_5.20_dcl-funcargs.rst b/source/cprogramming/chapter5/ex_5.20_dcl-funcargs.rst index a98cdde0..a18df686 100644 --- a/source/cprogramming/chapter5/ex_5.20_dcl-funcargs.rst +++ b/source/cprogramming/chapter5/ex_5.20_dcl-funcargs.rst @@ -8,20 +8,49 @@ Question Expand dcl to handle declarations with function argument types, qualifiers like const, and so on. -.. literalinclude:: ../../languages/cprogs/Ex_5.20_dcl-funcargs.c +The implementation of this program is from https://clc-wiki.net/wiki/K%26R2_solutions:Chapter_5:Exercise_20 + +.. literalinclude:: cprogs/ex_5.20_dcl-funcargs.c :language: c :tab-width: 4 -.. runcode:: ../../languages/cprogs/Ex_5.20_dcl-funcargs.c - :language: c - :codesite: ideone Explanation =========== +This program is a simple parser that reads a C declaration, breaks down the C declaration into constituent parts and provides +a human readable representation of the declaration. It handles basic declaration syntax including pointers, functions, arrays and parameter declarations. + + +:: + + int simple; + simple: int + int dec, *larator, lists[]; + dec: int + larator: pointer to int + lists: array[] of int + static char *storage; + storage: pointer to static char + volatile int qualifier; + qualifier: volatile int + long unsigned int compound; + compound: long unsigned int + void arguments(char *name, double time); + arguments: function expecting 2 parameters: parameter name (pointer to char) parameter time (double) returning nothing + int nested_args(char *(*read)(void), void (*write)(char *message)); + nested_args: function expecting 2 parameters: parameter read (pointer to function expecting no parameters returning pointer to char) parameter write (pointer to function expecting 1 parameter: parameter message (pointer to char) returning nothing) returning int + void unnamed(char (*)(long)); + unnamed: function expecting 1 parameter: unnamed parameter (pointer to function expecting 1 parameter: unnamed parameter (long) returning char) returning nothing + static const long unsigned int (*book2)[13], *book3[13], complex(volatile char (*(*book6(void))[])(char **book1,void *book4(),void (*book5)()),char (*(*book7[3])())[5]); + book2: pointer to array[13] of static const long unsigned int + book3: array[13] of pointer to static const long unsigned int + complex: function expecting 2 parameters: parameter book6 (function expecting no parameters returning pointer to array[] of pointer to function expecting 3 parameters: parameter book1 (pointer to pointer to char) parameter book4 (obsolescent non-prototype function declaration with unknown parameters returning pointer to void) parameter book5 (pointer to obsolescent non-prototype function declaration with unknown parameters returning nothing) returning volatile char) parameter book7 (array[3] of pointer to obsolescent non-prototype function declaration with unknown parameters returning pointer to array[5] of char) returning static const long unsigned int + _Thread_local static int multipleStorageClassSpecifiers; + multipleStorageClassSpecifiers: _Thread_local static int + const volatile int multipleTypeQualifiers; + multipleTypeQualifiers: const volatile int + void everythingSupported(char a, signed char a, unsigned char a, short a, signed short a, short int a, signed short int a, unsigned short a, unsigned short int a, int a, signed a, signed int a, unsigned a, unsigned int a, long a, signed long a, long int a, signed long int a, unsigned long a, unsigned long int a, long long a, signed long long a, long long int a, signed long long int a, unsigned long long a, unsigned long long int a, float a, double a, long double a, _Bool a, float _Complex a, double _Complex a, long double _Complex a, _Atomic int a, const int a, restrict int a, volatile int a, _Thread_local int a, auto int a, extern int a, register int a, static int a); + everythingSupported: function expecting 42 parameters: parameter a (char) parameter a (signed char) parameter a (unsigned char) parameter a (short) parameter a (signed short) parameter a (short int) parameter a (signed short int) parameter a (unsigned short) parameter a (unsigned short int) parameter a (int) parameter a (signed) parameter a (signed int) parameter a (unsigned) parameter a (unsigned int) parameter a (long) parameter a (signed long) parameter a (long int) parameter a (signed long int) parameter a (unsigned long) parameter a (unsigned long int) parameter a (long long) parameter a (signed long long) parameter a (long long int) parameter a (signed long long int) parameter a (unsigned long long) parameter a (unsigned long long int) parameter a (float) parameter a (double) parameter a (long double) parameter a (_Bool) parameter a (float _Complex) parameter a (double _Complex) parameter a (long double _Complex) parameter a (_Atomic int) parameter a (const int) parameter a (restrict int) parameter a (volatile int) parameter a (_Thread_local int) parameter a (auto int) parameter a (extern int) parameter a (register int) parameter a (static int) returning nothing -.. seealso:: - - * :c-suggest-improve:`Ex_5.20_dcl-funcargs.c` - * :c-better-explain:`Ex_5.20_dcl-funcargs.rst` diff --git a/source/cprogramming/chapter5/ex_5.2_getfloat.rst b/source/cprogramming/chapter5/ex_5.2_getfloat.rst index 8abd6408..0c34df82 100644 --- a/source/cprogramming/chapter5/ex_5.2_getfloat.rst +++ b/source/cprogramming/chapter5/ex_5.2_getfloat.rst @@ -8,14 +8,10 @@ Question Write getfloat, the floating-point analog of getint. What type does getfloat return as its function value? -.. literalinclude:: ../../languages/cprogs/Ex_5.2_getfloat.c +.. literalinclude:: cprogs/ex_5.2_getfloat.c :language: c :tab-width: 4 -.. runcode:: ../../languages/cprogs/Ex_5.2_getfloat.c - :language: c - :codesite: ideone - Explanation =========== @@ -61,7 +57,4 @@ program. -.. seealso:: - * :c-suggest-improve:`Ex_5.2_getfloat.c` - * :c-better-explain:`Ex_5.2_getfloat.rst` diff --git a/source/cprogramming/chapter5/ex_5.3_strcat.rst b/source/cprogramming/chapter5/ex_5.3_strcat.rst index 9c54d787..bc411417 100644 --- a/source/cprogramming/chapter5/ex_5.3_strcat.rst +++ b/source/cprogramming/chapter5/ex_5.3_strcat.rst @@ -8,13 +8,10 @@ Question Write a pointer version of the function strcat that we showed in Chapter 2: strcat(s,t) copies the string t to the end of s. -.. literalinclude:: ../../languages/cprogs/Ex_5.3_strcat.c +.. literalinclude:: cprogs/ex_5.3_strcat.c :language: c :tab-width: 4 -.. runcode:: ../../languages/cprogs/Ex_5.3_strcat.c - :language: c - :codesite: ideone Explanation =========== @@ -49,7 +46,4 @@ The construct `while((*s=*t)!='\0')` assigns the character in `t` to `s` and the -.. seealso:: - * :c-suggest-improve:`Ex_5.3_strcat.c` - * :c-better-explain:`Ex_5.3_strcat.rst` diff --git a/source/cprogramming/chapter5/ex_5.4_strend.rst b/source/cprogramming/chapter5/ex_5.4_strend.rst index 3864c899..29ea502d 100644 --- a/source/cprogramming/chapter5/ex_5.4_strend.rst +++ b/source/cprogramming/chapter5/ex_5.4_strend.rst @@ -8,14 +8,10 @@ Question Write the function strend(s,t), which returns 1 if the string t occurs at the end of the string s, and zero otherwise. -.. literalinclude:: ../../languages/cprogs/Ex_5.4_strend.c +.. literalinclude:: cprogs/ex_5.4_strend.c :language: c :tab-width: 4 -.. runcode:: ../../languages/cprogs/Ex_5.4_strend.c - :language: c - :codesite: ideone - Explanation =========== @@ -79,7 +75,4 @@ return 0. -.. seealso:: - * :c-suggest-improve:`Ex_5.4_strend.c` - * :c-better-explain:`Ex_5.4_strend.rst` diff --git a/source/cprogramming/chapter5/ex_5.5_strncpy.rst b/source/cprogramming/chapter5/ex_5.5_strncpy.rst index f610d8bf..bd40882b 100644 --- a/source/cprogramming/chapter5/ex_5.5_strncpy.rst +++ b/source/cprogramming/chapter5/ex_5.5_strncpy.rst @@ -8,13 +8,10 @@ Question Write versions of the library functions strncpy, strncat, and strncmp, which operate on at most the first n characters of their argument strings. -.. literalinclude:: ../../languages/cprogs/Ex_5.5_strncpy.c +.. literalinclude:: cprogs/ex_5.5_strncpy.c :language: c :tab-width: 4 -.. runcode:: ../../languages/cprogs/Ex_5.5_strncpy.c - :language: c - :codesite: ideone Explanation =========== @@ -46,7 +43,4 @@ is smaller than rhs or positive value if lhs is greater than rhs. -.. seealso:: - * :c-suggest-improve:`Ex_5.5_strncpy.c` - * :c-better-explain:`Ex_5.5_strncpy.rst` diff --git a/source/cprogramming/chapter5/ex_5.6_findpattern.rst b/source/cprogramming/chapter5/ex_5.6_findpattern.rst index 480d3574..8ebf58e8 100644 --- a/source/cprogramming/chapter5/ex_5.6_findpattern.rst +++ b/source/cprogramming/chapter5/ex_5.6_findpattern.rst @@ -10,23 +10,19 @@ instead of array indexing. Good possibilities include getline (Chapters 1 and 4), atoi, itoa, and their variants (Chapters 2, 3, and 4), reverse (Chapter 3), and strindex and getop (Chapter 4). -.. literalinclude:: ../../languages/cprogs/Ex_5.6_findpattern.c +.. literalinclude:: cprogs/ex_5.6_findpattern.c :language: c :tab-width: 4 -.. runcode:: ../../languages/cprogs/Ex_5.6_findpattern.c - :language: c - :codesite: ideone - Explanation =========== -mgetline takes a string ``(char *)`` and MAXLINE, the maximum length of the line. It +_getline takes a string ``(char *)`` and MAXLINE, the maximum length of the line. It gets one character at a time using getchar() and as long as we are under limit (less than MAXLINE) and it is not \n character. It stores the charaacters in the line, advancing the pointer for each character. -When it hits \n, it adds \n and closes the line with \0. mgetline returns the +When it hits \n, it adds \n and closes the line with \0. _getline returns the length of the line, subtracting the last address with initial address. @@ -76,7 +72,4 @@ that we found a NUMBER. -.. seealso:: - * :c-suggest-improve:`Ex_5.6_findpattern.c` - * :c-better-explain:`Ex_5.6_findpattern.rst` diff --git a/source/cprogramming/chapter5/ex_5.7_readlines_using_array.rst b/source/cprogramming/chapter5/ex_5.7_readlines_using_array.rst index 88fdcfac..e3a299da 100644 --- a/source/cprogramming/chapter5/ex_5.7_readlines_using_array.rst +++ b/source/cprogramming/chapter5/ex_5.7_readlines_using_array.rst @@ -9,14 +9,10 @@ Rewrite readlines to store lines in an array supplied by main, rather than calling alloc to maintain storage. How much faster is the program? -.. literalinclude:: ../../languages/cprogs/Ex_5.7_readlines_using_array.c +.. literalinclude:: cprogs/ex_5.7_readlines_using_array.c :language: c :tab-width: 4 -.. runcode:: ../../languages/cprogs/Ex_5.7_readlines_using_array.c - :language: c - :codesite: ideone - Explanation =========== @@ -24,9 +20,24 @@ This uses the same qsort program. But instead of calculating the memory required using the alloc operator. It sends a predefined amount of memory from the main program. +It's a line sorting program written in C that reads input lines, sorts them alphabetically, and prints them out. + +:: + + $ ./ex_5.7_readlines_using_array + this is a line. + Another line. + Good Line. + Abacus + Backgammon. + ^D + Abacus + Another line. + Backgammon. + Good Line. + this is a line. + + -.. seealso:: - * :c-suggest-improve:`Ex_5.7_readlines_using_array.c` - * :c-better-explain:`Ex_5.7_readlines_using_array.rst` diff --git a/source/cprogramming/chapter5/ex_5.8_day_date.rst b/source/cprogramming/chapter5/ex_5.8_day_date.rst index aa996ad3..ff249bd3 100644 --- a/source/cprogramming/chapter5/ex_5.8_day_date.rst +++ b/source/cprogramming/chapter5/ex_5.8_day_date.rst @@ -7,14 +7,10 @@ Question There is no error checking in day_of_year or month_day. Remedy this defect. -.. literalinclude:: ../../languages/cprogs/Ex_5.8_day_date.c +.. literalinclude:: cprogs/ex_5.8_day_date.c :language: c :tab-width: 4 -.. runcode:: ../../languages/cprogs/Ex_5.8_day_date.c - :language: c - :codesite: ideone - Explanation =========== @@ -38,7 +34,4 @@ after conversion. -.. seealso:: - * :c-suggest-improve:`Ex_5.8_day_date.c` - * :c-better-explain:`Ex_5.8_day_date.rst` diff --git a/source/cprogramming/chapter5/index.rst b/source/cprogramming/chapter5/index.rst new file mode 100644 index 00000000..3a05cf99 --- /dev/null +++ b/source/cprogramming/chapter5/index.rst @@ -0,0 +1,29 @@ +========= +Chapter 5 +========= + +.. toctree:: + :maxdepth: 1 + + + ex_5.1_getint + ex_5.20_dcl-funcargs + ex_5.2_getfloat + ex_5.3_strcat + ex_5.4_strend + ex_5.5_strncpy + ex_5.6_findpattern + ex_5.7_readlines_using_array + ex_5.8_day_date + ex_5.10_exprcmd + ex_5.11_conddetab + ex_5.12_condientab + ex_5.13_tailn + ex_5.14_sortrevnum + ex_5.15_sortfnr + ex_5.16_sort_dfnr + ex_5.17_sortdfnr-withoption + ex_5.18_dcl-errorec + ex_5.19_undcl + ex_5.20_dcl-funcargs + diff --git a/source/cprogramming/chapter6/cprogs/ex_6.1_getword.c b/source/cprogramming/chapter6/cprogs/ex_6.1_getword.c index 6a09a459..90442886 100644 --- a/source/cprogramming/chapter6/cprogs/ex_6.1_getword.c +++ b/source/cprogramming/chapter6/cprogs/ex_6.1_getword.c @@ -5,16 +5,17 @@ struct key { char *word; int count; -} keytab[] = {"auto", 0, "break", 0, "case", 0, "char", 0, - "const", 0, "continue", 0, "default", 0, "do", 0, - "double", 0, "else", 0, "enum", 0, "extern", 0, - "float", 0, "for", 0, "goto", 0, "if", 0, - "int", 0, "long", 0, "register", 0, "return", 0, - "short", 0, "signed", 0, "sizeof", 0, "static", 0, - "struct", 0, "switch", 0, "typedef", 0, "union", 0, - "unsigned", 0, "void", 0, "volatite", 0, "while", 0}; +} keytab[] = {"auto", 0, "break", 0, "case", 0, "char", 0, + "const", 0, "continue", 0, "default", 0, "do", 0, + "double", 0, "else", 0, "enum", 0, "extern", 0, + "float", 0, "for", 0, "goto", 0, "if", 0, + "int", 0, "long", 0, "register", 0, "return", 0, + "short", 0, "signed", 0, "sizeof", 0, "static", 0, + "struct", 0, "switch", 0, "typedef", 0, "union", 0, + "unsigned", 0, "void", 0, "volatite", 0, "while", 0}; int mygetword(char *, int); + int binsearch(char *, struct key *, int); #define NKEYS (sizeof(keytab) / sizeof(keytab[0])) @@ -33,7 +34,7 @@ int main(int argc, char *argv[]) { printf("%4d %s\n", keytab[n].count, keytab[n].word); } -int binsearch(char *word, struct key keytab[], int n) { +int binsearch(char *word, struct key lkeytab[], int n) { int cond; int low, high, mid; @@ -41,7 +42,7 @@ int binsearch(char *word, struct key keytab[], int n) { high = n - 1; while (low <= high) { mid = (low + high) / 2; - if ((cond = strcmp(word, keytab[mid].word)) < 0) + if ((cond = strcmp(word, lkeytab[mid].word)) < 0) high = mid - 1; else if (cond > 0) low = mid + 1; @@ -57,21 +58,17 @@ int mygetword(char *word, int lim) { char *w = word; int t; - while (isspace(c = getch())) - ; + while (isspace(c = getch())); if (c != EOF) *w++ = c; if (!isalpha(c)) { if (c == '\"') { /*string constant*/ - for (c = getch(); c != '\"'; c = getch()) - ; + for (c = getch(); c != '\"'; c = getch()); } else if (c == '#') { /*preprocessor*/ - for (c = getch(); c != '\n'; c = getch()) - ; + for (c = getch(); c != '\n'; c = getch()); } else if (c == '/') /*comment*/ if ((c = getch()) == '/') { /*single comment*/ - for (c = getch(); c != '\n'; c = getch()) - ; + for (c = getch(); c != '\n'; c = getch()); } else if (c == '*') { /*mutiline comment*/ for (c = getch(), t = getch(); c != '*' && t != '/'; c = getch(), t = getch()) @@ -79,8 +76,7 @@ int mygetword(char *word, int lim) { } else ungetch(c); else /*underscore*/ - for (; !isspace(c) && c != EOF; c = getch()) - ; + for (; !isspace(c) && c != EOF; c = getch()); if (c != '\"' && c != '\n' && c != '/') ungetch(c); *w = '\0'; diff --git a/source/cprogramming/chapter6/cprogs/ex_6.2_identical_variables.c b/source/cprogramming/chapter6/cprogs/ex_6.2_identical_variables.c index d7997744..f9c15f40 100644 --- a/source/cprogramming/chapter6/cprogs/ex_6.2_identical_variables.c +++ b/source/cprogramming/chapter6/cprogs/ex_6.2_identical_variables.c @@ -8,7 +8,6 @@ */ #include -#include #include #include #include @@ -47,11 +46,17 @@ struct simword { }; struct tnode *addtree(struct tnode *, char *); + void treeprint(const struct tnode *); + int mgetword(char *, int); + struct simroot *addroot(struct simroot *, struct tnode *, int); + struct simroot *parse(struct tnode *, int); + void printlist(struct simroot *, int); + void printwords(struct simword *); int main(int argc, char *argv[]) { @@ -154,8 +159,11 @@ void printwords(struct simword *p) { } struct tnode *talloc(void); + char *mstrdup(char *); + struct simword *walloc(struct simword *, struct tnode *); + void addword(struct simword *, struct tnode *); /* @@ -168,14 +176,14 @@ void addword(struct simword *, struct tnode *); struct simroot *addroot(struct simroot *p, struct tnode *n, int len) { /* end of list, create a new root */ if (p == NULL) { - p = (struct simroot *)malloc(sizeof(struct simroot)); + p = (struct simroot *) malloc(sizeof(struct simroot)); p->nextroot = NULL; p->firstword = walloc(p->firstword, n); } - /* word belongs to this list, add it */ + /* word belongs to this list, add it */ else if (strncmp(p->firstword->word, n->word, len) == 0) addword(p->firstword, n); - /* haven't found the right root or end yet */ + /* haven't found the right root or end yet */ else p->nextroot = addroot(p->nextroot, n, len); return p; @@ -193,14 +201,14 @@ void addword(struct simword *p, struct tnode *n) { /* end of list. create a new node */ if (p->nextword == NULL) p->nextword = walloc(p->nextword, n); - /* haven't reached the end yet */ + /* haven't reached the end yet */ else addword(p->nextword, n); } /* walloc: Creates a new simword node. */ struct simword *walloc(struct simword *p, struct tnode *n) { - p = (struct simword *)malloc(sizeof(struct simword)); + p = (struct simword *) malloc(sizeof(struct simword)); if (p != NULL) { p->word = n->word; p->count = n->count; @@ -221,8 +229,7 @@ int mgetword(char *word, int lim) { comment = string = directive = OUT; - while (isspace(c = getch())) - ; + while (isspace(c = getch())); /* Check if inside a comment */ @@ -345,13 +352,13 @@ void treeprint(const struct tnode *p) { /* talloc: From K&R2 page 142. Makes a tnode. */ struct tnode *talloc(void) { - return (struct tnode *)malloc(sizeof(struct tnode)); + return (struct tnode *) malloc(sizeof(struct tnode)); } /* strdup: From K&R2 page 143. Makes a duplicate of s. */ char *mstrdup(char *s) { char *p; - p = (char *)malloc(strlen(s) + 1); + p = (char *) malloc(strlen(s) + 1); if (p != NULL) strcpy(p, s); return p; diff --git a/source/cprogramming/chapter6/cprogs/ex_6.3.c b/source/cprogramming/chapter6/cprogs/ex_6.3.c index 68ee888d..a2c3b391 100644 --- a/source/cprogramming/chapter6/cprogs/ex_6.3.c +++ b/source/cprogramming/chapter6/cprogs/ex_6.3.c @@ -1,297 +1,249 @@ /* - * Write a cross-referencer that prints a list of all words in a document, and - * for each word, a list of the line numbers on which it occurs. Remove noise - * words like "the" and "and" so on. - * - */ +* Write a cross-referencer that prints a list of all words in a document, +* and for each word, a list of the line numbers on which it occurs. +* Remove noise words like "the" and "and" so on. +* +*/ /* - * 1. Add all the word structures (word structure will have word and line - * numbers to the tree. - * 2. A word can occur in more than one line, if the same word is found and the - * new line number to the line numbers. - * 3. So line numbers should be a linked list of numbers. - * 4. Print it. + * 1. Create a binary tree that will contain words and structure with lines on which words occur. + * 2. Check if the word is noisy with binary search. + * 3. Print the words and lines. * */ -#include -#include +#define N_OF_NOISEWORDS 123 + +const char *noiseWords[N_OF_NOISEWORDS]={"a", "about", "after", "all", + "also", "an", "another", "any", "are", "as", "and", "at", "be", + "because", "been", "before", "being", "between", "but", "both", + "by", "came", "can", "come", "could","did", "do","each", "even", + "for", "from", "further", "furthermore","get", "got","has", "had", + "he", "have", "her", "here", "him", "himself", "his", "how", "hi", + "however","i", "if", "in", "into", "is", "it", "its", "indeed","just", + "like","made", "many", "me", "might", "more", "moreover", "most", + "much","must", "my","never", "not", "now","of", "on", "only", "other", + "our", "out", "or", "over","said", "same", "see", "should", "since", + "she", "some", "still", "such","take", "than", "that", "the", "their", + "them", "then", "there", "these", "therefore", "they", "this", "those", + "through", "to", "too", "thus","under", "up","very","was", "way", "we", + "well", "were", "what", "when", "where", "which", "while", "who", + "will", "with", "would","you", "your"}; + #include +#include #include #include -#define MAXWORD 1000 /* longest word that can be read by mgetword */ -#define DEFAULT_COMP_LEN 8 /* default length to compare */ +#define MAXWORD 500 -/* - * tnode: Tree node from K&R2 page 140. Words are initially read into - * the tree by getword. - */ -struct tnode { +struct tnode{ char *word; - int count; - struct linenumber *linenumbers; + unsigned int count; + struct ocurLine *lineOfOccurence; + struct tnode *left; struct tnode *right; }; -struct linenumber { - int *number; - struct linenumber *nextnumber; -}; - -/* - * simroot: Part of a linked list of pointers to simword lists with - * a common root. - */ -struct simroot { - struct simword *firstword; /* points to the list of words */ - struct simroot *nextroot; /* points to the next node in the list */ -}; -/* - * simword: Part of a linked list of words with a common root. Points - * to the word in the tnodes. - */ -struct simword { - char *word; /* points to the word in the tree */ - int count; /* copied from the tree */ - int linenumber; /* copied from the tree */ - struct simword *nextword; /* next node */ +struct ocurLine{ + unsigned int line; + struct ocurLine *next; }; -struct tnode *addtree(struct tnode *, char *, int); -void treeprint(const struct tnode *); -int mgetword(char *, int, int *); -struct linenumber *lnumberalloc(void); -struct linenumber *addlinenumber(struct linenumber *, int); +int binarySearch(const char *arr[], int l, int r, char *x); -int main(int argc, char *argv[]) { - struct tnode *root; - char word[MAXWORD]; - int len; - int lineno = 0; +void treeprint(const struct tnode *p); +char *mstrdup(char *s); - /* get all the words */ - root = NULL; - while (mgetword(word, MAXWORD, &lineno) != 'x') - if (isalpha(word[0])) - root = addtree(root, word, lineno); - - if (argc == 1) - len = DEFAULT_COMP_LEN; - else if (argc == 2) - len = atoi(argv[1]); - else { - printf("Incorrect number of arguments.\n"); - return 1; - } +int getWord(char *word, int lim); - printf("Words with line numbers\n"); +void ungetch(char c); +int getch(void); - treeprint(root); /* prints all the words */ - - return 0; -} /* end of main() */ +char buf; /* buffer for getch/ungetch */ struct tnode *talloc(void); -char *mstrdup(char *); +struct tnode *addtree(struct tnode *p, char *w, unsigned int l); -/* mgetword from Ex6.1 */ +void printline(const struct ocurLine *p); -#define IN 1 -#define OUT 0 +struct ocurLine *linealloc(void); +struct ocurLine *addLine(struct ocurLine *p, unsigned int l); -int mgetword(char *word, int lim, int *lineno_addr) { - int c, d, getch(void), comment, string, directive; - void ungetch(int); - char *w = word; +int main() +{ + int l=1; + struct tnode *root; + char word[MAXWORD]; - comment = string = directive = OUT; + root = NULL; - while (isspace(c = getch())) { - if (c == '\n') { + while(getWord(word, MAXWORD) != EOF) + if (word[0] == '\n') // Adding 1 to [l] if there is new line + l++; + else if(isalpha(word[0])) + if (binarySearch(noiseWords, 0, N_OF_NOISEWORDS, word) == -1) + root = addtree(root, word, l); + treeprint(root); +} - *lineno_addr = *lineno_addr + 1; - } - } - /* Check if inside a comment */ +/* Binary search for our array of noise words. */ +int binarySearch(const char *arr[], int l, int r, char *x) +{ + if (r >= l) { + int mid = l + (r - l) / 2; + int cmp = strcmp(arr[mid], x); - if (c == '/') { - if ((d = getch()) == '*') { - comment = IN; - } else { - comment = OUT; - ungetch(d); - } - } + if (cmp == 0) + return mid; - /* Check if inside a quote */ + if (cmp > 0) + return binarySearch(arr, l, mid - 1, x); - if (c == '\"') { - string = IN; + return binarySearch(arr, mid + 1, r, x); } - /* Check if inside a directive */ + return -1; +} - if (c == '#') { - directive = IN; - } - if (c == '\\') { - c = getch(); /* ignore the \\ character */ - } +int getWord(char *word, int lim) +{ + int c; - if (comment == OUT && string == OUT && directive == OUT) { - - if (c != EOF) - *w++ = c; + char *w = word; - if (!isalnum(c) && c != '_') { - *w = '\0'; - return c; - } + while (isspace(c = getch()) && c != '\n') + ; - for (; --lim > 0; w++) { - *w = getch(); - if (!isalnum(*w) && *w != '_') { - ungetch(*w); - break; - } - } - *w = '\0'; - return word[0]; - } else if (comment == IN) { + if (c != EOF) *w++ = c; - *w++ = d; - - while ((*w++ = c = getch())) { - if (c == '*') { - if ((c = getch()) == '/') { - *w++ = c; - comment = OUT; - break; - } else { - ungetch(c); - } - } - } - *w = '\0'; - } else if (string == IN) { - *w++ = c; - while ((*w++ = getch()) != '\"') { - if (*w == '\\') /* Take care of escaped quotes */ - *w++ = getch(); - } - string = OUT; - *w = '\0'; - } else if (directive == IN) { - *w++ = c; - while ((*w++ = getch()) != '\n') { - if (c == '\\') { /* Take care of continuation line escape */ - *w++ = getch(); - } - } - directive = OUT; + if (!isalpha(c) && c != '_' && c != '#') { *w = '\0'; + return c; } - return c; -} + for ( ; --lim > 0; w++) + if (!isalnum(*w = getch())){ + ungetch(*w); + break; + } -/*************************************************************************** - * All code below here is from K&R2. * - ***************************************************************************/ + *w = '\0'; + return word[0]; +} -/* - * addtree: From K&R2 page 141. - * Adds a node containing w, at or below node p. - */ -struct tnode *addtree(struct tnode *p, char *w, int linenumber) { +/* addtree: adds branch to a tree*/ +struct tnode *addtree(struct tnode *p, char *w, unsigned int l) +{ int cond; - if (p == NULL) { /* new word */ + if(p == NULL) { /* new word */ p = talloc(); - p->word = mstrdup(w); + p->word=mstrdup(w); p->count = 1; - p->linenumbers = NULL; - p->linenumbers = addlinenumber(p->linenumbers, linenumber); + p->lineOfOccurence = NULL; + p->lineOfOccurence = addLine(p->lineOfOccurence, l); p->left = p->right = NULL; - } else if ((cond = strcmp(w, p->word)) == 0) { + } + else if((cond = strcmp(w, p->word)) == 0){ p->count++; - p->linenumbers = addlinenumber(p->linenumbers, linenumber); - } else if (cond < 0) - p->left = addtree(p->left, w, linenumber); + p->lineOfOccurence = addLine(p->lineOfOccurence, l); + } + else if(cond < 0) + p->left = addtree(p->left, w, l); else - p->right = addtree(p->right, w, linenumber); + p->right = addtree(p->right, w, l); return p; } -struct linenumber *addlinenumber(struct linenumber *p, int linenumber) { - if (p == NULL) { - p = lnumberalloc(); - p->number = linenumber; - p->nextnumber = NULL; - } else { - p->nextnumber = addlinenumber(p->nextnumber, linenumber); - } +/* treeprint: prints all the branches of the tree with words.*/ +void treeprint(const struct tnode *p) +{ - return p; + if(p != NULL) { + treeprint(p->left); + + printf("%s: [", p->word); + + printline(p->lineOfOccurence); + + printf("]\n"); + + treeprint(p->right); + } } -struct linenumber *lnumberalloc(void) { - return (struct linenumber *)malloc(sizeof(struct linenumber)); +/* talloc: From K&R2 page 142. Makes a tnode. */ +struct tnode *talloc(void) +{ + return (struct tnode *) malloc(sizeof(struct tnode)); } -/* treeprint: From K&R2 page 142. Prints tree p in-order. */ -void treeprint(const struct tnode *p) { - if (p != NULL) { - treeprint(p->left); - printf("\n%s :", p->word); - printnumbers(p->linenumbers); - treeprint(p->right); + +/* printline: Prints all lines.*/ +void printline(const struct ocurLine *p) +{ + if (p->next == NULL) + printf("%i", p->line); + else{ + printf("%i, ", p->line); + printline(p->next); } } -void printnumbers(const struct linenumber *p) { - if (p != NULL) { - printf("%d,", p->number); - printnumbers(p->nextnumber); +/* addLine: adds a line to word. */ +struct ocurLine *addLine(struct ocurLine *p, unsigned int l) +{ + if (p == NULL){ + p = linealloc(); + p->line = l; + p->next = NULL; } + else + p->next = addLine(p->next, l); + return p; } -/* talloc: From K&R2 page 142. Makes a tnode. */ -struct tnode *talloc(void) { - return (struct tnode *)malloc(sizeof(struct tnode)); +/* linealloc: Makes ocurLine*/ +struct ocurLine *linealloc(void) +{ + return (struct ocurLine *) malloc(sizeof(struct ocurLine)); } /* strdup: From K&R2 page 143. Makes a duplicate of s. */ -char *mstrdup(char *s) { +char *mstrdup(char *s) +{ char *p; - p = (char *)malloc(strlen(s) + 1); - if (p != NULL) + + p = (char *) malloc(strlen(s) + 1); + + if(p != NULL) strcpy(p, s); return p; } -/* - * getch and ungetch are from K&R2, page 79 - */ -#define BUFSIZE 100 - -char buf[BUFSIZE]; /* buffer for ungetch() */ -int bufp = 0; /* next free position in buf */ - -int getch(void) { /* get a (possibly pushed back) character */ - return (bufp > 0) ? buf[--bufp] : getchar(); +/************************************************************* + * Getch/Ungetch functions from previous exercises * + *************************************************************/ + +/* getch: gets a (possibly pushed-back) character */ +int getch(void) +{ + if (buf > 0){ + int copy=buf; + buf=0; + return copy; + } + else + return getchar(); } -void ungetch(int c) { /* push character back on input */ - if (bufp >= BUFSIZE) - printf("ungetch: too many characters\n"); - else - buf[bufp++] = c; - return; +/* ungetch: pushes character back on input */ +void ungetch(char c) +{ + buf = c; } \ No newline at end of file diff --git a/source/cprogramming/chapter6/cprogs/ex_6.4.c b/source/cprogramming/chapter6/cprogs/ex_6.4.c index e0cb8fda..af21156b 100644 --- a/source/cprogramming/chapter6/cprogs/ex_6.4.c +++ b/source/cprogramming/chapter6/cprogs/ex_6.4.c @@ -10,7 +10,6 @@ */ #include -#include #include #include #include @@ -37,24 +36,29 @@ struct words { }; struct tnode *addtree(struct tnode *p, char *w); + struct bynumbernode *addnumtree(struct bynumbernode *, int, char *); + struct words *addwordtolist(struct words *, char *); + void printwords(const struct words *, const int); struct bynumbernode *traverse(const struct tnode *, struct bynumbernode *); + void treeprint(const struct bynumbernode *); + int mgetword(char *, int); struct tnode *talloc(void) { - return (struct tnode *)malloc(sizeof(struct tnode)); + return (struct tnode *) malloc(sizeof(struct tnode)); }; struct bynumbernode *bynumbernodealloc(void) { - return (struct bynumbernode *)malloc(sizeof(struct bynumbernode)); + return (struct bynumbernode *) malloc(sizeof(struct bynumbernode)); }; struct words *wordsalloc(void) { - return (struct words *)malloc(sizeof(struct words)); + return (struct words *) malloc(sizeof(struct words)); }; #define BUFSIZE 100 @@ -63,6 +67,7 @@ char buf[BUFSIZE]; int bufp = 0; int getch(void) { return (bufp > 0) ? buf[--bufp] : getchar(); } + void ungetch(int c) { if (bufp >= BUFSIZE) { printf("ungetch: too many characters\n"); @@ -73,7 +78,7 @@ void ungetch(int c) { char *mstrdup(char *s) { char *p; - p = (char *)malloc(strlen(s) + 1); + p = (char *) malloc(strlen(s) + 1); if (p != NULL) { strcpy(p, s); } @@ -86,8 +91,7 @@ int getword(char *word, int lim) { char *w = word; while (isspace(c = getch()) || c == '_' || c == '/' || c == '#' || - c == '*' || c == '"') - ; + c == '*' || c == '"'); if (c != EOF) { *w++ = c; @@ -105,6 +109,7 @@ int getword(char *word, int lim) { *w = '\0'; return word[0]; } + /* addtree : add a node with w at or below p */ struct tnode *addtree(struct tnode *p, char *w) { int cond; @@ -123,6 +128,7 @@ struct tnode *addtree(struct tnode *p, char *w) { } return p; } + // treeprint: in-order print of tree p void treeprint(const struct bynumbernode *p) { if (p != NULL) { diff --git a/source/cprogramming/chapter6/cprogs/ex_6.5.c b/source/cprogramming/chapter6/cprogs/ex_6.5.c index 231545d0..7dc6eec4 100644 --- a/source/cprogramming/chapter6/cprogs/ex_6.5.c +++ b/source/cprogramming/chapter6/cprogs/ex_6.5.c @@ -4,23 +4,19 @@ #include #include +#include -/*undef will be if it is just hashtable. Remove it. - * If it is in linked list, delete from linked list. - */ +#define HASHSIZE 101 -/* nlist from K&R Page 144 */ +static struct nlist *hashtab[HASHSIZE]; /* pointer table */ +/* linked List of words. nlist from K&R Page 144 */ struct nlist { /* table entry: */ struct nlist *next; /* next entry in chain */ char *name; /* defined name */ char *defn; /* replacement text */ }; -#define HASHSIZE 101 - -static struct nlist *hashtab[HASHSIZE]; /* pointer table */ - /* hash: form hash value for string s */ unsigned hash(char *s) { unsigned hashval; @@ -32,7 +28,6 @@ unsigned hash(char *s) { } /* lookup: look for s in hashtab */ - struct nlist *lookup(char *s) { struct nlist *np; @@ -42,16 +37,13 @@ struct nlist *lookup(char *s) { return NULL; /* not found */ } -struct nlist *lookup(char *); -char *strdup(char *); - /* install: put (name, defn) in hashtab */ struct nlist *install(char *name, char *defn) { struct nlist *np; unsigned hashval; if ((np = lookup(name)) == NULL) { /* not found */ - np = (struct nlist *)malloc(sizeof(*np)); + np = (struct nlist *) malloc(sizeof(*np)); if (np == NULL || (np->name = strdup(name)) == NULL) return NULL; @@ -59,7 +51,7 @@ struct nlist *install(char *name, char *defn) { np->next = hashtab[hashval]; hashtab[hashval] = np; } else /* already there */ - free((void *)np->defn); /* free the previous defn */ + free((void *) np->defn); /* free the previous defn */ if ((np->defn = strdup(defn)) == NULL) return NULL; @@ -67,6 +59,10 @@ struct nlist *install(char *name, char *defn) { return np; } +/** + * undef will be if it is just hashtable. Remove it. + * If it is in linked list, delete from linked list. + **/ struct nlist *undef(char *name) { struct nlist *found; @@ -80,7 +76,7 @@ struct nlist *undef(char *name) { found = found->next; } else { hashtab[hash(name)] = NULL; - free((void *)found); + free((void *) found); } } return found; @@ -88,8 +84,10 @@ struct nlist *undef(char *name) { int main(int argc, char *argv[]) { struct nlist *table[4] = { - (install("key", "value")), (install("key1", "value1")), - (install("key2", "value2")), (install("key3", "value3"))}; + (install("key", "value")), + (install("key1", "value1")), + (install("key2", "value2")), + (install("key3", "value3"))}; int i; diff --git a/source/cprogramming/chapter6/cprogs/ex_6.6.c b/source/cprogramming/chapter6/cprogs/ex_6.6.c index 5f32e687..a2296996 100644 --- a/source/cprogramming/chapter6/cprogs/ex_6.6.c +++ b/source/cprogramming/chapter6/cprogs/ex_6.6.c @@ -1,35 +1,39 @@ -/* Implement a simple version of the #define processor (i.e, no arguments) - * suitable for use with C programs, based on the routines of this section. - * You may also find getch and ungetch helpful. - */ - -/* - * Use getword for #define, key and value - * and use install routines to install it. - * - */ - #include -#include #include #include #include +#define BUFSIZE 100 #define MAXWORD 1000 +#define IN 1 +#define OUT 0 +#define HASHSIZE 101 -int mgetword(char *, int, int *); -/* nlist from K&R Page 144 */ +char buf[BUFSIZE]; /* buffer for ungetch() */ +int bufp = 0; /* next free position in buf */ +static struct nlist *hashtab[HASHSIZE]; /* pointer table */ + +/* linked list. nlist from K&R Page 144 */ struct nlist { /* table entry: */ struct nlist *next; /* next entry in chain */ char *name; /* defined name */ char *defn; /* replacement text */ }; -#define HASHSIZE 101 -static struct nlist *hashtab[HASHSIZE]; /* pointer table */ +int getch(void) { /* get a (possibly pushed back) character */ + return (bufp > 0) ? buf[--bufp] : getchar(); +} + +void ungetch(int c) { /* push character back on input */ + if (bufp >= BUFSIZE) + printf("ungetch: too many characters\n"); + else + buf[bufp++] = c; + return; +} /* hash: form hash value for string s */ unsigned hash(char *s) { @@ -42,7 +46,6 @@ unsigned hash(char *s) { } /* lookup: look for s in hashtab */ - struct nlist *lookup(char *s) { struct nlist *np; @@ -52,9 +55,6 @@ struct nlist *lookup(char *s) { return NULL; /* not found */ } -struct nlist *lookup(char *); -// char *strdup(char *); - /* install: put (name, defn) in hashtab */ struct nlist *install(char *name, char *defn) { struct nlist *np; @@ -96,35 +96,6 @@ struct nlist *undef(char *name) { return found; } -int main(void) { - - int lineno = 0; - char word[MAXWORD]; - - char key[MAXWORD], value[MAXWORD]; - - struct nlist *result; - - while (mgetword(word, MAXWORD, &lineno) != 'x') { - /* TODO: Strip the spaces */ - if (strcmp(word, "#define ") == 0) { - mgetword(key, MAXWORD, &lineno); - mgetword(value, MAXWORD, &lineno); - install(key, value); - result = lookup(key); - printf("%s->%s", result->name, result->defn); - } - } - - return 0; -} - -; - /* mgetword from Ex6.1 */ - -#define IN 1 -#define OUT 0 - int mgetword(char *word, int lim, int *lineno_addr) { int c, d, getch(void), comment, string, directive; void ungetch(int); @@ -138,9 +109,7 @@ int mgetword(char *word, int lim, int *lineno_addr) { *lineno_addr = *lineno_addr + 1; } } - /* Check if inside a comment */ - if (c == '/') { if ((d = getch()) == '*') { comment = IN; @@ -151,13 +120,11 @@ int mgetword(char *word, int lim, int *lineno_addr) { } /* Check if inside a quote */ - if (c == '\"') { string = IN; } /* Check if inside a directive */ - if (c == '#') { directive = IN; } @@ -225,22 +192,24 @@ int mgetword(char *word, int lim, int *lineno_addr) { return c; } -/* - * getch and ungetch are from K&R2, page 79 - */ -#define BUFSIZE 100 +int main(void) { -char buf[BUFSIZE]; /* buffer for ungetch() */ -int bufp = 0; /* next free position in buf */ + int lineno = 0; + char word[MAXWORD]; -int getch(void) { /* get a (possibly pushed back) character */ - return (bufp > 0) ? buf[--bufp] : getchar(); -} + char key[MAXWORD], value[MAXWORD]; -void ungetch(int c) { /* push character back on input */ - if (bufp >= BUFSIZE) - printf("ungetch: too many characters\n"); - else - buf[bufp++] = c; - return; -} + struct nlist *result; + + while (mgetword(word, MAXWORD, &lineno) != 'x') { + if (strcmp(word, "#define ") == 0) { + mgetword(key, MAXWORD, &lineno); + mgetword(value, MAXWORD, &lineno); + install(key, value); + result = lookup(key); + printf("%s->%s", result->name, result->defn); + } + } + + return 0; +} \ No newline at end of file diff --git a/source/cprogramming/chapter6/cprogs/sec_6.3_getword.c b/source/cprogramming/chapter6/cprogs/sec_6.3_getword.c index b2190543..f601a78d 100644 --- a/source/cprogramming/chapter6/cprogs/sec_6.3_getword.c +++ b/source/cprogramming/chapter6/cprogs/sec_6.3_getword.c @@ -2,35 +2,48 @@ #include #include +#define BUFSIZE 100 #define MAXWORD 100 +#define NKEYS (sizeof keytab / sizeof(struct key)) +char buf[BUFSIZE]; /* buffer for ungetch */ +int bufp = 0; /* next free position in buf */ + +/* Figure out why printf is a special case */ struct key { char *word; int count; } keytab[] = { - "auto", 0, "break", 0, "case", 0, "char", 0, "const", 0, - "continue", 0, "default", 0, "unsigned", 0, "void", 0, "volatile", 0, - "while", 0, "printf", 0, /* Figure out why printf is a special case */ + "auto", 0, + "break", 0, + "case", 0, + "char", 0, + "const", 0, + "continue", 0, + "default", 0, + "unsigned", 0, + "void", 0, + "volatile", 0, + "while", 0, + "printf", 0, }; -#define NKEYS (sizeof keytab / sizeof(struct key)) - -int mgetword(char *, int); int binsearch(char *, struct key *, int); +int getch(void); +int mgetword(char *, int); +void ungetch(int c); -/* count C keywords */ -int main(int argc, char *argv[]) { - int n; - char word[MAXWORD]; +int getch(void) /* get a (possibly pushed back) character */ +{ + return (bufp > 0) ? buf[--bufp] : getchar(); +} - while (mgetword(word, MAXWORD) != EOF) - if (isalpha(word[0])) - if ((n = binsearch(word, keytab, NKEYS)) >= 0) - keytab[n].count++; - for (n = 0; n < NKEYS; n++) - if (keytab[n].count > 0) - printf("%4d %s\n", keytab[n].count, keytab[n].word); - return 0; +void ungetch(int c) /* push a character back on input */ +{ + if (bufp >= BUFSIZE) + printf("ungetch: too many characters \n"); + else + buf[bufp++] = c; } /* binsearch: find word in tab[0]...tab[n-1] */ @@ -53,11 +66,9 @@ int binsearch(char *word, struct key tab[], int n) { /* getword: get next word or character from input */ int mgetword(char *word, int lim) { - int c, getch(void); - void ungetch(int); + int c; char *w = word; - while (isspace(c = getch())) - ; + while (isspace(c = getch())); if (c != EOF) *w++ = c; if (!isalpha(c)) { @@ -73,20 +84,17 @@ int mgetword(char *word, int lim) { return word[0]; } -#define BUFSIZE 100 - -char buf[BUFSIZE]; /* buffer for ungetch */ -int bufp = 0; /* next free position in buf */ - -int getch(void) /* get a (possibly pushed back) character */ -{ - return (bufp > 0) ? buf[--bufp] : getchar(); -} +/* count C keywords */ +int main(int argc, char *argv[]) { + int n; + char word[MAXWORD]; -void ungetch(int c) /* push a character back on input */ -{ - if (bufp >= BUFSIZE) - printf("ungetch: too many characters \n"); - else - buf[bufp++] = c; -} + while (mgetword(word, MAXWORD) != EOF) + if (isalpha(word[0])) + if ((n = binsearch(word, keytab, NKEYS)) >= 0) + keytab[n].count++; + for (n = 0; n < NKEYS; n++) + if (keytab[n].count > 0) + printf("%4d %s\n", keytab[n].count, keytab[n].word); + return 0; +} \ No newline at end of file diff --git a/source/cprogramming/chapter6/ex_6.1_getword.rst b/source/cprogramming/chapter6/ex_6.1_getword.rst index 68e16335..66111e33 100644 --- a/source/cprogramming/chapter6/ex_6.1_getword.rst +++ b/source/cprogramming/chapter6/ex_6.1_getword.rst @@ -8,20 +8,25 @@ Question Our version of getword does not properly handle underscores, string constants, comments, or preprocessor control lines. Write a better version. -.. literalinclude:: ../../languages/cprogs/Ex_6.1_getword.c +.. literalinclude:: cprogs/ex_6.1_getword.c :language: c :tab-width: 4 -.. runcode:: ../../languages/cprogs/Ex_6.1_getword.c +This is program from Section 6.3 implementing getword. + +.. literalinclude:: cprogs/sec_6.3_getword.c :language: c - :codesite: ideone + :tab-width: 4 Explanation =========== +This program identifies the keywords in the given input. + +:: + $ ./ex_6.1_getword + this is a short sentence. + 1 short -.. seealso:: - * :c-suggest-improve:`Ex_6.1_getword.c` - * :c-better-explain:`Ex_6.1_getword.rst` diff --git a/source/cprogramming/chapter6/ex_6.2_identical_variables.rst b/source/cprogramming/chapter6/ex_6.2_identical_variables.rst index 4c141d39..6f9dd1cc 100644 --- a/source/cprogramming/chapter6/ex_6.2_identical_variables.rst +++ b/source/cprogramming/chapter6/ex_6.2_identical_variables.rst @@ -11,20 +11,15 @@ group of variable names that are identical in the first 6 characters, but different somewhere thereafter. Don't count words within strings and comments. Make 6 a parameter that can be set from the command line. -.. literalinclude:: ../../languages/cprogs/Ex_6.2_identical_variables.c +.. literalinclude:: cprogs/ex_6.2_identical_variables.c :language: c :tab-width: 4 -.. runcode:: ../../languages/cprogs/Ex_6.2_identical_variables.c - :language: c - :codesite: ideone - Explanation =========== +This program reads a C program and groups similar list of variable names as similar words list. +It parses the C program and stores the variables names in a binary tree, then constructs a similar word list which have +a common prefix length. -.. seealso:: - - * :c-suggest-improve:`Ex_6.2_identical_variables.c` - * :c-better-explain:`Ex_6.2_identical_variables.rst` diff --git a/source/cprogramming/chapter6/ex_6.3.rst b/source/cprogramming/chapter6/ex_6.3.rst index bf31e59a..b8aa9bec 100644 --- a/source/cprogramming/chapter6/ex_6.3.rst +++ b/source/cprogramming/chapter6/ex_6.3.rst @@ -9,53 +9,44 @@ Write a cross-referencer that prints a list of all words in a document, and for each word, a list of the line numbers on which it occurs. Remove noise words like ``the, and`` and so on. -.. literalinclude:: ../../languages/cprogs/Ex_6.3.c +.. literalinclude:: cprogs/ex_6.3.c :language: c :tab-width: 4 -.. runcode:: ../../languages/cprogs/Ex_6.3.c - :language: c - :codesite: ideone - Explanation =========== +This program is a cross-referencer that prints a list of all words in a document. + +1. Create a binary tree that will contain words and structure with lines on which words occur. +2. Check if the word is noisy with binary search. +3. Print the words and lines. + + + Here is an example execution of this program. :: - This is a - cross reference - word - document - creator - lists words and their line numbers. - Gets the word and puts their line numbers. - x - - Words with line numbers - - Gets :6, - This :0, - a :0, - and :5,6, - creator :4, - cross :1, - document :3, - is :0, - line :5,6, - lists :5, - numbers :5,6, - puts :6, - reference :1, - the :6, - their :5,6, - word :2,6, - words :5, - - - -.. seealso:: - - * :c-suggest-improve:`Ex_6.3.c` - * :c-better-explain:`Ex_6.3.rst` + [ec2-user@ip-172-32-32-162 learntosolveit]$ ./ex_6.3 + This is a + cross reference + word + document + creator + lists words and their line numbers. + Gets the word and puts their line numbers. + + Gets: [7] + This: [1] + and: [6, 7] + creator: [5] + cross: [2] + document: [4] + line: [6, 7] + lists: [6] + numbers: [6, 7] + puts: [7] + reference: [2] + word: [3, 7] + words: [6] diff --git a/source/cprogramming/chapter6/ex_6.4.rst b/source/cprogramming/chapter6/ex_6.4.rst index b71e878f..1f47fd45 100644 --- a/source/cprogramming/chapter6/ex_6.4.rst +++ b/source/cprogramming/chapter6/ex_6.4.rst @@ -8,17 +8,19 @@ Question Write a program that prints the distinct words in its input sorted into decreasing order of frequency of occurrence. Precede each word by its count. -.. literalinclude:: ../../languages/cprogs/Ex_6.4.c +.. literalinclude:: cprogs/ex_6.4.c :language: c :tab-width: 4 -.. runcode:: ../../languages/cprogs/Ex_6.4.c - :language: c - :codesite: ideone - Explanation =========== +This program prints the distinct words in its input sorted into decreasing order of frequency of occurrence. Each word +is preceded by its count. + +This works by creating a Tree with word and count, just like tnode. +Parse the tree and create a new tree with count and list of words in the node. Print the new tree in-order traversal. + :: ab @@ -38,7 +40,4 @@ Explanation -.. seealso:: - * :c-suggest-improve:`Ex_6.4.c` - * :c-better-explain:`Ex_6.4.rst` diff --git a/source/cprogramming/chapter6/ex_6.5.rst b/source/cprogramming/chapter6/ex_6.5.rst index 43cc6ab9..1075d8e1 100644 --- a/source/cprogramming/chapter6/ex_6.5.rst +++ b/source/cprogramming/chapter6/ex_6.5.rst @@ -8,17 +8,25 @@ Question Write a function undef that will remove a name and definition from the table maintained by lookup and install. -.. literalinclude:: ../../languages/cprogs/Ex_6.5.c +.. literalinclude:: cprogs/ex_6.5.c :language: c :tab-width: 4 -.. runcode:: ../../languages/cprogs/Ex_6.5.c - :language: c - :codesite: ideone - Explanation =========== +This program demonstrates implementing a hash table for inserting key -> value. +When there is a collision to inserting values against a key, it will create a linked list of values. + +So, it implements + +* install - installs the word in the hash table. Creates a linked list for the new value. +* lookup - looks up the word in the hash table. +* undef - removes the word in the hash table. + +For each of these operations, it takes word, calculates the hash value. +If there is a collision, it will add the word to the linked list in the hashtable key. + Sample run of this program. :: @@ -33,7 +41,4 @@ Sample run of this program. -.. seealso:: - * :c-suggest-improve:`Ex_6.5.c` - * :c-better-explain:`Ex_6.5.rst` diff --git a/source/cprogramming/chapter6/ex_6.6.rst b/source/cprogramming/chapter6/ex_6.6.rst index 30da0777..57bd0970 100644 --- a/source/cprogramming/chapter6/ex_6.6.rst +++ b/source/cprogramming/chapter6/ex_6.6.rst @@ -9,17 +9,18 @@ Implement a simple version of the #define processor (i.e., no arguments) suitable for use with C programs, based on the routines of this section. You may also find getch and ungetch helpful. -.. literalinclude:: ../../languages/cprogs/Ex_6.6.c +.. literalinclude:: cprogs/ex_6.6.c :language: c :tab-width: 4 -.. runcode:: ../../languages/cprogs/Ex_6.6.c - :language: c - :codesite: ideone - Explanation =========== +This implements a simple version of `#define` pre-processor used in C programs. +In the program program it identifies `#define key value` in the given text, and then using the previously taught +concepts of install, lookup and undef to create a hash table, to keep track of the identified key value pairs in +a hash table. + Example output. :: @@ -29,7 +30,4 @@ Example output. -.. seealso:: - * :c-suggest-improve:`Ex_6.6.c` - * :c-better-explain:`Ex_6.6.rst` diff --git a/source/cprogramming/chapter6/index.rst b/source/cprogramming/chapter6/index.rst new file mode 100644 index 00000000..5231170b --- /dev/null +++ b/source/cprogramming/chapter6/index.rst @@ -0,0 +1,14 @@ +========= +Chapter 6 +========= + +.. toctree:: + :maxdepth: 1 + + + ex_6.1_getword + ex_6.2_identical_variables + ex_6.3 + ex_6.4 + ex_6.5 + ex_6.6 diff --git a/source/cprogramming/chapter7/cprogs/Ex_7.1_lower-upper.c b/source/cprogramming/chapter7/cprogs/ex_7.1_lower-upper.c similarity index 63% rename from source/cprogramming/chapter7/cprogs/Ex_7.1_lower-upper.c rename to source/cprogramming/chapter7/cprogs/ex_7.1_lower-upper.c index cec9d0ff..847780de 100644 --- a/source/cprogramming/chapter7/cprogs/Ex_7.1_lower-upper.c +++ b/source/cprogramming/chapter7/cprogs/ex_7.1_lower-upper.c @@ -8,14 +8,27 @@ upper case depending on the name it is involved with as found in argv[0] */ /* lower: converts upper case to lower case */ /* upper: converts lower case to upper case */ +const char *input = "This\tis\ta\ttest"; +int input_index = 0; + +int _getchar(void) { + if (input[input_index] == '\0') { + return EOF; + } else { + return input[input_index++]; + } +} + + + int main(int argc, char *argv[]) { int c; if (strcmp(argv[0], "./lower") == 0) - while ((c = getchar()) != EOF) + while ((c = _getchar()) != EOF) putchar(tolower(c)); else - while ((c = getchar()) != EOF) + while ((c = _getchar()) != EOF) putchar(toupper(c)); return 0; diff --git a/source/cprogramming/chapter7/cprogs/Ex_7.2_nongraphic.c b/source/cprogramming/chapter7/cprogs/ex_7.2_nongraphic.c similarity index 64% rename from source/cprogramming/chapter7/cprogs/Ex_7.2_nongraphic.c rename to source/cprogramming/chapter7/cprogs/ex_7.2_nongraphic.c index dfa4d2ce..b81c952f 100644 --- a/source/cprogramming/chapter7/cprogs/Ex_7.2_nongraphic.c +++ b/source/cprogramming/chapter7/cprogs/ex_7.2_nongraphic.c @@ -1,6 +1,8 @@ -/* Write a Program that will print arbitrary input in a sensible way.As a -/* minimum,it should prrint non-graphic character in octal or hexadecimal -/* according to the local customer and break long text lines */ +/** + * Write a program that will print arbitrary input in a sensible way. As a + * minimum, it should print non-graphic characters in octal or hexadecimal + * according to local custom, and break long text lines. + */ #include #include @@ -8,15 +10,35 @@ #define MAXLINE 100 /* maximum number of chars in one line */ #define OCTLEN 6 /* length of an octal value */ -/* print arbitrary input in a sensible way */ +const char *input = "This\tis\ta\ttest. With a very long line."; +int input_index = 0; + +int _getchar(void) { + if (input[input_index] == '\0') { + return EOF; + } else { + return input[input_index++]; + } +} + +/* inc : increment position counter for output */ +int inc(int pos, int n) { + if (pos + n < MAXLINE) + return pos + n; + else { + putchar('\n'); + return n; + } +} + +/* print arbitrary input in a sensible way */ int main(void) { int c, pos; - int inc(int pos, int n); pos = 0; /* position in the line */ - while ((c = getchar()) != EOF) + while ((c = _getchar()) != EOF) if (iscntrl(c) || c == ' ') { /* non-graphic or blank character */ pos = inc(pos, OCTLEN); @@ -31,14 +53,4 @@ int main(void) { putchar(c); } return 0; -} - -/* inc : increment position counter for output */ -int inc(int pos, int n) { - if (pos + n < MAXLINE) - return pos + n; - else { - putchar('\n'); - return n; - } -} +} \ No newline at end of file diff --git a/source/cprogramming/chapter7/cprogs/Ex_7.3_minprintf.c b/source/cprogramming/chapter7/cprogs/ex_7.3_minprintf.c similarity index 51% rename from source/cprogramming/chapter7/cprogs/Ex_7.3_minprintf.c rename to source/cprogramming/chapter7/cprogs/ex_7.3_minprintf.c index 9e0d2587..784f1f8e 100644 --- a/source/cprogramming/chapter7/cprogs/Ex_7.3_minprintf.c +++ b/source/cprogramming/chapter7/cprogs/ex_7.3_minprintf.c @@ -1,5 +1,7 @@ /* minprintf: minimalistic printf function */ #include +#include + void minprintf(char *fmt, ...); int main(void) { @@ -29,29 +31,29 @@ void minprintf(char *fmt, ...) { } switch (*++p) { - case 'd': - ival = va_arg(ap, int); - printf("%d", ival); - break; - case 'f': - dval = va_arg(ap, double); - printf("%f", dval); - break; - case 's': - for (sval = va_arg(ap, char *); *sval; sval++) - putchar(*sval); - break; - case 'o': - ival = va_arg(ap, int); - printf("%o", ival); - break; - case 'x': - ival = va_arg(ap, int); - printf("%x", ival); - break; - default: - putchar(*p); - break; + case 'd': + ival = va_arg(ap, int); + printf("%d", ival); + break; + case 'f': + dval = va_arg(ap, double); + printf("%f", dval); + break; + case 's': + for (sval = va_arg(ap, char *); *sval; sval++) + putchar(*sval); + break; + case 'o': + ival = va_arg(ap, int); + printf("%o", ival); + break; + case 'x': + ival = va_arg(ap, int); + printf("%x", ival); + break; + default: + putchar(*p); + break; } } va_end(ap); /* clean up when done */ diff --git a/source/cprogramming/chapter7/cprogs/Ex_7.4.c b/source/cprogramming/chapter7/cprogs/ex_7.4.c similarity index 50% rename from source/cprogramming/chapter7/cprogs/Ex_7.4.c rename to source/cprogramming/chapter7/cprogs/ex_7.4.c index c5684d46..c411de31 100644 --- a/source/cprogramming/chapter7/cprogs/Ex_7.4.c +++ b/source/cprogramming/chapter7/cprogs/ex_7.4.c @@ -1,6 +1,8 @@ /* minscanf: minimalistic scanf function */ #include +#include #include + void minscanf(char *fmt, ...); int main(void) { @@ -9,9 +11,10 @@ int main(void) { minscanf("%d", &i); printf("minscanf input: %d\n", i); - char *a; + char *a = malloc(100); // Allocate 100 bytes, enough for "test char" minscanf("%s", a); printf("minscanf input: %s\n", a); + free(a); // free the allocated memory float f; minscanf("%f", &f); @@ -41,33 +44,33 @@ void minscanf(char *fmt, ...) { } switch (*++p) { - case 'd': - ival = va_arg(ap, int *); - char *d = "44"; - sscanf(d, "%d", ival); - break; - case 'f': - dval = va_arg(ap, float *); - char *f = "5.33"; - sscanf(f, "%f", dval); - break; - case 's': - sval = va_arg(ap, char *); - sscanf("test char", "%s", sval); - break; - case 'o': - ival = va_arg(ap, int *); - char *o = "011"; - sscanf(o, "%o", ival); - break; - case 'x': - ival = va_arg(ap, int *); - char *x = "1a"; - sscanf(x, "%x", ival); - break; - default: - putchar(*p); - break; + case 'd': + ival = va_arg(ap, int *); + char *d = "44"; + sscanf(d, "%d", ival); + break; + case 'f': + dval = va_arg(ap, float *); + char *f = "5.33"; + sscanf(f, "%f", dval); + break; + case 's': + sval = va_arg(ap, char *); + sscanf("test char", "%s", sval); + break; + case 'o': + ival = va_arg(ap, int *); + char *o = "011"; + sscanf(o, "%o", ival); + break; + case 'x': + ival = va_arg(ap, int *); + char *x = "1a"; + sscanf(x, "%x", ival); + break; + default: + putchar(*p); + break; } } va_end(ap); /* clean up when done */ diff --git a/source/cprogramming/chapter7/cprogs/Ex_7.4v2.c b/source/cprogramming/chapter7/cprogs/ex_7.4v2.c similarity index 92% rename from source/cprogramming/chapter7/cprogs/Ex_7.4v2.c rename to source/cprogramming/chapter7/cprogs/ex_7.4v2.c index 34cd3237..ddeeb038 100644 --- a/source/cprogramming/chapter7/cprogs/Ex_7.4v2.c +++ b/source/cprogramming/chapter7/cprogs/ex_7.4v2.c @@ -1,6 +1,7 @@ #include #include #include + // compare two files, printing the first line where they differ int main(int argc, char *argv[]) { FILE *fp1, *fp2; @@ -28,9 +29,9 @@ void filecmp(FILE *f1, FILE *f2) { char *string1; while (!feof(f1) && !feof(f2)) { - string = (char *)malloc(size); + string = (char *) malloc(size); getline(&string, &size, f1); - string1 = (char *)malloc(size); + string1 = (char *) malloc(size); getline(&string1, &size, f2); if (strcmp(string, string1) != 0) { printf("%s", string); diff --git a/source/cprogramming/chapter7/cprogs/Ex_7.5.c b/source/cprogramming/chapter7/cprogs/ex_7.5.c similarity index 64% rename from source/cprogramming/chapter7/cprogs/Ex_7.5.c rename to source/cprogramming/chapter7/cprogs/ex_7.5.c index b550dbc5..b676809a 100644 --- a/source/cprogramming/chapter7/cprogs/Ex_7.5.c +++ b/source/cprogramming/chapter7/cprogs/ex_7.5.c @@ -4,44 +4,49 @@ */ #include #include /* for atof() */ + #define MAXOP 100 /* max size of operand or operator */ #define NUMBER '0' /* signal that a number was found */ + int getop(char[]); + void push(double); + double pop(void); + /* reverse Polish calculator */ -main() { +int main() { int type; double op2; char s[MAXOP]; while ((type = getop(s)) != EOF) { switch (type) { - case NUMBER: - push(atof(s)); - break; - case '+': - push(pop() + pop()); - break; - case '*': - push(pop() * pop()); - break; - case '-': - op2 = pop(); - push(pop() - op2); - break; - case '/': - op2 = pop(); - if (op2 != 0.0) - push(pop() / op2); - else - printf("error: zero divisor\n"); - break; - case '\n': - printf("\t%.8g\n", pop()); - break; - default: - printf("error: unknown command %s\n", s); - break; + case NUMBER: + push(atof(s)); + break; + case '+': + push(pop() + pop()); + break; + case '*': + push(pop() * pop()); + break; + case '-': + op2 = pop(); + push(pop() - op2); + break; + case '/': + op2 = pop(); + if (op2 != 0.0) + push(pop() / op2); + else + printf("error: zero divisor\n"); + break; + case '\n': + printf("\t%.8g\n", pop()); + break; + default: + printf("error: unknown command %s\n", s); + break; } } } @@ -70,13 +75,13 @@ double pop(void) { #include int getch(void); + void ungetch(int); int getop(char s[]) { int i, c; - while ((s[0] = c = getch()) == ' ' || c == '\t') - ; + while ((s[0] = c = getch()) == ' ' || c == '\t'); s[1] = '\0'; i = 0; @@ -93,12 +98,10 @@ int getop(char s[]) { } if (isdigit(c)) - while (isdigit(s[++i] = c = getch())) - ; + while (isdigit(s[++i] = c = getch())); if (c == '.') - while (isdigit(s[++i] = c = getch())) - ; + while (isdigit(s[++i] = c = getch())); s[i] = '\0'; if (c != EOF) diff --git a/source/cprogramming/chapter7/cprogs/Ex_7.6.c b/source/cprogramming/chapter7/cprogs/ex_7.6.c similarity index 100% rename from source/cprogramming/chapter7/cprogs/Ex_7.6.c rename to source/cprogramming/chapter7/cprogs/ex_7.6.c diff --git a/source/cprogramming/chapter7/cprogs/Ex_7.7.c b/source/cprogramming/chapter7/cprogs/ex_7.7.c similarity index 92% rename from source/cprogramming/chapter7/cprogs/Ex_7.7.c rename to source/cprogramming/chapter7/cprogs/ex_7.7.c index d63b01fe..ad5e58a5 100644 --- a/source/cprogramming/chapter7/cprogs/Ex_7.7.c +++ b/source/cprogramming/chapter7/cprogs/ex_7.7.c @@ -13,6 +13,8 @@ int mgetline(char *line, int max); +int strindex(char *s, char *t); + char pattern[] = "ould"; /* pattern to search for */ /* find all the matching patterns */ @@ -55,8 +57,7 @@ int strindex(char *s, char *t) { char *p, *r; for (; *s != '\0'; s++) { - for (p = s, r = t; *r != '\0' && *p == *r; p++, r++) - ; + for (p = s, r = t; *r != '\0' && *p == *r; p++, r++); if (r > t && *r == '\0') return s - b; diff --git a/source/cprogramming/chapter7/cprogs/Ex_7.8.c b/source/cprogramming/chapter7/cprogs/ex_7.8.c similarity index 100% rename from source/cprogramming/chapter7/cprogs/Ex_7.8.c rename to source/cprogramming/chapter7/cprogs/ex_7.8.c diff --git a/source/cprogramming/chapter7/cprogs/Ex_7.9.c b/source/cprogramming/chapter7/cprogs/ex_7.9.c similarity index 66% rename from source/cprogramming/chapter7/cprogs/Ex_7.9.c rename to source/cprogramming/chapter7/cprogs/ex_7.9.c index 0247d85d..acd7a805 100644 --- a/source/cprogramming/chapter7/cprogs/Ex_7.9.c +++ b/source/cprogramming/chapter7/cprogs/ex_7.9.c @@ -8,10 +8,22 @@ int myisupper(int); +const char *input = "AbCdEfx"; +int input_index = 0; + +int custom_getchar(void) { + if (input[input_index] == '\0') { + return EOF; + } else { + return input[input_index++]; + } +} + + int main(void) { int c; - while ((c = getchar()) != 'x') { + while ((c = custom_getchar()) != 'x') { if (c == '\n') continue; diff --git a/source/cprogramming/chapter7/ex_7.1_lower-upper.rst b/source/cprogramming/chapter7/ex_7.1_lower-upper.rst index e017181a..57861866 100644 --- a/source/cprogramming/chapter7/ex_7.1_lower-upper.rst +++ b/source/cprogramming/chapter7/ex_7.1_lower-upper.rst @@ -8,20 +8,28 @@ Question Write a program that converts upper case to lower or lower case to upper, depending on the name it is invoked with, as found in argv[0] -.. literalinclude:: ../../languages/cprogs/Ex_7.1_lower-upper.c +.. literalinclude:: cprogs/ex_7.1_lower-upper.c :language: c :tab-width: 4 -.. runcode:: ../../languages/cprogs/Ex_7.1_lower-upper.c - :language: c - :codesite: ideone - Explanation =========== +This program converts the input string to either lower case or upper case depending on the program. +This takes help of the various header files like. + +:: + + #include // Provides character handling functions like tolower() and toupper() + #include // Provides input/output functions like putchar() + #include // Provides string handling functions like strcmp() + + + +Visualize +========= +.. raw:: html -.. seealso:: + - * :c-suggest-improve:`Ex_7.1_lower-upper.c` - * :c-better-explain:`Ex_7.1_lower-upper.rst` diff --git a/source/cprogramming/chapter7/ex_7.2_nongraphic.rst b/source/cprogramming/chapter7/ex_7.2_nongraphic.rst index 6a0d50da..b05c5af4 100644 --- a/source/cprogramming/chapter7/ex_7.2_nongraphic.rst +++ b/source/cprogramming/chapter7/ex_7.2_nongraphic.rst @@ -9,20 +9,22 @@ Write a program that will print arbitrary input in a sensible way. As a minimum, it should print non-graphic characters in octal or hexadecimal according to local custom, and break long text lines. -.. literalinclude:: ../../languages/cprogs/Ex_7.2_nongraphic.c +.. literalinclude:: cprogs/ex_7.2_nongraphic.c :language: c :tab-width: 4 -.. runcode:: ../../languages/cprogs/Ex_7.2_nongraphic.c - :language: c - :codesite: ideone - Explanation =========== +We use the standard library function `iscntrl` declared in `ctype.h` to determine if a character is a control character. +We keep track of the position to print the output in the `inc` function and print the output in the `putchar` function. +If there is special character, we allocate 6 characters to it and print the character in octal along with the special +character. + +Visualize +========= -.. seealso:: +.. raw:: html - * :c-suggest-improve:`Ex_7.2_nongraphic.c` - * :c-better-explain:`Ex_7.2_nongraphic.rst` + diff --git a/source/cprogramming/chapter7/ex_7.3_minprintf.rst b/source/cprogramming/chapter7/ex_7.3_minprintf.rst index f2230fc8..7deafb80 100644 --- a/source/cprogramming/chapter7/ex_7.3_minprintf.rst +++ b/source/cprogramming/chapter7/ex_7.3_minprintf.rst @@ -7,20 +7,22 @@ Question Revise minprintf to handle more of the other facilities of printf. -.. literalinclude:: ../../languages/cprogs/Ex_7.3_minprintf.c +.. literalinclude:: cprogs/ex_7.3_minprintf.c :language: c :tab-width: 4 -.. runcode:: ../../languages/cprogs/Ex_7.3_minprintf.c - :language: c - :codesite: ideone - Explanation =========== +The header `#include ` provides functionality for functions with variable arguments (variadic functions) It defines va_list, va_start, va_arg, and va_end macros which are used to handle variable arguments. +Essential for implementing functions like scanf/printf that can take varying numbers of arguments + + +Visualize +========= + +.. raw:: html + -.. seealso:: - * :c-suggest-improve:`Ex_7.3_minprintf.c` - * :c-better-explain:`Ex_7.3_minprintf.rst` diff --git a/source/cprogramming/chapter7/ex_7.4.rst b/source/cprogramming/chapter7/ex_7.4.rst index c8447ba2..d65cdcd7 100644 --- a/source/cprogramming/chapter7/ex_7.4.rst +++ b/source/cprogramming/chapter7/ex_7.4.rst @@ -1,5 +1,5 @@ ======================================= -Exercise 7.4 - private version of scanf +Exercise 7.4 - private version of scanf ======================================= @@ -9,20 +9,48 @@ Question Write a private version of scanf analogous to minprintf from the previous section. -.. literalinclude:: ../../languages/cprogs/Ex_7.4.c +.. literalinclude:: cprogs/ex_7.4.c :language: c :tab-width: 4 -.. runcode:: ../../languages/cprogs/Ex_7.4.c - :language: c - :codesite: ideone - Explanation =========== +The Headers + +`#include ` + +This header provides functionality for functions with variable arguments (variadic functions) +It defines va_list, va_start, va_arg, and va_end macros which are used to handle variable arguments +Essential for implementing functions like scanf/printf that can take varying numbers of arguments + + +`#include ` + +This is the standard input/output header +Provides functions like printf, sscanf, putchar used in the program +Necessary for basic input/output operations + +This program implements a functionality similar to scanf, by taking a variable number of args and prints them to output. + +`#include ` for the malloc macro. + +The key components are + +:: + + va_list ap; // Declares a variable to hold the argument list + va_start(ap, fmt); // Initializes ap to point to first unnamed argument + va_arg(ap, type); // Returns next argument of specified type + va_end(ap); // Cleanup of argument list + + + +Visualize +========= + +.. raw:: html + -.. seealso:: - * :c-suggest-improve:`Ex_7.4.c` - * :c-better-explain:`Ex_7.4.rst` diff --git a/source/cprogramming/chapter7/ex_7.5.rst b/source/cprogramming/chapter7/ex_7.5.rst index 6145d545..fc6ba70e 100644 --- a/source/cprogramming/chapter7/ex_7.5.rst +++ b/source/cprogramming/chapter7/ex_7.5.rst @@ -8,20 +8,33 @@ Question Rewrite the postfix calculator of Chapter 4 to use scanf and/or sscanf to do the input and number conversion. -.. literalinclude:: ../../languages/cprogs/Ex_7.5.c +.. literalinclude:: cprogs/ex_7.5.c :language: c :tab-width: 4 -.. runcode:: ../../languages/cprogs/Ex_7.5.c - :language: c - :codesite: ideone - Explanation =========== +In this Reverse Polish Notation Calculator, we use scanf in the getch function. Instead of getchar this uses the function +scanf from the input output library introduced in this chapter. + + +:: + + #define BUFSIZE 100 + char buf[BUFSIZE]; + int bufp = 0; + + int getch(void) { + char c; + if (bufp > 0) { + return buf[--bufp]; + } else { + scanf("%c", &c); + return c; + } + } + -.. seealso:: - * :c-suggest-improve:`Ex_7.5.c` - * :c-better-explain:`Ex_7.5.rst` diff --git a/source/cprogramming/chapter7/ex_7.6.rst b/source/cprogramming/chapter7/ex_7.6.rst index 3a7d6f34..20ef0199 100644 --- a/source/cprogramming/chapter7/ex_7.6.rst +++ b/source/cprogramming/chapter7/ex_7.6.rst @@ -7,20 +7,23 @@ Question Write a program to compare two files, printing the first line where they differ. -.. literalinclude:: ../../languages/cprogs/Ex_7.6.c +.. literalinclude:: cprogs/ex_7.6.c :language: c :tab-width: 4 -.. runcode:: ../../languages/cprogs/Ex_7.6.c - :language: c - :codesite: ideone - Explanation =========== +This program reads two files using two file pointers, get one character at a time from each file and compares them, +and if they are not same, prints their differences. + +:: + + if (f1 != f2) { + putchar(f1); + putchar(f2); + break; + } -.. seealso:: - * :c-suggest-improve:`Ex_7.6.c` - * :c-better-explain:`Ex_7.6.rst` diff --git a/source/cprogramming/chapter7/ex_7.7.rst b/source/cprogramming/chapter7/ex_7.7.rst index b7e28eeb..1d97af41 100644 --- a/source/cprogramming/chapter7/ex_7.7.rst +++ b/source/cprogramming/chapter7/ex_7.7.rst @@ -9,20 +9,16 @@ Modify the pattern finding program of Chapter 5 to take its input from a set of named files or, if no files are named as arguments, from the standard input. Should the file name be printed when a matching line is found? -.. literalinclude:: ../../languages/cprogs/Ex_7.7.c +.. literalinclude:: cprogs/ex_7.7.c :language: c :tab-width: 4 -.. runcode:: ../../languages/cprogs/Ex_7.7.c - :language: c - :codesite: ideone - Explanation =========== +This program searches for a pattern `char pattern[] = "ould";`` in the given input line. +The idea of this program is to take the input from a file. + -.. seealso:: - * :c-suggest-improve:`Ex_7.7.c` - * :c-better-explain:`Ex_7.7.rst` diff --git a/source/cprogramming/chapter7/ex_7.8.rst b/source/cprogramming/chapter7/ex_7.8.rst index 0dc5915f..d32c2722 100644 --- a/source/cprogramming/chapter7/ex_7.8.rst +++ b/source/cprogramming/chapter7/ex_7.8.rst @@ -9,20 +9,63 @@ Write a program to print a set of files, starting each new one on a new page, with a title and a running page count for each file. -.. literalinclude:: ../../languages/cprogs/Ex_7.8.c +.. literalinclude:: cprogs/ex_7.8.c :language: c :tab-width: 4 -.. runcode:: ../../languages/cprogs/Ex_7.8.c - :language: c - :codesite: ideone - Explanation =========== +This takes a file as argument, and prints the file into number of pages, with Page # End as a de-mark at the end of the page. + +:: + + $ ./ex_7.8 README.md + + + File: README.md + + # https://learntosolveit.com + + [https://learntosolveit.com](https://learntosolveit.com) is a website to learn C programming using K&R book. It uses modern tools, and is designed to be used along with the book. + + To practice the exercises, you can use the online compilers like + + * [https://www.tutorialspoint.com/compile_c_online.php](https://www.tutorialspoint.com/compile_c_online.php) + * [https://replit.com/](https://replit.com/) + * [https://www.jdoodle.com/c-online-compiler](https://www.jdoodle.com/c-online-compiler) + * [https://www.onlinegdb.com/online_c_compiler](https://www.onlinegdb.com/online_c_compiler) + + Page 1 End. + + * [https://www.codechef.com/ide](https://www.codechef.com/ide) + * [https://www.programiz.com/c-programming/online-compiler/](https://www.programiz.com/c-programming/online-compiler/). + + I recommend [https://exercism.org](https://exercism.org) as the platform to + learn programming, including C, and practice with a community of intrinsically + motivated developers. + + ### Reference Books + + * C Programming Language by Kernighan and Ritchie. + + Page 2 End. + + + + [![Netlify Status](https://api.netlify.com/api/v1/badges/27a766e4-762c-420f-92e2-f35441c79f63/deploy-status)](https://app.netlify.com/sites/learntosolveit/deploys) + [![Documentation Status](https://readthedocs.org/projects/learntosolveit/badge/?version=latest)](http://www.learntosolveit.com/?badge=latest) + + + ## Author + + * Senthil Kumaran + * Email: [senthil@uthcode.com](mailto:senthil@uthcode.com) + + Page 3 End. + + * Blog: [https://senthil.learntosolveit.com](https://senthil.learntosolveit.com) + -.. seealso:: - * :c-suggest-improve:`Ex_7.8.c` - * :c-better-explain:`Ex_7.8.rst` diff --git a/source/cprogramming/chapter7/ex_7.9.rst b/source/cprogramming/chapter7/ex_7.9.rst index 519e095d..6f98e1b4 100644 --- a/source/cprogramming/chapter7/ex_7.9.rst +++ b/source/cprogramming/chapter7/ex_7.9.rst @@ -8,20 +8,31 @@ Question Functions like isupper can be implemented to save space or to save time. Explore both possibilities. -.. literalinclude:: ../../languages/cprogs/Ex_7.9.c +.. literalinclude:: cprogs/ex_7.9.c :language: c :tab-width: 4 -.. runcode:: ../../languages/cprogs/Ex_7.9.c - :language: c - :codesite: ideone Explanation =========== +This is custom implementation of isupper function instead of the standard library one. + +:: + + int myisupper(int c) { + if (c >= 'A' && c <= 'Z') + return 1; + else + return 0; + } + + +Visualize +========= + +.. raw:: html + -.. seealso:: - * :c-suggest-improve:`Ex_7.9.c` - * :c-better-explain:`Ex_7.9.rst` diff --git a/source/cprogramming/chapter7/index.rst b/source/cprogramming/chapter7/index.rst new file mode 100644 index 00000000..c8ba3e25 --- /dev/null +++ b/source/cprogramming/chapter7/index.rst @@ -0,0 +1,17 @@ +========= +Chapter 7 +========= + +.. toctree:: + :maxdepth: 1 + + + ex_7.1_lower-upper + ex_7.2_nongraphic + ex_7.3_minprintf + ex_7.4 + ex_7.5 + ex_7.6 + ex_7.7 + ex_7.8 + ex_7.9 diff --git a/source/cprogramming/chapter8/cprogs/Ex_8.5_fsize.c b/source/cprogramming/chapter8/cprogs/Ex_8.5_fsize.c deleted file mode 100644 index 007c0595..00000000 --- a/source/cprogramming/chapter8/cprogs/Ex_8.5_fsize.c +++ /dev/null @@ -1,160 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include - -#define NAME_MAX 14 - -typedef struct { - long ino; - char name[NAME_MAX + 1]; -} Dirent; - -typedef struct { - int fd; - Dirent d; -} MYDIR; - -MYDIR *myopendir(char *dirname); - -Dirent *myreaddir(MYDIR *dfd); - -void myclosedir(MYDIR *dfd); - -void fsize(char *); -void dirwalk(char *, void (*fcn)(char *)); - -/* stat from sys.stat.h has the following structure and these fields can be -accessed. - * -struct stat { - dev_t st_dev; [XSI] ID of device containing file - ino_t st_ino; [XSI] File serial number - mode_t st_mode; [XSI] Mode of file (see below) - nlink_t st_nlink; [XSI] Number of hard links - uid_t st_uid; [XSI] User ID of the file - gid_t st_gid; [XSI] Group ID of the file - dev_t st_rdev; [XSI] Device ID -#if !defined(_POSIX_C_SOURCE) || defined(_DARWIN_C_SOURCE) - struct timespec st_atimespec; time of last access - struct timespec st_mtimespec; time of last data modification - struct timespec st_ctimespec; time of last status change -#else - time_t st_atime; [XSI] Time of last access - long st_atimensec; nsec of last access - time_t st_mtime; [XSI] Last data modification time - long st_mtimensec; last data modification nsec - time_t st_ctime; [XSI] Time of last status change - long st_ctimensec; nsec of last status change -#endif - off_t st_size; [XSI] file size, in bytes - blkcnt_t st_blocks; [XSI] blocks allocated for file - blksize_t st_blksize; [XSI] optimal blocksize for I/O - __uint32_t st_flags; user defined flags for file - __uint32_t st_gen; file generation number - __int32_t st_lspare; RESERVED: DO NOT USE! - __int64_t st_qspare[2]; RESERVED: DO NOT USE! -}; -*/ - -/*fsize: print size of file "name" */ -void fsize(char *name) { - struct stat stbuf; - - if (stat(name, &stbuf) == -1) { - fprintf(stderr, "fsize: can't access %s\n", name); - return; - } - - if ((stbuf.st_mode & S_IFMT) == S_IFDIR) - dirwalk(name, fsize); - - printf("%8ld - %8ld - %8ld - %8ld - %8ld - %8ld %s\n", stbuf.st_size, - stbuf.st_blocks, stbuf.st_blksize, stbuf.st_flags, stbuf.st_gen, - stbuf.st_nlink, name); -} - -#define MAX_PATH 1024 - -void dirwalk(char *dir, void (*fcn)(char *)) { - char name[MAX_PATH]; - Dirent *dp; - MYDIR *dfd; - - if ((dfd = myopendir(dir)) == NULL) { - fprintf(stderr, "dirwalk: cant open %s\n", dir); - return; - } - - while ((dp = myreaddir(dfd)) != NULL) { - if (strcmp(dp->name, ".") == 0 || strcmp(dp->name, "..") == 0) - continue; - if (strlen(dir) + strlen(dp->name) + 2 > sizeof(name)) - fprintf(stderr, "dirwalk: name %s/%s too long\n", dir, dp->name); - else { - sprintf(name, "%s/%s", dir, dp->name); - (*fcn)(name); - } - } - myclosedir(dfd); -} - -#ifndef DIRSIZ -#define DIRSIZE 14 -#endif - -struct direct { /* directory entry */ - ino_t d_ino; - char d_name[DIRSIZE]; -}; - -MYDIR *myopendir(char *dirname) { - int fd; - struct stat stbuf; - MYDIR *dp; - - if ((fd = open(dirname, O_RDONLY, 0)) == -1 || fstat(fd, &stbuf) == -1 || - (stbuf.st_mode & S_IFMT) != S_IFDIR || - (dp = (MYDIR *)malloc(sizeof(MYDIR))) == NULL) - return NULL; - dp->fd = fd; - return dp; -} - -void myclosedir(MYDIR *dp) { - if (dp) { - close(dp->fd); - free(dp); - } -} - -#include - -#define DIRSIZE 14 - -Dirent *myreaddir(MYDIR *dp) { - struct direct dirbuf; - static Dirent d; - - while (read(dp->fd, (char *)&dirbuf, sizeof(dirbuf)) == sizeof(dirbuf)) { - if (dirbuf.d_ino == 0) - continue; - d.ino = dirbuf.d_ino; - strncpy(d.name, dirbuf.d_name, DIRSIZE); - d.name[DIRSIZE] = '\0'; - return &d; - } - return NULL; -} - -int main(int argc, char *argv[]) { - if (argc == 1) - fsize("."); - else - while (--argc > 0) - fsize(*++argv); - return 0; -} diff --git a/source/cprogramming/chapter8/cprogs/Ex_8.1_mycat.c b/source/cprogramming/chapter8/cprogs/ex_8.1_mycat.c similarity index 78% rename from source/cprogramming/chapter8/cprogs/Ex_8.1_mycat.c rename to source/cprogramming/chapter8/cprogs/ex_8.1_mycat.c index d6fc2a9e..164b937f 100644 --- a/source/cprogramming/chapter8/cprogs/Ex_8.1_mycat.c +++ b/source/cprogramming/chapter8/cprogs/ex_8.1_mycat.c @@ -1,11 +1,8 @@ -/* Rewrite the program cat from Chapter 7 using read,write,open and close -instead of their standard library equivalents. Perform experiments to determine -the relative speeds of the two versions */ - #include #include #include #include +#include #define STDIN 0 #define STDOUT 1 @@ -17,10 +14,10 @@ void error(char *fmt, ...) { va_list args; va_start(args, fmt); - fprintf((FILE *)STDERR, "error: "); + fprintf((FILE *) STDERR, "error: "); - vfprintf((FILE *)STDERR, fmt, args); - fprintf((FILE *)STDERR, "\n"); + vfprintf((FILE *) STDERR, fmt, args); + fprintf((FILE *) STDERR, "\n"); va_end(args); exit(1); } @@ -39,7 +36,6 @@ void filecopy(int ifd, int ofd) { } /* cat: concatenate files - read/write/open/close */ - int main(int argc, char *argv[]) { int fd; @@ -56,4 +52,4 @@ int main(int argc, char *argv[]) { close(fd); } return 0; -} +} \ No newline at end of file diff --git a/source/cprogramming/chapter8/cprogs/Ex_8.2.c b/source/cprogramming/chapter8/cprogs/ex_8.2.c similarity index 56% rename from source/cprogramming/chapter8/cprogs/Ex_8.2.c rename to source/cprogramming/chapter8/cprogs/ex_8.2.c index 1bd8c34b..df888546 100644 --- a/source/cprogramming/chapter8/cprogs/Ex_8.2.c +++ b/source/cprogramming/chapter8/cprogs/ex_8.2.c @@ -1,9 +1,4 @@ -#include -#include -// The functions available from stdio.h are implemented here. -//#include #include -#include #include #ifdef NULL @@ -12,7 +7,7 @@ #define NULL 0 #define EOF (-1) -#define BUFSIZ 1024 +#define BUFSIZE 1024 #define OPEN_MAX 20 /* max # files open at once */ typedef struct _iobuf { @@ -27,74 +22,24 @@ extern FILE _iob[OPEN_MAX]; #define stdin (&_iob[0]) #define stdout (&_iob[1]) -#define stderr (&_iob[2]) enum _flags { - _READ = 01, - /* file open for reading */ /* binary 1 */ - _WRITE = 02, - /* file open for writing */ /* binary 10 */ - _UNBUF = 03, - /* file is unbuffered */ /* binary 11 */ - _EOF = 010, - /* EOF has occurred on this file */ /* binary 1000 */ - _ERR = 020, - /* error occurred on this file */ /* binary 10000*/ + _READ = 01, /* file open for reading */ /* binary 1 */ + _WRITE = 02, /* file open for writing */ /* binary 10 */ + _UNBUF = 03, /* file is unbuffered */ /* binary 11 */ + _EOF = 010, /* EOF has occurred on this file */ /* binary 1000 */ + _ERR = 020, /* error occurred on this file */ /* binary 10000*/ }; int _fillbuf(FILE *); -int _flushbuf(int, FILE *); -#define feof(p) (((p)->flag & _EOF) != 0) -#define ferror(p) (((p)->flag & _ERR) != 0) -#define fileno(p) ((p)->fd) +int _flushbuf(int, FILE *); #define getc(p) (--(p)->cnt >= 0 ? (unsigned char)*(p)->ptr++ : _fillbuf(p)) - #define putc(x, p) (--(p)->cnt >= 0 ? *(p)->ptr++ = (x) : _flushbuf((x), p)) - #define getchar() getc(stdin) #define putchar(x) putc((x), stdout) -#define PERMS 0666 /* RW for owner, group and others */ - -/* fopen: open file, return file ptr */ - -FILE *fopen(char *name, char *mode) { - int fd; - FILE *fp; - - if (*mode != 'r' && *mode != 'w' && *mode != 'a') - return NULL; - - /* Bit operation */ - - for (fp = _iob; fp < _iob + OPEN_MAX; fp++) - if ((fp->flag & (_READ | _WRITE)) == 0) - break; /* found free slot */ - - if (fp >= _iob + OPEN_MAX) /* no free slots */ - return NULL; - - if (*mode == 'w') - fd = creat(name, PERMS); - else if (*mode == 'a') { - if ((fd = open(name, O_WRONLY, 0)) == -1) - fd = creat(name, PERMS); - lseek(fd, 0L, 2); - } else - fd = open(name, O_RDONLY, 0); - - if (fd == -1) /* couldn't access name */ - return NULL; - - fp->fd = fd; - fp->cnt = 0; - fp->base = NULL; - fp->flag = (*mode == 'r') ? _READ : _WRITE; - return fp; -} - /* _fillbuf: allocate and fill input buffer */ int _fillbuf(FILE *fp) { @@ -107,10 +52,10 @@ int _fillbuf(FILE *fp) { /* this is a bit operation */ - bufsize = (fp->flag & _UNBUF) ? 1 : BUFSIZ; + bufsize = (fp->flag & _UNBUF) ? 1 : BUFSIZE; if (fp->base == NULL) /* no buffer yet */ - if ((fp->base = (char *)malloc(bufsize)) == NULL) + if ((fp->base = (char *) malloc(bufsize)) == NULL) return EOF; /* can't get buffer */ fp->ptr = fp->base; @@ -127,7 +72,7 @@ int _fillbuf(FILE *fp) { return EOF; } - return (unsigned char)*fp->ptr++; + return (unsigned char) *fp->ptr++; } /* _flushbuf: flush a buffer */ @@ -143,12 +88,12 @@ int _flushbuf(int c, FILE *f) { if (f->base == NULL && ((f->flag & _UNBUF) == 0)) { /* no buffer yet */ - if ((f->base = malloc(BUFSIZ)) == NULL) + if ((f->base = malloc(BUFSIZE)) == NULL) /* could not allocate a buffer, so try unbuffered */ f->flag |= _UNBUF; else { f->ptr = f->base; - f->cnt = BUFSIZ - 1; + f->cnt = BUFSIZE - 1; } } @@ -166,10 +111,10 @@ int _flushbuf(int c, FILE *f) { /*if ( c!= EOF) { f->ptr = uc; } */ - bufsize = (int)(f->ptr - f->base); + bufsize = (int) (f->ptr - f->base); num_written = write(f->fd, f->base, bufsize); f->ptr = f->base; - f->cnt = BUFSIZ - 1; + f->cnt = BUFSIZE - 1; } if (num_written == bufsize) @@ -181,13 +126,13 @@ int _flushbuf(int c, FILE *f) { } FILE _iob[OPEN_MAX] = {/* stdin, stdout, stderr */ - {0, (char *)0, (char *)0, _READ, 0}, - {0, (char *)0, (char *)0, _WRITE, 1}, - {0, (char *)0, (char *)0, _WRITE | _UNBUF, 2}}; + {0, (char *) 0, (char *) 0, _READ, 0}, + {0, (char *) 0, (char *) 0, _WRITE, 1}, + {0, (char *) 0, (char *) 0, _WRITE | _UNBUF, 2}}; int main(int argc, char *argv[]) { int c; while ((c = getchar()) != 'x') { putchar(c); } -} +} \ No newline at end of file diff --git a/source/cprogramming/chapter8/cprogs/Ex_8.3.c b/source/cprogramming/chapter8/cprogs/ex_8.3.c similarity index 88% rename from source/cprogramming/chapter8/cprogs/Ex_8.3.c rename to source/cprogramming/chapter8/cprogs/ex_8.3.c index 9327615d..945b99c5 100644 --- a/source/cprogramming/chapter8/cprogs/Ex_8.3.c +++ b/source/cprogramming/chapter8/cprogs/ex_8.3.c @@ -1,9 +1,5 @@ #include -#include -// The functions available from stdio.h are implemented here. -//#include #include -#include #include #ifdef NULL @@ -27,7 +23,6 @@ extern FILE _iob[OPEN_MAX]; #define stdin (&_iob[0]) #define stdout (&_iob[1]) -#define stderr (&_iob[2]) enum _flags { _READ = 01, /* file open for reading */ @@ -38,11 +33,8 @@ enum _flags { }; int _fillbuf(FILE *); -int _flushbuf(int, FILE *); -#define feof(p) (((p)->flag & _EOF) != 0) -#define ferror(p) (((p)->flag & _ERR) != 0) -#define fileno(p) ((p)->fd) +int _flushbuf(int, FILE *); #define getc(p) (--(p)->cnt >= 0 ? (unsigned char)*(p)->ptr++ : _fillbuf(p)) @@ -99,7 +91,7 @@ int _fillbuf(FILE *fp) { bufsize = (fp->flag & _UNBUF) ? 1 : BUFSIZ; if (fp->base == NULL) /* no buffer yet */ - if ((fp->base = (char *)malloc(bufsize)) == NULL) + if ((fp->base = (char *) malloc(bufsize)) == NULL) return EOF; /* can't get buffer */ fp->ptr = fp->base; @@ -114,7 +106,7 @@ int _fillbuf(FILE *fp) { return EOF; } - return (unsigned char)*fp->ptr++; + return (unsigned char) *fp->ptr++; } /* _flushbuf: flush a buffer */ @@ -154,7 +146,7 @@ int _flushbuf(int c, FILE *f) { /*if ( c!= EOF) { f->ptr = uc; } */ - bufsize = (int)(f->ptr - f->base); + bufsize = (int) (f->ptr - f->base); num_written = write(f->fd, f->base, bufsize); f->ptr = f->base; f->cnt = BUFSIZ - 1; @@ -169,9 +161,9 @@ int _flushbuf(int c, FILE *f) { } FILE _iob[OPEN_MAX] = {/* stdin, stdout, stderr */ - {0, (char *)0, (char *)0, _READ, 0}, - {0, (char *)0, (char *)0, _WRITE, 1}, - {0, (char *)0, (char *)0, _WRITE | _UNBUF, 2}}; + {0, (char *) 0, (char *) 0, _READ, 0}, + {0, (char *) 0, (char *) 0, _WRITE, 1}, + {0, (char *) 0, (char *) 0, _WRITE | _UNBUF, 2}}; /* fflush */ int fflush(FILE *f) { diff --git a/source/cprogramming/chapter8/cprogs/Ex_8.4.c b/source/cprogramming/chapter8/cprogs/ex_8.4.c similarity index 100% rename from source/cprogramming/chapter8/cprogs/Ex_8.4.c rename to source/cprogramming/chapter8/cprogs/ex_8.4.c diff --git a/source/cprogramming/chapter8/cprogs/ex_8.5_fsize.c b/source/cprogramming/chapter8/cprogs/ex_8.5_fsize.c new file mode 100644 index 00000000..ce59bcc0 --- /dev/null +++ b/source/cprogramming/chapter8/cprogs/ex_8.5_fsize.c @@ -0,0 +1,80 @@ +/* + Modify the fsize program to print the other information contained in the inode entry. + + Solution by Akil Adeshwar + https://clc-wiki.net/wiki/K%26R2_solutions:Chapter_8:Exercise_5 +*/ + +#include +#include +#include +#include +#include +#include +#include +#include + + +#define MAX_PATH 1024 + +#ifndef DIRSIZ +#define DIRSIZ 14 +#endif + + +void dirwalk( char *dir,void (*fcn)(char *)){ + + char name[MAX_PATH]; + struct dirent *dp; + DIR *dfd; + + if((dfd = opendir(dir))==NULL){ + puts("Error: Cannot open Directory"); + return; + } + puts(dir); + // Get each dir entry + while((dp=readdir(dfd)) != NULL){ + // Skip . and .. is redundant. + if(strcmp(dp->d_name,".") == 0 + || strcmp(dp->d_name,"..") ==0 ) + continue; + if(strlen(dir)+strlen(dp->d_name)+2 > sizeof(name)) + puts("Error: Name too long!"); + else{ + sprintf(name,"%s/%s",dir,dp->d_name); + // Call fsize + (*fcn)(name); + } + } + closedir(dfd); +} + +void fsize(char *name){ + struct stat stbuf; + + if(stat(name,&stbuf) == -1){ + puts("Error: Cannot get file stats!"); + return; + } + + if((stbuf.st_mode & S_IFMT) == S_IFDIR){ + dirwalk(name,fsize); + } + struct passwd *pwd = getpwuid(stbuf.st_uid); + //print file name,size and owner + printf("%81d %s Owner: %s\n",(int)stbuf.st_size,name,pwd->pw_name); +} + + + + +int main(int argc,char *argv[]){ + + if(argc==1) + fsize("."); + else + while(--argc>0) + fsize(*++argv); + return 0; +} diff --git a/source/cprogramming/chapter8/cprogs/Ex_8.6_calloc.c b/source/cprogramming/chapter8/cprogs/ex_8.6_calloc.c similarity index 100% rename from source/cprogramming/chapter8/cprogs/Ex_8.6_calloc.c rename to source/cprogramming/chapter8/cprogs/ex_8.6_calloc.c diff --git a/source/cprogramming/chapter8/cprogs/Ex_8.7_malloc.c b/source/cprogramming/chapter8/cprogs/ex_8.7_malloc.c similarity index 93% rename from source/cprogramming/chapter8/cprogs/Ex_8.7_malloc.c rename to source/cprogramming/chapter8/cprogs/ex_8.7_malloc.c index 93a53762..fe0fd30f 100644 --- a/source/cprogramming/chapter8/cprogs/Ex_8.7_malloc.c +++ b/source/cprogramming/chapter8/cprogs/ex_8.7_malloc.c @@ -33,12 +33,12 @@ static Header *morecore(unsigned nu) { nu = NALLOC; cp = sbrk(nu * sizeof(Header)); - if (cp == (char *)-1) /* no space at all */ + if (cp == (char *) -1) /* no space at all */ return NULL; - up = (Header *)cp; + up = (Header *) cp; up->s.size = nu; - free((void *)(up + 1)); + free((void *) (up + 1)); return freep; } @@ -69,7 +69,7 @@ void *mymalloc(unsigned nbytes) { p->s.size = nunits; } freep = prevp; - return (void *)(p + 1); + return (void *) (p + 1); } if (p == freep) /* wrapped around free list */ @@ -83,7 +83,7 @@ void *mymalloc(unsigned nbytes) { void free(void *ap) { Header *bp, *p; - bp = (Header *)ap - 1; /* point to block header */ + bp = (Header *) ap - 1; /* point to block header */ for (p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr) if (p >= p->s.ptr && (bp > p || bp < p->s.ptr)) break; /* freed block at start or end of arena */ diff --git a/source/cprogramming/chapter8/cprogs/Ex_8.8_bfree.c b/source/cprogramming/chapter8/cprogs/ex_8.8_bfree.c similarity index 100% rename from source/cprogramming/chapter8/cprogs/Ex_8.8_bfree.c rename to source/cprogramming/chapter8/cprogs/ex_8.8_bfree.c diff --git a/source/cprogramming/chapter8/cprogs/sec_8.2_getchar.c b/source/cprogramming/chapter8/cprogs/sec_8.2_getchar.c index c36604fc..5f615cc2 100644 --- a/source/cprogramming/chapter8/cprogs/sec_8.2_getchar.c +++ b/source/cprogramming/chapter8/cprogs/sec_8.2_getchar.c @@ -29,7 +29,7 @@ int main() { int ugetchar(void) { char c; - return (read(0, &c, 1) == 1) ? (unsigned char)c : EOF; + return (read(0, &c, 1) == 1) ? (unsigned char) c : EOF; } int bgetchar(void) { @@ -43,5 +43,5 @@ int bgetchar(void) { bufp = buf; } - return (--n >= 0) ? (unsigned char)*bufp++ : EOF; + return (--n >= 0) ? (unsigned char) *bufp++ : EOF; } diff --git a/source/cprogramming/chapter8/cprogs/sec_8.3_open_creat.c b/source/cprogramming/chapter8/cprogs/sec_8.3_open_creat.c index a8bff8e8..49618bcf 100644 --- a/source/cprogramming/chapter8/cprogs/sec_8.3_open_creat.c +++ b/source/cprogramming/chapter8/cprogs/sec_8.3_open_creat.c @@ -1,8 +1,12 @@ -#include -#include -#include -#include -#include +#include // For file control options like O_RDONLY +#include // For variable argument functions +#include // For standard I/O +#include // For system calls +#include // For UNIX standard functions like read/write +#include // For exit() + +#define PERMS 0666 // File permissions: read/write for all users +#define BUFSIZ 1024 // Buffer size for reading/writing #define PERMS 0666 /* RW for owner, group and others */ @@ -29,12 +33,17 @@ int main(int argc, char *argv[]) { return 0; } +/** +fmt is the format string parameter +... (ellipsis) indicates variable number of arguments can follow + +*/ void merror(char *fmt, ...) { - va_list args; - va_start(args, fmt); + va_list args; // Declares a variable to hold the argument list + va_start(args, fmt); // Initialize 'args' to start after 'fmt' fprintf(stderr, "error: "); - vfprintf(stderr, fmt, args); + vfprintf(stderr, fmt, args); // Print formatted output using args list fprintf(stderr, "\n"); - va_end(args); + va_end(args); // cleans up variable arguments. exit(1); } diff --git a/source/cprogramming/chapter8/ex_8.1_mycat.rst b/source/cprogramming/chapter8/ex_8.1_mycat.rst index 1edd1584..a4eac327 100644 --- a/source/cprogramming/chapter8/ex_8.1_mycat.rst +++ b/source/cprogramming/chapter8/ex_8.1_mycat.rst @@ -16,4 +16,7 @@ the relative speeds of the two versions. Explanation =========== +This is custom implementation of `cat` program using read/write/open/close function calls instead of the standard library ones. + + diff --git a/source/cprogramming/chapter8/ex_8.2.rst b/source/cprogramming/chapter8/ex_8.2.rst index 1c6f5bfb..a6ce6a34 100644 --- a/source/cprogramming/chapter8/ex_8.2.rst +++ b/source/cprogramming/chapter8/ex_8.2.rst @@ -8,12 +8,14 @@ Question Rewrite fopen and _fillbuf with fields instead of explicit bit operations. Compare code size and execution speed. -**inprogress** - .. literalinclude:: cprogs/ex_8.2.c :language: c Explanation =========== +This is a low level implementation of fopen and _fillbuf with enums and fields. + + + diff --git a/source/cprogramming/chapter8/ex_8.3.rst b/source/cprogramming/chapter8/ex_8.3.rst index 046e71a0..4454a521 100644 --- a/source/cprogramming/chapter8/ex_8.3.rst +++ b/source/cprogramming/chapter8/ex_8.3.rst @@ -15,3 +15,6 @@ Design and write _flushbuf, fflush, and fclose. Explanation =========== +This is an internal implementation of `_flushbuf`, `fflush`, and `fclose`. This is implemented by defining a structure called +`_iobuf`, making it point to a file pointer, and reading the contents as a linked list implementation, each time allocating a memory to `base` in the iobuf. + diff --git a/source/cprogramming/chapter8/ex_8.4.rst b/source/cprogramming/chapter8/ex_8.4.rst index 92c982e4..e8174471 100644 --- a/source/cprogramming/chapter8/ex_8.4.rst +++ b/source/cprogramming/chapter8/ex_8.4.rst @@ -19,4 +19,13 @@ The standard library function: Explanation =========== +This uses three fields + +:: + + #define SEEK_SET 0 + #define SEEK_CUR 1 + #define SEEK_END 2 + +and determines where we are in the file using the file seek operations. diff --git a/source/cprogramming/chapter8/ex_8.5_fsize.rst b/source/cprogramming/chapter8/ex_8.5_fsize.rst index 7de7d3ef..b316f08e 100644 --- a/source/cprogramming/chapter8/ex_8.5_fsize.rst +++ b/source/cprogramming/chapter8/ex_8.5_fsize.rst @@ -16,4 +16,20 @@ entry. Explanation =========== +The main purpose of this program information about files and directories, similar to the ls command in Unix-like systems, +but with more detailed information. It prints various file attributes like size, block information, and other metadata. + +If a file argument is provided, it gets file statistics using stat to get the file inode and other information. +If the program encounters a directory, it uses dirwalk to recursively traverse through it and on each file, it does +a stat on the file. + +:: + + $ ./ex_8.5_fsize source/_templates + + source/_templates + 101 source/_templates/index.html Owner: ec2-user + 902 source/_templates/layout.html Owner: ec2-user + 275 source/_templates/logo.html Owner: ec2-user + 60 source/_templates Owner: ec2-user \ No newline at end of file diff --git a/source/cprogramming/chapter8/ex_8.6_calloc.rst b/source/cprogramming/chapter8/ex_8.6_calloc.rst index 2c12fd34..03598c58 100644 --- a/source/cprogramming/chapter8/ex_8.6_calloc.rst +++ b/source/cprogramming/chapter8/ex_8.6_calloc.rst @@ -16,3 +16,8 @@ or by modifying it. Explanation =========== +This is a custom implmentation of calloc. The standard library function calloc(n,size) returns a pointer to n objects +of `size`, with the storage intialized to zero. + +This program writes calloc,by utilizing malloc. + diff --git a/source/cprogramming/chapter8/ex_8.7_malloc.rst b/source/cprogramming/chapter8/ex_8.7_malloc.rst index 2df7136c..26622729 100644 --- a/source/cprogramming/chapter8/ex_8.7_malloc.rst +++ b/source/cprogramming/chapter8/ex_8.7_malloc.rst @@ -9,9 +9,18 @@ Malloc accepts a size request without checking its plausibility; free believes that the block it is asked to free contains a valid size field. Improve these routines so they make more pains with error checking. -.. literalinclude:: cprogs/Ex_8.7_malloc.c +.. literalinclude:: cprogs/ex_8.7_malloc.c :language: c Explanation =========== +This is an error checking implementation of malloc. If it cannot allocate more bytes, it will throw an error + +:: + + if (nbytes > MAXBYTES) { + fprintf(stderr, "alloc: can't allocate more than %u bytes\n", MAXBYTES); + return NULL; + } + diff --git a/source/cprogramming/chapter8/ex_8.8_bfree.rst b/source/cprogramming/chapter8/ex_8.8_bfree.rst index 4b81d193..3613c191 100644 --- a/source/cprogramming/chapter8/ex_8.8_bfree.rst +++ b/source/cprogramming/chapter8/ex_8.8_bfree.rst @@ -9,10 +9,15 @@ Write a routine bfree(p,n) that will free any arbitrary block p of n characters into the free list maintained by malloc and free. By using bfree, a user can add a static or external array to the free list at any time. -.. literalinclude:: cprogs/Ex_8.8_bfree.c +.. literalinclude:: cprogs/ex_8.8_bfree.c :language: c Explanation =========== +This program manages the memory blocks, takes care of the alignment, and for the smaller memory blocks it maintains a wtbfree method +that helps align smaller memory blocks. + +This memory allocation program is simliar how to parking lot orchestrator can allocate park spots for regular sized cars +and smaller vehicles like bikes, and it will squeeze the spots together to make room for bigger car or additional small sized bikes. \ No newline at end of file diff --git a/source/cprogramming/chapter8/index.rst b/source/cprogramming/chapter8/index.rst new file mode 100644 index 00000000..4c2d4026 --- /dev/null +++ b/source/cprogramming/chapter8/index.rst @@ -0,0 +1,19 @@ +========= +Chapter 8 +========= + +.. toctree:: + :maxdepth: 1 + + + ex_8.1_mycat + ex_8.2 + ex_8.3 + ex_8.4 + ex_8.5_fsize + ex_8.6_calloc + ex_8.7_malloc + ex_8.8_bfree + sec_8.2_getchar + sec_8.2_read_write + sec_8.3_open_creat diff --git a/source/cprogramming/chapter8/sec_8.2_getchar.rst b/source/cprogramming/chapter8/sec_8.2_getchar.rst index 2a3cdcd5..95417c1f 100644 --- a/source/cprogramming/chapter8/sec_8.2_getchar.rst +++ b/source/cprogramming/chapter8/sec_8.2_getchar.rst @@ -22,7 +22,7 @@ The buffered version of getchar, sets aside a buffer for reading the characters. :: - static char buf[BUFSIZ]; + static char buf[BUFSIZE]; static char *bufp = buf; And reads each of the characters into the buffer, `read(0, buf, sizeof buf)` and then returns one character at a diff --git a/source/cprogramming/chapter8/sec_8.2_read_write.rst b/source/cprogramming/chapter8/sec_8.2_read_write.rst index 8d8bb175..343429cd 100644 --- a/source/cprogramming/chapter8/sec_8.2_read_write.rst +++ b/source/cprogramming/chapter8/sec_8.2_read_write.rst @@ -17,4 +17,24 @@ Explanation This uses the read and write system calls to copy input to output. +:: + # Compile the program + + gcc copy.c -o copy + + # Test 1: Echo a simple string + + echo "Hello, World!" | ./copy + + # Test 2: Multiple lines + + cat << 'EOL' | ./copy + Line 1 + Line 2 + Line 3 + EOL + + # Test 3: Binary data (create a file with some null bytes) + + dd if=/dev/zero bs=1024 count=1 2>/dev/null | ./copy > /dev/null \ No newline at end of file diff --git a/source/cprogramming/chapter8/sec_8.3_open_creat.rst b/source/cprogramming/chapter8/sec_8.3_open_creat.rst index 9dc4fd08..bf6a0d22 100644 --- a/source/cprogramming/chapter8/sec_8.3_open_creat.rst +++ b/source/cprogramming/chapter8/sec_8.3_open_creat.rst @@ -15,4 +15,10 @@ Demonstrate the ``cp`` like program which copies the contents of one file to ano Explanation =========== +:: + while ((n = read(f1, buf, BUFSIZE)) > 0) + if (write(f2, buf, n) != n) + +Reads up to BUFSIZE bytes from source file into buffer. Writes the same number of bytes to destination file. continues +until entire file is copied diff --git a/source/cprogramming/concepts/concepts.rst b/source/cprogramming/concepts/concepts.rst new file mode 100644 index 00000000..2c5894b6 --- /dev/null +++ b/source/cprogramming/concepts/concepts.rst @@ -0,0 +1,112 @@ +C Programming Building Blocks +============================= + +These are simple C programs that provide an intuitive understanding of the entire +language. These are building blocks of programs that can help you understand any +complex program. This even this entire Learn To Solve It can be approached if the reader +has the intuitive understanding of these building block C Programs. + +Integer and float data types +---------------------------- + +.. literalinclude:: cprogs/p1_integer_float_data_types.c + :language: c + +Character Datatype +------------------ + +.. literalinclude:: cprogs/p2_character_datatype.c + :language: c + +Character Array and String +-------------------------- + +.. literalinclude:: cprogs/p3_charater_array_string.c + :language: c + +Pointers +-------- + +.. literalinclude:: cprogs/p4_pointer.c + :language: c + +.. literalinclude:: cprogs/p5_pointer.c + :language: c + +.. literalinclude:: cprogs/p6_pointer.c + :language: c + +.. literalinclude:: cprogs/p7_pointer.c + :language: c + +.. literalinclude:: cprogs/p8_pointer.c + :language: c + +Structures +---------- + +.. literalinclude:: cprogs/p9_structures.c + :language: c + +Pointer to Structures +--------------------- + +.. literalinclude:: cprogs/p10_pointer_to_structures.c + :language: c + +TypeDefs +-------- + +.. literalinclude:: cprogs/p11_defines_two_dimensional_arrays.c + :language: c + +DEFS and IFDEFS Macros +---------------------- + +.. literalinclude:: cprogs/p14_macros.c + :language: c + +Union and Pointer to Unions +--------------------------- + +.. literalinclude:: cprogs/p15_union.c + :language: c + +Bitwise manipulation +-------------------- + +.. literalinclude:: cprogs/p16_bitwise.c + :language: c + +Using extern +------------ + +.. literalinclude:: cprogs/p17_extern.c + :language: c + +.. literalinclude:: cprogs/other.h + :language: c + +A practical program demonstrating the use of externs + +.. literalinclude:: cprogs/p18_extern_config.c + :language: c + +.. literalinclude:: cprogs/config.h + :language: c + +.. literalinclude:: cprogs/config.c + :language: c + + +Using enums +----------- + +.. literalinclude:: cprogs/p19_enums.c + :language: c + +malloc and calloc +----------------- + +.. literalinclude:: cprogs/p13_malloc.c + :language: c \ No newline at end of file diff --git a/source/cprogramming/concepts/cprogs/config.c b/source/cprogramming/concepts/cprogs/config.c new file mode 100644 index 00000000..0201010c --- /dev/null +++ b/source/cprogramming/concepts/cprogs/config.c @@ -0,0 +1,11 @@ +#include "config.h" + +struct Config app_config = { + .max_connections = 100, + .server_name = "localhost", + .port = 8080 +}; + +void init_config(void) { + // Initialize configuration +} \ No newline at end of file diff --git a/source/cprogramming/concepts/cprogs/config.h b/source/cprogramming/concepts/cprogs/config.h new file mode 100644 index 00000000..2f966e59 --- /dev/null +++ b/source/cprogramming/concepts/cprogs/config.h @@ -0,0 +1,11 @@ +#ifndef LEARNTOSOLVEIT_CONFIG_H +#define LEARNTOSOLVEIT_CONFIG_H + +extern struct Config { + int max_connections; + char *server_name; + int port; +} app_config; + +extern void init_config(void); +#endif //LEARNTOSOLVEIT_CONFIG_H diff --git a/source/cprogramming/concepts/cprogs/other.h b/source/cprogramming/concepts/cprogs/other.h new file mode 100644 index 00000000..2c7656f1 --- /dev/null +++ b/source/cprogramming/concepts/cprogs/other.h @@ -0,0 +1,12 @@ +#ifndef LEARNTOSOLVEIT_OTHER_H +#define LEARNTOSOLVEIT_OTHER_H + +#include +int shared_value = 10; + +void modify_value(void) { + shared_value *= 2; + printf("Modified in other.h : %d\n", shared_value); +} + +#endif //LEARNTOSOLVEIT_OTHER_H diff --git a/source/cprogramming/concepts/cprogs/p10_pointer_to_structures.c b/source/cprogramming/concepts/cprogs/p10_pointer_to_structures.c new file mode 100644 index 00000000..fa72b97f --- /dev/null +++ b/source/cprogramming/concepts/cprogs/p10_pointer_to_structures.c @@ -0,0 +1,30 @@ +#include +#include + +struct tag { /* the structure type */ + char lname[20]; /* last name */ + char fname[20]; /* first name */ + int age; /* age */ + float rate; /* e.g. 12.75 per hour */ +}; + +struct tag my_struct; /* define the structure */ +void show_name(struct tag *p); /* function prototype */ + +int main(void) { + struct tag *st_ptr; /* a pointer to a structure */ + st_ptr = &my_struct; /* point the pointer to my_struct */ + strcpy(my_struct.lname, "Jensen"); + strcpy(my_struct.fname, "Ted"); + printf("\n%s ", my_struct.fname); + printf("%s\n", my_struct.lname); + my_struct.age = 63; + show_name(st_ptr); /* pass the pointer */ + return 0; +} + +void show_name(struct tag *p) { + printf("\n%s ", p->fname); /* p points to a structure */ + printf("%s ", p->lname); + printf("%d\n", p->age); +} \ No newline at end of file diff --git a/source/cprogramming/concepts/cprogs/p11_defines_two_dimensional_arrays.c b/source/cprogramming/concepts/cprogs/p11_defines_two_dimensional_arrays.c new file mode 100644 index 00000000..0765eb62 --- /dev/null +++ b/source/cprogramming/concepts/cprogs/p11_defines_two_dimensional_arrays.c @@ -0,0 +1,23 @@ +#include + +#define ROWS 5 +#define COLS 10 + +int main(int argc, char *argv[]) { + int multi[ROWS][COLS]; + + int row, col; + + for (row = 0; row < ROWS; row++) { + for (col = 0; col < COLS; col++) { + multi[row][col] = row * col; + } + } + + for (row = 0; row < ROWS; row++) { + for (col = 0; col < COLS; col++) { + printf("\n%d ", multi[row][col]); + printf("%d ", *(*(multi + row) + col)); + } + } +} \ No newline at end of file diff --git a/source/cprogramming/concepts/cprogs/p12_typedef.c b/source/cprogramming/concepts/cprogs/p12_typedef.c new file mode 100644 index 00000000..1e29a6c2 --- /dev/null +++ b/source/cprogramming/concepts/cprogs/p12_typedef.c @@ -0,0 +1,9 @@ +#include + +int main(int argc, char *argv[]) { + typedef unsigned char byte; + + byte b[] = {'b', 'y', 't', 'e', '\0'}; + + printf("%s", b); +} \ No newline at end of file diff --git a/source/cprogramming/concepts/cprogs/p13_malloc.c b/source/cprogramming/concepts/cprogs/p13_malloc.c new file mode 100644 index 00000000..e2ff5ff6 --- /dev/null +++ b/source/cprogramming/concepts/cprogs/p13_malloc.c @@ -0,0 +1,25 @@ +#include +#include + +#define COLS 5 + + +int main(int argc, char *argv[]) { + + typedef int RowArray[COLS]; + RowArray *rptr; + + int nrows = 10; + int row, col; + + rptr = malloc(nrows * COLS * sizeof(int)); + + for (row = 0; row < nrows; row++) { + for (col = 0; col < COLS; col++) { + rptr[row][col] = row * col; + } + } + + free(rptr); + return 0; +} \ No newline at end of file diff --git a/source/cprogramming/concepts/cprogs/p14_macros.c b/source/cprogramming/concepts/cprogs/p14_macros.c new file mode 100644 index 00000000..2d4716eb --- /dev/null +++ b/source/cprogramming/concepts/cprogs/p14_macros.c @@ -0,0 +1,31 @@ +#ifndef MY_PROGRAM_HEADER +#define MY_PROGRAM_HEADER + +#define SQUARE(x) ((x) * (x)) +#define WINDOWS 1 +#define LINUX 2 +#define PLATFORM LINUX + +#include + +int main(int argc, char *argv[]) { + int num = 20; + printf("Square of the number is %d\n", SQUARE(num)); + + // Conditinal Compilation + +#ifdef PLATFORM +#if PLATFORM == WINDOWS + printf("Compiling for Windows\n"); +#define PATH_SEPARATOR "\\" +#elif PLATFORM == LINUX + printf("Compiling for Linux\n"); +#endif +#define PATH_SEPARATOR "/" +#else +#error Platform not defined! +#endif + +} + +#endif // MY_PROGRAM_HEADER \ No newline at end of file diff --git a/source/cprogramming/concepts/cprogs/p15_union.c b/source/cprogramming/concepts/cprogs/p15_union.c new file mode 100644 index 00000000..3d286895 --- /dev/null +++ b/source/cprogramming/concepts/cprogs/p15_union.c @@ -0,0 +1,23 @@ +#include + +union Data { + int i; + float f; + char str[20]; +}; + +int main(int argc, char *argv[]) { + union Data data; + union Data *ptr; + + ptr = &data; + + data.i = 42; + printf("Integer value: %d \n", data.i); + + ptr->f = 3.14; + printf("Float value: %f\n", data.f); + + printf("Integer value again: %d \n", data.i); + printf("Since Union share memory, the integer value is lost."); +} \ No newline at end of file diff --git a/source/cprogramming/concepts/cprogs/p16_bitwise.c b/source/cprogramming/concepts/cprogs/p16_bitwise.c new file mode 100644 index 00000000..ec4acb9b --- /dev/null +++ b/source/cprogramming/concepts/cprogs/p16_bitwise.c @@ -0,0 +1,59 @@ +#include +#include + +/** + * %b specifier is available since C23 + * https://www.open-std.org/jtc1/sc22/wg14/www/docs/n2630.pdf + * if %b is not available for your compiler + * we can use print_bin to see the binary + **/ + +void print_bin(unsigned char byte) +{ + int i = CHAR_BIT; /* however many bits are in a byte on your platform */ + while(i--) { + putchar('0' + ((byte >> i) & 1)); /* loop through and print the bits */ + } +} + +int main(int argc, char *argv[]) { + unsigned char a = 12 ; // Binary 00001100 + unsigned char b = 10; // Binary 00001010 + + printf("Original Values: \n"); + printf("a = %d (Binary: %08b)\n", a, a); + printf("b = %d (Binary: %08b)\n", b, b); + + printf("Decimal %d in Binary is", a); + print_bin(a); + + printf("\n"); + + printf("Decimal %d in Binary is", b); + print_bin(b); + + // Bitwise AND (&) + printf("\n Bitwise AND (&): \n"); + printf("%d & %d = %d (binary: %08b)\n", a, b, a & b, a & b); + + + // Bitwise OR (|) + printf("\n Bitwise OR (|): \n"); + printf("%d | %d = %d (binary: %08b)\n", a, b, a | b, a | b); + + // Bitwise XOR (^) + printf("\n Bitwise XOR (^): \n"); + printf("%d ^ %d = %d (binary: %08b)\n", a, b, a ^b, a ^b); + + // Left shift << + printf("\n Left Shift (<<): \n"); + printf("%d << 1 = %d (binary: %08b)\n", a, a << 1, a << 1); + + // Right shift >> + printf("\n Right Shift (>>): \n"); + printf("%d >> 1 = %d (binary: %08b)\n", a, a >> 1, a >> 1); + + // Bitwise NOT (~) + printf("\n Bitwise NOT (~) \n"); + printf("~%d = %d (binary: %08b)\n", a, (unsigned char) ~a, (unsigned char)~a); +} \ No newline at end of file diff --git a/source/cprogramming/concepts/cprogs/p17_extern.c b/source/cprogramming/concepts/cprogs/p17_extern.c new file mode 100644 index 00000000..d2ea0a15 --- /dev/null +++ b/source/cprogramming/concepts/cprogs/p17_extern.c @@ -0,0 +1,21 @@ +#include +#include "other.h" + +// Declare the external variable +extern int shared_value; // This tells compiler variable is defined elsewhere +extern void modify_value(void); // Declare external function + +int main(int argc, char *argv[]) { + printf("Initial shared value: %d\n", shared_value); + + + // Modify the value in main + shared_value = 20; + printf("After modifying the value in main: %d\n", shared_value); + + + modify_value(); + printf("After calling modify_value: %d\n", shared_value); + + return 0; +} \ No newline at end of file diff --git a/source/cprogramming/concepts/cprogs/p18_extern_config.c b/source/cprogramming/concepts/cprogs/p18_extern_config.c new file mode 100644 index 00000000..901b9c7d --- /dev/null +++ b/source/cprogramming/concepts/cprogs/p18_extern_config.c @@ -0,0 +1,14 @@ +#include +#include "config.h" + +/** + * $ gcc p18_extern_config.c config.c -o p18_extern_config + * $ ./p18_extern_config + * Max connections: 100 + **/ + +int main(int argc, char *argv[]) { + init_config(); + printf("Max connections: %d\n", app_config.max_connections); + return 0; +} \ No newline at end of file diff --git a/source/cprogramming/concepts/cprogs/p19_enums.c b/source/cprogramming/concepts/cprogs/p19_enums.c new file mode 100644 index 00000000..f2dac0d5 --- /dev/null +++ b/source/cprogramming/concepts/cprogs/p19_enums.c @@ -0,0 +1,38 @@ +#include + + +enum DayOfWeek { + SUNDAY = 1, + MONDAY, + TUESDAY, + WEDNESDAY, + THURSDAY, + FRIDAY, + SATURDAY +}; + +enum TaskStatus { + PENDING, // Will start at 0 + IN_PROGRESS, + COMPLETED, + CANCELLED +}; + +int main(int argc, char *argv[]) { + enum DayOfWeek today = WEDNESDAY; + printf("Day number of the week %d\n", today); + + + enum TaskStatus status = PENDING; + printf("\nTask Status: \n"); + printf("Initial Status: %d\n", status); + + status = COMPLETED; + printf("Updated status: %d\n", status); + + if (status == COMPLETED) { + printf("Task is Complete!\n"); + } + + return 0; +} \ No newline at end of file diff --git a/source/cprogramming/concepts/cprogs/p1_integer_float_data_types.c b/source/cprogramming/concepts/cprogs/p1_integer_float_data_types.c new file mode 100644 index 00000000..bfa0c028 --- /dev/null +++ b/source/cprogramming/concepts/cprogs/p1_integer_float_data_types.c @@ -0,0 +1,12 @@ +#include + +int main(int argc, char *argv[]) { + int int_variable; + float float_variable; + + int_variable = 10; + float_variable = 10.10; + + printf("The value of the integer variable is %d\n", int_variable); + printf("The value of my float variable is %f\n", float_variable); +} \ No newline at end of file diff --git a/source/cprogramming/concepts/cprogs/p2_character_datatype.c b/source/cprogramming/concepts/cprogs/p2_character_datatype.c new file mode 100644 index 00000000..8afe8c10 --- /dev/null +++ b/source/cprogramming/concepts/cprogs/p2_character_datatype.c @@ -0,0 +1,13 @@ +#include + +int main(int argc, char *argv[]) { + char char_value; + char_value = 'c'; + printf("The value of my character datatype is %c\n", char_value); + + int i = 0; + for (i = 0; i <128; i++) { + char_value = (char) i; + printf("The value of my character datatype is %c for the integer value %d \n", char_value, i); + } +} \ No newline at end of file diff --git a/source/cprogramming/concepts/cprogs/p3_charater_array_string.c b/source/cprogramming/concepts/cprogs/p3_charater_array_string.c new file mode 100644 index 00000000..76abd679 --- /dev/null +++ b/source/cprogramming/concepts/cprogs/p3_charater_array_string.c @@ -0,0 +1,21 @@ +#include + +int main(int argc, char *argv[]) { + char s[] = {'s', 't', 'r', 'i', 'n', 'g', '\0'}; + printf("%s\n", s); + + char s1[10]; + int i, j; + for (i = 65, j = 0; i < 70; i++) { + s1[j] = (char) i; + j++; + } + s1[j] = '\0'; + + printf("%s\n", s1); + + char s2[] = "string"; + + printf("%s\n", s2); + +} \ No newline at end of file diff --git a/source/cprogramming/concepts/cprogs/p4_pointer.c b/source/cprogramming/concepts/cprogs/p4_pointer.c new file mode 100644 index 00000000..413a13da --- /dev/null +++ b/source/cprogramming/concepts/cprogs/p4_pointer.c @@ -0,0 +1,7 @@ +#include + +int main() { + printf("size of a short is %d\\n", sizeof(short)); + printf("size of a int is %d\\n", sizeof(int)); + printf("size of a long is %d\\n", sizeof(long)); +} \ No newline at end of file diff --git a/source/cprogramming/concepts/cprogs/p5_pointer.c b/source/cprogramming/concepts/cprogs/p5_pointer.c new file mode 100644 index 00000000..7e0f577f --- /dev/null +++ b/source/cprogramming/concepts/cprogs/p5_pointer.c @@ -0,0 +1,17 @@ +#include + +int main(void) { + + int j, k; + int *ptr; + j = 1; + k = 2; + ptr = &k; + printf("\n"); + printf("j has the value %d and is stored at %p\n", j, (void *) &j); + printf("k has the value %d and is stored at %p\n", k, (void *) &k); + printf("ptr has the value %p and is stored at %p\n", ptr, (void *) &ptr); + printf("The value of the integer pointed to by ptr is %d\n", *ptr); + + return 0; +} \ No newline at end of file diff --git a/source/cprogramming/concepts/cprogs/p6_pointer.c b/source/cprogramming/concepts/cprogs/p6_pointer.c new file mode 100644 index 00000000..981a7090 --- /dev/null +++ b/source/cprogramming/concepts/cprogs/p6_pointer.c @@ -0,0 +1,16 @@ +#include + + +int main(void) { + + int my_array[] = {1, 23, 17, 4, -5, 100}; + int *ptr; + int i; + ptr = &my_array[0]; + printf("\n\n"); + for (i = 0; i < 6; i++) { + printf("my_array[%d] = %d ", i, my_array[i]); + printf("ptr + %d = %d\n", i, *(ptr + i)); + } + return 0; +} \ No newline at end of file diff --git a/source/cprogramming/concepts/cprogs/p7_pointer.c b/source/cprogramming/concepts/cprogs/p7_pointer.c new file mode 100644 index 00000000..f119cb2b --- /dev/null +++ b/source/cprogramming/concepts/cprogs/p7_pointer.c @@ -0,0 +1,22 @@ +#include + +int main(void) { + + char strA[80] = "A string to be used for demonstration purposes"; + char strB[80]; + + char *pA; /* a pointer to type character */ + char *pB; /* another pointer to type character */ + puts(strA); /* show string A */ + pA = strA; /* point pA at string A */ + puts(pA); /* show what pA is pointing to */ + pB = strB; /* point pB at string B */ + putchar('\n'); /* move down one line on the screen */ + while (*pA != '\0') /* line A (see text) */ + { + *pB++ = *pA++; /* line B (see text) */ + } + *pB = '\0'; /* line C (see text) */ + puts(strB); /* show strB on screen */ + return 0; +} diff --git a/source/cprogramming/concepts/cprogs/p8_pointer.c b/source/cprogramming/concepts/cprogs/p8_pointer.c new file mode 100644 index 00000000..5f05bc1f --- /dev/null +++ b/source/cprogramming/concepts/cprogs/p8_pointer.c @@ -0,0 +1,24 @@ +#include + +#define ROWS 5 +#define COLS 10 + +int multi[ROWS][COLS]; + +int main(void) { + int row, col; + for (row = 0; row < ROWS; row++) { + for (col = 0; col < COLS; col++) { + multi[row][col] = row * col; + } + } + + for (row = 0; row < ROWS; row++) { + for (col = 0; col < COLS; col++) { + printf("\n%d ", multi[row][col]); + printf("%d ", *(*(multi + row) + col)); + } + } + + return 0; +} \ No newline at end of file diff --git a/source/cprogramming/concepts/cprogs/p9_structures.c b/source/cprogramming/concepts/cprogs/p9_structures.c new file mode 100644 index 00000000..b6ff38fd --- /dev/null +++ b/source/cprogramming/concepts/cprogs/p9_structures.c @@ -0,0 +1,22 @@ +#include +#include + +int main(int argc, char *argv[]) { + struct tag { + char lname[20]; + char fname[20]; + int age; + float rate; + }; + + struct tag my_struct; + + strcpy(my_struct.lname, "Kumaran"); + strcpy(my_struct.fname, "Senthil"); + + printf("\n%s ", my_struct.fname); + printf("%s\n", my_struct.lname); + + return 0; +} + diff --git a/source/cprogramming/counts.rst b/source/cprogramming/counts.rst deleted file mode 100644 index fe80e3c7..00000000 --- a/source/cprogramming/counts.rst +++ /dev/null @@ -1,16 +0,0 @@ -====== -counts -====== - -*counts.c* - -.. literalinclude:: ../../languages/cprogs/counts.c - :language: c - :tab-width: 4 - - - -.. seealso:: - - * :c-suggest-improve:`counts.c` - * :c-better-explain:`counts.rst` diff --git a/source/cprogramming/day_datev3.rst b/source/cprogramming/day_datev3.rst deleted file mode 100644 index 85f10213..00000000 --- a/source/cprogramming/day_datev3.rst +++ /dev/null @@ -1,16 +0,0 @@ -========== -day_datev3 -========== - -*day_datev3.c* - -.. literalinclude:: ../../languages/cprogs/day_datev3.c - :language: c - :tab-width: 4 - - - -.. seealso:: - - * :c-suggest-improve:`day_datev3.c` - * :c-better-explain:`day_datev3.rst` diff --git a/source/cprogramming/dcl.rst b/source/cprogramming/dcl.rst deleted file mode 100644 index 53a1259e..00000000 --- a/source/cprogramming/dcl.rst +++ /dev/null @@ -1,18 +0,0 @@ -=== -dcl -=== - -*dcl.c* - -.. literalinclude:: ../../languages/cprogs/dcl.c - :language: c - :tab-width: 4 - ----- - - - -.. seealso:: - - * :c-suggest-improve:`dcl.c` - * :c-better-explain:`dcl.rst` diff --git a/source/cprogramming/endian.rst b/source/cprogramming/endian.rst deleted file mode 100644 index 286a2f17..00000000 --- a/source/cprogramming/endian.rst +++ /dev/null @@ -1,16 +0,0 @@ -====== -endian -====== - -*endian.c* - -.. literalinclude:: ../../languages/cprogs/endian.c - :language: c - :tab-width: 4 - - - -.. seealso:: - - * :c-suggest-improve:`endian.c` - * :c-better-explain:`endian.rst` diff --git a/source/cprogramming/eratosthenes.rst b/source/cprogramming/eratosthenes.rst deleted file mode 100644 index 7c7c4102..00000000 --- a/source/cprogramming/eratosthenes.rst +++ /dev/null @@ -1,16 +0,0 @@ -============ -eratosthenes -============ - -*eratosthenes.c* - -.. literalinclude:: ../../languages/cprogs/eratosthenes.c - :language: c - :tab-width: 4 - - - -.. seealso:: - - * :c-suggest-improve:`eratosthenes.c` - * :c-better-explain:`eratosthenes.rst` diff --git a/source/cprogramming/fork1.rst b/source/cprogramming/fork1.rst deleted file mode 100644 index 9e3b1e29..00000000 --- a/source/cprogramming/fork1.rst +++ /dev/null @@ -1,16 +0,0 @@ -===== -fork1 -===== - -*fork1.c* - -.. literalinclude:: ../../languages/cprogs/fork1.c - :language: c - :tab-width: 4 - - - -.. seealso:: - - * :c-suggest-improve:`fork1.c` - * :c-better-explain:`fork1.rst` diff --git a/source/cprogramming/fsize.rst b/source/cprogramming/fsize.rst deleted file mode 100644 index 406b98c0..00000000 --- a/source/cprogramming/fsize.rst +++ /dev/null @@ -1,16 +0,0 @@ -===== -fsize -===== - -*fsize.c* - -.. literalinclude:: ../../languages/cprogs/fsize.c - :language: c - :tab-width: 4 - - - -.. seealso:: - - * :c-suggest-improve:`fsize.c` - * :c-better-explain:`fsize.rst` diff --git a/source/cprogramming/getbits.rst b/source/cprogramming/getbits.rst deleted file mode 100644 index f22fae88..00000000 --- a/source/cprogramming/getbits.rst +++ /dev/null @@ -1,16 +0,0 @@ -======= -getbits -======= - -*getbits.c* - -.. literalinclude:: ../../languages/cprogs/getbits.c - :language: c - :tab-width: 4 - - - -.. seealso:: - - * :c-suggest-improve:`getbits.c` - * :c-better-explain:`getbits.rst` diff --git a/source/cprogramming/getline_woandr.rst b/source/cprogramming/getline_woandr.rst deleted file mode 100644 index ef4e0f8f..00000000 --- a/source/cprogramming/getline_woandr.rst +++ /dev/null @@ -1,17 +0,0 @@ -============== -getline_woandr -============== - -*getline_woandr.c* - -.. literalinclude:: ../../languages/cprogs/getline_woandr.c - :language: c - :tab-width: 4 - - - - -.. seealso:: - - * :c-suggest-improve:`getline_woandr.c` - * :c-better-explain:`getline_woandr.rst` diff --git a/source/cprogramming/getpass1.rst b/source/cprogramming/getpass1.rst deleted file mode 100644 index 543b8a66..00000000 --- a/source/cprogramming/getpass1.rst +++ /dev/null @@ -1,16 +0,0 @@ -======== -getpass1 -======== - -*getpass1.c* - -.. literalinclude:: ../../languages/cprogs/getpass1.c - :language: c - :tab-width: 4 - - - -.. seealso:: - - * :c-suggest-improve:`getpass1.c` - * :c-better-explain:`getpass1.rst` diff --git a/source/cprogramming/glat17.rst b/source/cprogramming/glat17.rst deleted file mode 100644 index 47d1362d..00000000 --- a/source/cprogramming/glat17.rst +++ /dev/null @@ -1,16 +0,0 @@ -====== -glat17 -====== - -*glat17.c* - -.. literalinclude:: ../../languages/cprogs/glat17.c - :language: c - :tab-width: 4 - - - -.. seealso:: - - * :c-suggest-improve:`glat17.c` - * :c-better-explain:`glat17.rst` diff --git a/source/cprogramming/index.rst b/source/cprogramming/index.rst deleted file mode 100644 index cbd7b077..00000000 --- a/source/cprogramming/index.rst +++ /dev/null @@ -1,184 +0,0 @@ -============= -C Programming -============= - -This is the C programming language section. Our intention is to present the programs of Kernighan and Ritchie here with explanation. -If you like that book or like to learn C, you may find this interesting. - - -Chapter 1. A Tutorial Introduction -================================== - -.. toctree:: - :maxdepth: 1 - - sec_1.1_helloworld - Ex_1.1_exp_helloworld - Ex_1.2_exp_printf_c - sec_1.2_fahr2cel - Ex_1.3_fahr2celheading - Ex_1.4_cel2fahr - sec_1.3_for_loop - Ex_1.5_reverse - sec_1.4_symbolic - sec_1.5_inp2ou - sec_1.5.1_File_Copying - Ex_1.6_verifyeof - Ex_1.7_eofval - sec_1.5.2_Character_Counting - sec_1.5.2_Character_Counting2 - sec_1.5.3_line_counting - Ex_1.8_count_blanks_etc - Ex_1.9_SinBlank - Ex_1.10_TbsBlnkSpaces - sec_1.5.4_word_counting - Ex_1.11_test_word_count - Ex_1.12_word_per_line - sec_1.6_arrays - Ex_1.13_His_Horizontal - Ex_1.13.2_His_vertical - Ex_1.14_Hist_Freq - sec_1.7_functions - Ex_1.15_tempconv - sec_1.9_character_arrays - Ex_1.16_LongLine - Ex_1.17_lengt80 - Ex_1.18_remtrailbt - Ex_1.19_reversestr - sec_1.10_external_variables - Ex_1.20_detab - Ex_1.21_entab - Ex_1.22_fold - Ex_1.23_remcomments - Ex_1.24_synerrors - -Chapter 2. Types, Operators and Expressions -=========================================== - -.. toctree:: - :maxdepth: 1 - - Ex_2.1_cal_limits - Ex_2.2_getline_without_and_or - Ex_2.3_htoi - Ex_2.4_squeezess - Ex_2.5_any - Ex_2.6_setbits - Ex_2.7_invert - Ex_2.8_rightrot - Ex_2.9_bitcount2s - Ex_2.10_lowercondit - -Chapter 3. Control Flow -======================= - -.. toctree:: - :maxdepth: 1 - - Ex_3.1_binsearch-2 - Ex_3.2_escape - Ex_3.3_expand - Ex_3.4_itoa-2 - Ex_3.5_itob - Ex_3.6_itoa-3 - -Chapter 4. Functions and Program Structure -========================================== - -.. toctree:: - :maxdepth: 1 - - sec_4.1 - Ex_4.1_strindex_rightmost - sec_4.2 - Ex_4.2_atof_scientific - sec_4.3 - Ex_4.3_rpn_modulus_negative - Ex_4.4_rpn_top_two_elements - Ex_4.5_calculator_math_functions - Ex_4.6_calculator_variables - Ex_4.7_ungets - Ex_4.8_getch_ungetch_pushback - Ex_4.9_getch_ungetch_eof - Ex_4.10_calculator_getline - Ex_4.11_getch_static - Ex_4.12_recursive_itoa - Ex_4.13_reverse_string - Ex_4.14_swap_t_x_y - -Chapter 5. Pointers and Arrays -============================== - -.. toctree:: - :maxdepth: 1 - - - Ex_5.1_getint - Ex_5.2_getfloat - Ex_5.3_strcat - Ex_5.4_strend - Ex_5.5_strncpy - Ex_5.6_findpattern - sec_5.6_pointer_arrays - Ex_5.7_readlines_using_array - Ex_5.8_day_date - Ex_5.9_day_date_using_pointers - Ex_5.10_exprcmd - Ex_5.11_conddetab - Ex_5.12_condientab - Ex_5.13_tailn - Ex_5.14_sortrevnum - Ex_5.15_sortfnr - Ex_5.16_sort_dfnr - Ex_5.17_sortdfnr-withoption - Ex_5.18_dcl-errorec - Ex_5.19_undcl - Ex_5.20_dcl-funcargs - -Chapter 6. Structures -===================== - -.. toctree:: - :maxdepth: 1 - - Ex_6.1_getword - Ex_6.2_identical_variables - sec_6.3_getword - Ex_6.3 - Ex_6.4 - Ex_6.5 - Ex_6.6 - -Chapter 7. Input and Output -=========================== - -.. toctree:: - :maxdepth: 1 - - Ex_7.1_lower-upper - Ex_7.2_nongraphic - Ex_7.3_minprintf - Ex_7.4 - Ex_7.5 - Ex_7.6 - Ex_7.7 - Ex_7.8 - Ex_7.9 - -Chapter 8. The Unix System Interface -==================================== - -.. toctree:: - :maxdepth: 1 - - sec_8.2_read_write - sec_8.2_getchar - sec_8.3_open_creat - Ex_8.1_mycat - Ex_8.2 - Ex_8.3 - Ex_8.4 - Ex_8.5_fsize - Ex_8.6_calloc - Ex_8.7_malloc - Ex_8.8_bfree diff --git a/source/cprogramming/leap.rst b/source/cprogramming/leap.rst deleted file mode 100644 index d19f6de4..00000000 --- a/source/cprogramming/leap.rst +++ /dev/null @@ -1,16 +0,0 @@ -==== -leap -==== - -*leap.c* - -.. literalinclude:: ../../languages/cprogs/leap.c - :language: c - :tab-width: 4 - - - -.. seealso:: - - * :c-suggest-improve:`leap.c` - * :c-better-explain:`leap.rst` diff --git a/source/cprogramming/likefind.rst b/source/cprogramming/likefind.rst deleted file mode 100644 index 8baf69a6..00000000 --- a/source/cprogramming/likefind.rst +++ /dev/null @@ -1,16 +0,0 @@ -======== -likefind -======== - -*likefind.c* - -.. literalinclude:: ../../languages/cprogs/likefind.c - :language: c - :tab-width: 4 - - - -.. seealso:: - - * :c-suggest-improve:`likefind.c` - * :c-better-explain:`likefind.rst` diff --git a/source/cprogramming/likegrep.rst b/source/cprogramming/likegrep.rst deleted file mode 100644 index 9d987003..00000000 --- a/source/cprogramming/likegrep.rst +++ /dev/null @@ -1,16 +0,0 @@ -======== -likegrep -======== - -*likegrep.c* - -.. literalinclude:: ../../languages/cprogs/likegrep.c - :language: c - :tab-width: 4 - - - -.. seealso:: - - * :c-suggest-improve:`likegrep.c` - * :c-better-explain:`likegrep.rst` diff --git a/source/cprogramming/long_extnal.rst b/source/cprogramming/long_extnal.rst deleted file mode 100644 index 94871862..00000000 --- a/source/cprogramming/long_extnal.rst +++ /dev/null @@ -1,16 +0,0 @@ -=========== -long_extnal -=========== - -*long_extnal.c* - -.. literalinclude:: ../../languages/cprogs/long_extnal.c - :language: c - :tab-width: 4 - - - -.. seealso:: - - * :c-suggest-improve:`long_extnal.c` - * :c-better-explain:`long_extnal.rst` diff --git a/source/cprogramming/makedir.rst b/source/cprogramming/makedir.rst deleted file mode 100644 index 601e02cb..00000000 --- a/source/cprogramming/makedir.rst +++ /dev/null @@ -1,14 +0,0 @@ -======= -makedir -======= - -*makedir.c* - -.. literalinclude:: ../../languages/cprogs/makedir.c - :tab-width: 4 - - -.. seealso:: - - * :c-suggest-improve:`makedir.c` - * :c-better-explain:`makedir.rst` diff --git a/source/cprogramming/mygetchar.rst b/source/cprogramming/mygetchar.rst deleted file mode 100644 index 14b28219..00000000 --- a/source/cprogramming/mygetchar.rst +++ /dev/null @@ -1,16 +0,0 @@ -========= -mygetchar -========= - -*mygetchar.c* - -.. literalinclude:: ../../languages/cprogs/mygetchar.c - :language: c - :tab-width: 4 - - - -.. seealso:: - - * :c-suggest-improve:`mygetchar.c` - * :c-better-explain:`mygetchar.rst` diff --git a/source/cprogramming/numlinesort.rst b/source/cprogramming/numlinesort.rst deleted file mode 100644 index 821fa69a..00000000 --- a/source/cprogramming/numlinesort.rst +++ /dev/null @@ -1,16 +0,0 @@ -=========== -numlinesort -=========== - -*numlinesort.c* - -.. literalinclude:: ../../languages/cprogs/numlinesort.c - :language: c - :tab-width: 4 - - - -.. seealso:: - - * :c-suggest-improve:`numlinesort.c` - * :c-better-explain:`numlinesort.rst` diff --git a/source/cprogramming/pgechov1.rst b/source/cprogramming/pgechov1.rst deleted file mode 100644 index 7fc5f7b2..00000000 --- a/source/cprogramming/pgechov1.rst +++ /dev/null @@ -1,16 +0,0 @@ -======== -pgechov1 -======== - -*pgechov1.c* - -.. literalinclude:: ../../languages/cprogs/pgechov1.c - :language: c - :tab-width: 4 - - - -.. seealso:: - - * :c-suggest-improve:`pgechov1.c` - * :c-better-explain:`pgechov1.rst` diff --git a/source/cprogramming/pgechov2.rst b/source/cprogramming/pgechov2.rst deleted file mode 100644 index f57a3e79..00000000 --- a/source/cprogramming/pgechov2.rst +++ /dev/null @@ -1,16 +0,0 @@ -======== -pgechov2 -======== - -*pgechov2.c* - -.. literalinclude:: ../../languages/cprogs/pgechov2.c - :language: c - :tab-width: 4 - - - -.. seealso:: - - * :c-suggest-improve:`pgechov2.c` - * :c-better-explain:`pgechov2.rst` diff --git a/source/cprogramming/pgechov3.rst b/source/cprogramming/pgechov3.rst deleted file mode 100644 index 5be5e980..00000000 --- a/source/cprogramming/pgechov3.rst +++ /dev/null @@ -1,16 +0,0 @@ -======== -pgechov3 -======== - -*pgechov3.c* - -.. literalinclude:: ../../languages/cprogs/pgechov3.c - :language: c - :tab-width: 4 - - - -.. seealso:: - - * :c-suggest-improve:`pgechov3.c` - * :c-better-explain:`pgechov3.rst` diff --git a/source/cprogramming/pick_random.sh b/source/cprogramming/pick_random.sh new file mode 100755 index 00000000..02355d6f --- /dev/null +++ b/source/cprogramming/pick_random.sh @@ -0,0 +1,2 @@ +#!/bin/sh +find . -type f -print0 -name "*.c" | xargs --null shuf -n1 -e diff --git a/source/cprogramming/prepro1.rst b/source/cprogramming/prepro1.rst deleted file mode 100644 index b6765f4e..00000000 --- a/source/cprogramming/prepro1.rst +++ /dev/null @@ -1,16 +0,0 @@ -======= -prepro1 -======= - -*prepro1.c* - -.. literalinclude:: ../../languages/cprogs/prepro1.c - :language: c - :tab-width: 4 - - - -.. seealso:: - - * :c-suggest-improve:`prepro1.c` - * :c-better-explain:`prepro1.rst` diff --git a/source/cprogramming/prepro2.rst b/source/cprogramming/prepro2.rst deleted file mode 100644 index f3257424..00000000 --- a/source/cprogramming/prepro2.rst +++ /dev/null @@ -1,16 +0,0 @@ -======= -prepro2 -======= - -*prepro2.c* - -.. literalinclude:: ../../languages/cprogs/prepro2.c - :language: c - :tab-width: 4 - - - -.. seealso:: - - * :c-suggest-improve:`prepro2.c` - * :c-better-explain:`prepro2.rst` diff --git a/source/cprogramming/printd.rst b/source/cprogramming/printd.rst deleted file mode 100644 index 6fe0a41c..00000000 --- a/source/cprogramming/printd.rst +++ /dev/null @@ -1,16 +0,0 @@ -====== -printd -====== - -*printd.c* - -.. literalinclude:: ../../languages/cprogs/printd.c - :language: c - :tab-width: 4 - - - -.. seealso:: - - * :c-suggest-improve:`printd.c` - * :c-better-explain:`printd.rst` diff --git a/source/cprogramming/quicksort.rst b/source/cprogramming/quicksort.rst deleted file mode 100644 index 2e14c8d5..00000000 --- a/source/cprogramming/quicksort.rst +++ /dev/null @@ -1,16 +0,0 @@ -========= -quicksort -========= - -*quicksort.c* - -.. literalinclude:: ../../languages/cprogs/quicksort.c - :language: c - :tab-width: 4 - - - -.. seealso:: - - * :c-suggest-improve:`quicksort.c` - * :c-better-explain:`quicksort.rst` diff --git a/source/cprogramming/rot13.rst b/source/cprogramming/rot13.rst deleted file mode 100644 index daf33d5d..00000000 --- a/source/cprogramming/rot13.rst +++ /dev/null @@ -1,15 +0,0 @@ -===== -rot13 -===== - -*rot13.c* - -.. literalinclude:: ../../languages/cprogs/rot13.c - :language: c - :tab-width: 4 - - -.. seealso:: - - * :c-suggest-improve:`rot13.c` - * :c-better-explain:`rot13.rst` diff --git a/source/cprogramming/sec_1.10_external_variables.rst b/source/cprogramming/sec_1.10_external_variables.rst deleted file mode 100644 index 84ba909e..00000000 --- a/source/cprogramming/sec_1.10_external_variables.rst +++ /dev/null @@ -1,37 +0,0 @@ -========================================= -Section 1.10 External Variables and Scope -========================================= - -Program -======= - -.. literalinclude:: ../../languages/cprogs/sec_1.10_external_variables.c - :language: c - :tab-width: 4 - -.. runcode:: ../../languages/cprogs/sec_1.10_external_variables.c - :language: c - :codesite: ideone - - - -Explanation -=========== - -This program is same as finding the length of the longest line. The special -thing here is we use external variables declared outside of any functions in the -program and reference them within the functions by using the type **extern**. -Here we see the integer max, strings line and longest declared outside of the -main function, and those variables are referenced using **extern** type in main, -getline and in copy function so that all these functions act upon the same -variable. That is the reason, unlike the previous programs, we do not send the -line and the longest as arguments to getline and copy, and neither we have to -return the length from getline, because sharing of those is accomplished by -sharing of the variable themselves. - - - -.. seealso:: - - * :c-suggest-improve:`sec_1.10_external_variables.c` - * :c-better-explain:`sec_1.10_external_variables.rst` diff --git a/source/cprogramming/sec_1.1_helloworld.rst b/source/cprogramming/sec_1.1_helloworld.rst deleted file mode 100644 index a172c37b..00000000 --- a/source/cprogramming/sec_1.1_helloworld.rst +++ /dev/null @@ -1,36 +0,0 @@ -=========================== -Section 1.1 Getting Started -=========================== - -Hello World -=========== - - -Question -======== - -The only way to learn a new programming language is by writing programs in it. -The first program to write is the same for all languages: -Print the words - - -Solution -======== - -.. literalinclude:: ../../languages/cprogs/sec_1.1_helloworld.c - :language: c - :tab-width: 4 - - -Understand ----------- - -.. raw:: html - - - - -.. seealso:: - - * :c-suggest-improve:`sec_1.1_helloworld.c` - * :c-better-explain:`sec_1.1_helloworld.rst` diff --git a/source/cprogramming/sec_1.2_fahr2cel.rst b/source/cprogramming/sec_1.2_fahr2cel.rst deleted file mode 100644 index 1b69a0a1..00000000 --- a/source/cprogramming/sec_1.2_fahr2cel.rst +++ /dev/null @@ -1,54 +0,0 @@ -================================================ -Section 1.2 Variables and Arithmetic Expressions -================================================ - - -Question -======== - -This program uses the formula `C=(5/9)(F-32)` to print the Fahrenheit -temperatures and their centigrade or Celsius equivalents. - - -Program -======= - -.. literalinclude:: ../../languages/cprogs/sec_1.2_fahr2cel.c - :language: c - :tab-width: 4 - - -Explanation -=========== - -In this program we are going to convert a given Fahrenheit temperature to -Celsius temperature using the formula C=(5/9)(F-32) To do this we declare some -variables in the beginning of the program so that they can be used in the later -stages of the program. The variables in this program are: lower,upper,step, -celsius,fahr. - - -The variable lower is assigned the value 0 similarly upper to 300, step to 20, -and fahr to lower. So when the program enters the while loop it checks whether -fahr <= upper is true if it is true then it assigns the variable celsius 5 * -(fahr - 32) / 9 and then it prints out put. - - -Understand ----------- - -.. raw:: html - - - - ----- - -.. seealso:: - - * :c-suggest-improve:`sec_1.2_fahr2cel.c` - * :c-better-explain:`sec_1.2_fahr2cel.rst` - ----- - -This document was updated on |today| diff --git a/source/cprogramming/sec_1.3_for_loop.rst b/source/cprogramming/sec_1.3_for_loop.rst deleted file mode 100644 index 7f07826a..00000000 --- a/source/cprogramming/sec_1.3_for_loop.rst +++ /dev/null @@ -1,39 +0,0 @@ -============================= -Section 1.3 The for statement -============================= - - -Question -======== - -There are plenty of different ways to write a program for a particular task. -Let's try a variation on the temperature converter using for loop. - - -Program -======= - -.. literalinclude:: ../../languages/cprogs/sec_1.3_for_loop.c - :language: c - :tab-width: 4 - - -.. runcode:: ../../languages/cprogs/sec_1.3_for_loop.c - :language: c - :codesite: ideone - -Explanation -=========== - -In this program we are going to convert a given Fahrenheit temperature to -Celsius temperature using the formula C=(5/9)(F-32) using a for loop :: - - for (fahr = 0; fahr <= 300; fahr = fahr + 20) - printf("%3d %6.1f\n", fahr, (5.0/9.0)*(fahr-32)); - - - -.. seealso:: - - * :c-suggest-improve:`sec_1.3_for_loop.c` - * :c-better-explain:`sec_1.3_for_loop.rst` diff --git a/source/cprogramming/sec_1.4_symbolic.rst b/source/cprogramming/sec_1.4_symbolic.rst deleted file mode 100644 index 20092a95..00000000 --- a/source/cprogramming/sec_1.4_symbolic.rst +++ /dev/null @@ -1,39 +0,0 @@ -============================== -Section 1.4 Symbolic Constants -============================== - -Program -======= - -.. literalinclude:: ../../languages/cprogs/sec_1.4_symbolic.c - :language: c - :tab-width: 4 - -.. runcode:: ../../languages/cprogs/sec_1.4_symbolic.c - :language: c - :codesite: ideone - -Explanation -=========== - -In this program we are going to convert a given Fahrenheit temperature to -Celsius temperature using the formula C=(5/9)(F-32). We define some some -**symbolic constants** in the beginning of the program so that they can be used -in the later stages of the program. The constants that are defined in the program are: -LOWER,UPPER,STEP, . The label LOWER is assigned the value 0 similarly UPPER -to 300, STEP to 20. So when the program enters the for loop it checks whether -fahr <= UPPER, and the increments fahr using STEP in each iteration. - -*symbolic constants* are substituted inline in the program during pre-processing -phase of compilation. - - - -.. seealso:: - - * :c-suggest-improve:`sec_1.4_symbolic.c` - * :c-better-explain:`sec_1.4_symbolic.rst` - ----- - -This document was updated on |today| diff --git a/source/cprogramming/sec_1.5.1_File_Copying.rst b/source/cprogramming/sec_1.5.1_File_Copying.rst deleted file mode 100644 index 7e700a18..00000000 --- a/source/cprogramming/sec_1.5.1_File_Copying.rst +++ /dev/null @@ -1,30 +0,0 @@ -========================== -Section 1.5.1 File Copying -========================== - -Program -------- - - -.. literalinclude:: ../../languages/cprogs/sec_1.5.1_File_Copying.c - :language: c - :tab-width: 4 - -.. runcode:: ../../languages/cprogs/sec_1.5.1_File_Copying.c - :language: c - :codesite: ideone - - -Explanation ------------ - - - -.. seealso:: - - * :c-suggest-improve:`sec_1.5.1_File_Copying.c` - * :c-better-explain:`sec_1.5.1_File_Copying.rst` - ----- - -This document was updated on |today| diff --git a/source/cprogramming/sec_1.5.2_Character_Counting.rst b/source/cprogramming/sec_1.5.2_Character_Counting.rst deleted file mode 100644 index f04f4a00..00000000 --- a/source/cprogramming/sec_1.5.2_Character_Counting.rst +++ /dev/null @@ -1,35 +0,0 @@ -================================ -Section 1.5.2 Character Counting -================================ - - -Program -------- - - -.. literalinclude:: ../../languages/cprogs/sec_1.5.2_Character_Counting.c - :language: c - :tab-width: 4 - -.. runcode:: ../../languages/cprogs/sec_1.5.2_Character_Counting.c - :language: c - :codesite: ideone - -Explanation ------------ - -In this program we are going to count the number of characters present in the -input. The program does the counting by setting nc to 0 in the beginning. As the -program enters while loop condition (getchar() != EOF). When nc hits end of the -document it prints the number of characters in the file. - - - -.. seealso:: - - * :c-suggest-improve:`sec_1.5.2_Character_Counting.c` - * :c-better-explain:`sec_1.5.2_Character_Counting.rst` - ----- - -This document was updated on |today| diff --git a/source/cprogramming/sec_1.5.2_Character_Counting2.rst b/source/cprogramming/sec_1.5.2_Character_Counting2.rst deleted file mode 100644 index b3ceb925..00000000 --- a/source/cprogramming/sec_1.5.2_Character_Counting2.rst +++ /dev/null @@ -1,35 +0,0 @@ -================================= -Section 1.5.2 Character Counting2 -================================= - - -Program -------- - - -.. literalinclude:: ../../languages/cprogs/sec_1.5.2_Character_Counting2.c - :language: c - :tab-width: 4 - -.. runcode:: ../../languages/cprogs/sec_1.5.2_Character_Counting2.c - :language: c - :codesite: ideone - -Explanation ------------ - -In this program we are going to count the number of characters present in the -input. The program does the counting by setting nc to 0 in the beginning. As the -program enters for loop condition (nc = 0; getchar() != EOF; ++nc). When nc -hits end of the document it prints the number of characters in the file. - - - -.. seealso:: - - * :c-suggest-improve:`sec_1.5.2_Character_Counting2.c` - * :c-better-explain:`sec_1.5.2_Character_Counting2.rst` - ----- - -This document was updated on |today| diff --git a/source/cprogramming/sec_1.5.3_line_counting.rst b/source/cprogramming/sec_1.5.3_line_counting.rst deleted file mode 100644 index 3fd36ab5..00000000 --- a/source/cprogramming/sec_1.5.3_line_counting.rst +++ /dev/null @@ -1,34 +0,0 @@ -=========================== -Section 1.5.3 Line Counting -=========================== - -Program -======= - -.. literalinclude:: ../../languages/cprogs/sec_1.5.3_line_counting.c - :language: c - :tab-width: 4 - -.. runcode:: ../../languages/cprogs/sec_1.5.3_line_counting.c - :language: c - :codesite: ideone - -Explanation -=========== - -This Program counts input lines. The program does that counting by setting a -variable nl to 0 in the beginning. As the program one character at a time in -the while loop ((c = getchar()) != EOF) till the EOF. If the character is -newline character '\n' the number of lines variable is incremented, ++nl. At the -end, the number of lines, nl, is printed. - - - -.. seealso:: - - * :c-suggest-improve:`sec_1.5.3_line_counting.c` - * :c-better-explain:`sec_1.5.3_line_counting.rst` - ----- - -This document was updated on |today| diff --git a/source/cprogramming/sec_1.5.4_word_counting.rst b/source/cprogramming/sec_1.5.4_word_counting.rst deleted file mode 100644 index c5a7f994..00000000 --- a/source/cprogramming/sec_1.5.4_word_counting.rst +++ /dev/null @@ -1,38 +0,0 @@ -=========================== -Section 1.5.4 Word Counting -=========================== - - -Program -======= - -.. literalinclude:: ../../languages/cprogs/sec_1.5.4_word_counting.c - :language: c - :tab-width: 4 - -.. runcode:: ../../languages/cprogs/sec_1.5.4_word_counting.c - :language: c - :codesite: ideone - -Explanation -=========== - -We need to count the number of characters, the number of words and the newlines -in the program. We store the characters in a variable `c`, it's count in nc, the -count of newlines in `nl` and the number of words in `nw`. In order to count the -words, the trick is to know when we enter the word and when we exit the word. -This is kept track by a `state` variable. - -We start with OUTSIDE a word, if we hit a whitespace (' ', \t or \n), we say, we -are outside the word (`state` = OUT). When we read a character again which is -not a whitespace and if were in OUT state earlier, we move to IN state (that is -we saw a new word) and we increment `nw`. For every character we read, we -increment `nc` and for every `\n` we read, we increment `nl`. The program in -the end prints, the *nl*, *nw* and *nc*. - - - -.. seealso:: - - * :c-suggest-improve:`sec_1.5.4_word_counting.c` - * :c-better-explain:`sec_1.5.4_word_counting.rst` diff --git a/source/cprogramming/sec_1.5_inp2ou.rst b/source/cprogramming/sec_1.5_inp2ou.rst deleted file mode 100644 index 720e339c..00000000 --- a/source/cprogramming/sec_1.5_inp2ou.rst +++ /dev/null @@ -1,36 +0,0 @@ -====================================== -Section 1.5 Character Input and Output -====================================== - -Program -------- - -.. literalinclude:: ../../languages/cprogs/sec_1.5_inp2ou.c - :language: c - :tab-width: 4 - -.. runcode:: ../../languages/cprogs/sec_1.5_inp2ou.c - :language: c - :codesite: ideone - -Explanation ------------ - -Input : In any programming language input means to feed some data into program. -This can be given in the form of file or from command line. C programming -language provides a set of built-in functions to read given input and feed it to -the program as per requirement. In this program getchar is a function of -reading the input from the user character by character. - -Output : In any programming language output means to display some data on -screen, printer or in any file. C programming language provides a set of built- -in functions to output required data. Similarly putchar is a function which -gives the output. - - - -.. seealso:: - - * :c-suggest-improve:`sec_1.5_inp2ou.c` - * :c-better-explain:`sec_1.5_inp2ou.rst` - diff --git a/source/cprogramming/sec_1.6_arrays.rst b/source/cprogramming/sec_1.6_arrays.rst deleted file mode 100644 index 3819dc42..00000000 --- a/source/cprogramming/sec_1.6_arrays.rst +++ /dev/null @@ -1,36 +0,0 @@ -================== -Section 1.6 Arrays -================== - - -Program -======= - -.. literalinclude:: ../../languages/cprogs/sec_1.6_arrays.c - :language: c - :tab-width: 4 - -.. runcode:: ../../languages/cprogs/sec_1.6_arrays.c - :language: c - :codesite: ideone - -Explanation -=========== - -This section introduces arrays. Arrays in C hold a number of same typed -variables into a one entity and are indexed by their position. In this program -it is demonstrated by holding the count of number of digits in the array `int -ndigit[10];` This program lets us count the digits, whitespace and others. -There are 10 digits, ranging from 0 to 9, so we create a array, ndigits which -can hold 10 digits. In the program we getchar() and for characters between '0' -and '9', we take it and substract '0' from it so that we can get the value and -we increment array index at that value. - -In the end, we print the values stored in the array. - - -.. seealso:: - - * :c-suggest-improve:`sec_1.6_arrays.c` - * :c-better-explain:`sec_1.6_arrays.rst` - diff --git a/source/cprogramming/sec_1.7_functions.rst b/source/cprogramming/sec_1.7_functions.rst deleted file mode 100644 index b52153ce..00000000 --- a/source/cprogramming/sec_1.7_functions.rst +++ /dev/null @@ -1,30 +0,0 @@ -===================== -Section 1.7 Functions -===================== - - -Program -======= - -.. literalinclude:: ../../languages/cprogs/sec_1.7_functions.c - :language: c - :tab-width: 4 - -.. runcode:: ../../languages/cprogs/sec_1.7_functions.c - :language: c - :codesite: ideone - -Explanation -=========== - -This program is a simple demonstration of functions. A function `power` is -declared to take two integer arguments and return an int value. In the program -we send a number, base and a number, n to power, and the program returns the -value of base raised to power n. - - - -.. seealso:: - - * :c-suggest-improve:`sec_1.7_functions.c` - * :c-better-explain:`sec_1.7_functions.rst` diff --git a/source/cprogramming/sec_1.9_character_arrays.rst b/source/cprogramming/sec_1.9_character_arrays.rst deleted file mode 100644 index 8a96b244..00000000 --- a/source/cprogramming/sec_1.9_character_arrays.rst +++ /dev/null @@ -1,35 +0,0 @@ -============================ -Section 1.9 Character Arrays -============================ - - -Program -======= - -.. literalinclude:: ../../languages/cprogs/sec_1.9_character_arrays.c - :language: c - :tab-width: 4 - -.. runcode:: ../../languages/cprogs/sec_1.9_character_arrays.c - :language: c - :codesite: ideone - - -Explanation -=========== - -In C, strings are nothing but a character arrays which end with a special -character `\0`. In this program, we declare character arrays `char line[]` in -the geline function and then `char to[]` and `char from[]` in the copy function. -Since arrays are passed by **reference**, so when we send `to` and `from` the -calling program, the function copies the contents to the `to` array and we are -reference the `to` array further from the main program itself. This is -demonstrated by copying line to the longest and then printing the longest in the -main program. - - - -.. seealso:: - - * :c-suggest-improve:`sec_1.9_character_arrays.c` - * :c-better-explain:`sec_1.9_character_arrays.rst` diff --git a/source/cprogramming/sec_4.1.rst b/source/cprogramming/sec_4.1.rst deleted file mode 100644 index 5d40652e..00000000 --- a/source/cprogramming/sec_4.1.rst +++ /dev/null @@ -1,75 +0,0 @@ -======================================================= -Section 4.1 - Find the pattern in the line and print it -======================================================= - -Program -======= - - -.. literalinclude:: ../../languages/cprogs/sec_4.1.c - :language: c - :tab-width: 4 - - -.. runcode:: ../../languages/cprogs/sec_4.1.c - :language: c - :codesite: ideone - - -Explanation -=========== - -This program searches particular pattern in a given string. As per the program -we are going to search for the pattern **ould** and print the line which has the -same. - -Let us say that we give the input as:: - - This line would print - This line will not print - -The output would be:: - - This line would print - -As it contains the pattern **ould**. The curx of the program is in the strindex function. - -:: - - int strindex(char s[], char t[]) - { - int i, j, k; - for (i = 0; s[i] != '\0'; i++) { - for (j=i, k=0; t[k]!='\0' && s[j]==t[k]; j++, k++) - ; - if (k > 0 && t[k] == '\0') - return i; - } - return -1; - } - -Here we have the source string in **s** and target string in **t**. We start -taking each character in s and starting at the position of the character, we -check if the entire target string **t** is present in the string. - -The checking for the entire target is present is done by the second for loop and -the if statement.:: - - for(j=i, k=0; t[k]!='\0' && s[j]==t[k]; j++, k++) - ; - if (k > 0 && t[k] == '\0') - return i; - -In the first for loop we use a temperorary variable k to iterate through and -check if the target string **t** is present in **s**. If the target string is -entirely present, which is ensured by if statement checking for `\0`, we return -the position **i**. - -In the main program, if we find the position greater than 0, we print the line. - - - -.. seealso:: - - * :c-suggest-improve:`sec_4.1.c` - * :c-better-explain:`sec_4.1.rst` diff --git a/source/cprogramming/sec_4.2.rst b/source/cprogramming/sec_4.2.rst deleted file mode 100644 index 1001047a..00000000 --- a/source/cprogramming/sec_4.2.rst +++ /dev/null @@ -1,37 +0,0 @@ -============================================= -Section 4.2 - atof - convert string to double -============================================= - -Program -======= - - -.. literalinclude:: ../../languages/cprogs/sec_4.2.c - :language: c - :tab-width: 4 - - -.. runcode:: ../../languages/cprogs/sec_4.2.c - :language: c - :codesite: ideone - - -Explanation -=========== - -In this program, we do the float conversion, by capturing the entire input as -decimal first, following the same procedure as converting `atoi`, that is we -keep track of sign, get each character and multiply it's positional value by 10 -and store the output in a variable called `val`. - -Additionally, since it is float, after the decimal, for each decimal we store -the power value too as multiples of 10. For e.g 10.21 will be gotten as value = -1021 and power = 100, So that when we return, we can send as `1021/100`. We -multiply the final by the stored `sign` and return the result. - - - -.. seealso:: - - * :c-suggest-improve:`sec_4.2.c` - * :c-better-explain:`sec_4.2.rst` diff --git a/source/cprogramming/sec_4.3.rst b/source/cprogramming/sec_4.3.rst deleted file mode 100644 index 960b3024..00000000 --- a/source/cprogramming/sec_4.3.rst +++ /dev/null @@ -1,36 +0,0 @@ -================================================ -Section 4.3 - Reverse Polish Notation Calculator -================================================ - -Program -======= - -.. literalinclude:: ../../languages/cprogs/sec_4.3.c - :language: c - :tab-width: 4 - -.. runcode:: ../../languages/cprogs/sec_4.3.c - :language: c - :codesite: ideone - - -Explanation -=========== - -This program has number of helper functions like `getop`, `push` and `pop`, -which we use to the implement the reverse polish notation calculator. - -The function `getop` takes a string and determines if it is number. If it is a -number, both integer or decimal, it will store that number in the array and -return a flag `NUMBER` which states that number is found. It will push that -number to the stack. If it getop returns an operator like `+`, `-`, `*` or `/`, -it will `pop` two numbers out of the stack and operate on it. When it encounters -a `/`, it ensures that the second operand is not 0 and disallows. - - - - -.. seealso:: - - * :c-suggest-improve:`sec_4.3.c` - * :c-better-explain:`sec_4.3.rst` diff --git a/source/cprogramming/sec_5.6_pointer_arrays.rst b/source/cprogramming/sec_5.6_pointer_arrays.rst deleted file mode 100644 index b02739c9..00000000 --- a/source/cprogramming/sec_5.6_pointer_arrays.rst +++ /dev/null @@ -1,40 +0,0 @@ -=============================== -Section 5.6 - Pointer to Arrays -=============================== - -Let us a write a program that will sort a set of text lines in alphabetical -order, a stripped down version of unix sort program. - - -.. literalinclude:: ../../languages/cprogs/sec_5.6_pointer_arrays.c - :language: c - :tab-width: 4 - -.. runcode:: ../../languages/cprogs/sec_5.6_pointer_arrays.c - :language: c - :codesite: ideone - -Explanation -=========== - -In this program, Pointer to Arrays, we intend to a sort a list of lines which is -sent to the program as `char *lineptr[MAXLINES]`. The sort function uses a quick -sort procedure. - -If the lines are not sorted for the pointers, left and right, it starts by -swaping the left end with the middle:: - - swap(v,left,(left+right)/2); - -We assign left to last, and consider last as the pivot element. We sort in -ascending order the string from , the strings from left to pivot element, last -and then we recursively qsort(v, left, last-1) and qsort(v, last+1, right). - - - - -.. seealso:: - - * :c-suggest-improve:`sec_5.6_pointer_arrays.c` - * :c-better-explain:`sec_5.6_pointer_arrays.rst` - diff --git a/source/cprogramming/sec_6.3_getword.rst b/source/cprogramming/sec_6.3_getword.rst deleted file mode 100644 index 0e19fac4..00000000 --- a/source/cprogramming/sec_6.3_getword.rst +++ /dev/null @@ -1,26 +0,0 @@ -================================ -Section 6.3 Arrays of Structures -================================ - - -Program -======= - -.. literalinclude:: ../../languages/cprogs/sec_6.3_getword.c - :language: c - :tab-width: 4 - -.. runcode:: ../../languages/cprogs/sec_6.3_getword.c - :language: c - :codesite: ideone - - -Explanation -=========== - - - -.. seealso:: - - * :c-suggest-improve:`sec_6.3_getword.c` - * :c-better-explain:`sec_6.3_getword.rst` diff --git a/source/cprogramming/sec_8.2_getchar.rst b/source/cprogramming/sec_8.2_getchar.rst deleted file mode 100644 index e3429ea8..00000000 --- a/source/cprogramming/sec_8.2_getchar.rst +++ /dev/null @@ -1,59 +0,0 @@ -============================================= -Section 8.2 - Buffered and Unbuffered getchar -============================================= - -Question -======== - -Demonstrate buffered and unbuffered getchar using the system read function. - - -.. literalinclude:: ../../languages/cprogs/sec_8.2_getchar.c - :language: c - :tab-width: 4 - -.. runcode:: ../../languages/cprogs/sec_8.2_getchar.c - :language: c - :codesite: ideone - -Explanation -=========== - -The un-buffered getchar, uses the system read and stores each character that is read in a character, c -and returns the character `return (read(0, &c, 1) == 1) ? (unsigned char) c : EOF;` - -The buffered version of getchar, sets aside a buffer for reading the characters. - -:: - - static char buf[BUFSIZ]; - static char *bufp = buf; - -And reads each of the characters into the buffer, `read(0, buf, sizeof buf)` and then returns one character at a -time from the buffer. - -The later would be more efficient than the former one. - -To execute this program, give the input in the following manner. - - -:: - - stdin - this is buffered getchar x - this is unbuffered getchar x - - stdout - - this is buffered getchar - this is unbuffered getchar - - - - - -.. seealso:: - - * :c-suggest-improve:`sec_8.2_getchar.c` - * :c-better-explain:`sec_8.2_getchar.rst` - diff --git a/source/cprogramming/sec_8.2_read_write.rst b/source/cprogramming/sec_8.2_read_write.rst deleted file mode 100644 index c5e40c51..00000000 --- a/source/cprogramming/sec_8.2_read_write.rst +++ /dev/null @@ -1,30 +0,0 @@ -============================ -Section 8.2 - Read and Write -============================ - -Question -======== - -Copy input to output by using read and write system calls. - - -.. literalinclude:: ../../languages/cprogs/sec_8_2_read_write.c - :language: c - :tab-width: 4 - -.. runcode:: ../../languages/cprogs/sec_8_2_read_write.c - :language: c - :codesite: ideone - -Explanation -=========== - -This uses the read and write system calls to copy input to output. - - - -.. seealso:: - - * :c-suggest-improve:`sec_8_2_read_write.c` - * :c-better-explain:`sec_8_2_read_write.rst` - diff --git a/source/cprogramming/sec_8.3_open_creat.rst b/source/cprogramming/sec_8.3_open_creat.rst deleted file mode 100644 index 2aca9df5..00000000 --- a/source/cprogramming/sec_8.3_open_creat.rst +++ /dev/null @@ -1,32 +0,0 @@ -================================= -Section 8.3 open and create calls -================================= - -Question -======== - -Demonstrate the ``cp`` like program which copies the contents of one file to another. - - -.. literalinclude:: ../../languages/cprogs/sec_8.3_open_creat.c - :language: c - :tab-width: 4 - -.. runcode:: ../../languages/cprogs/sec_8.3_open_creat.c - :language: c - :codesite: ideone - - -Explanation -=========== - - - - - - -.. seealso:: - - * :c-suggest-improve:`sec_8.3_open_creat.c` - * :c-better-explain:`sec_8.3_open_creat.rst` - diff --git a/source/cprogramming/shellsort.rst b/source/cprogramming/shellsort.rst deleted file mode 100644 index 3007908f..00000000 --- a/source/cprogramming/shellsort.rst +++ /dev/null @@ -1,16 +0,0 @@ -========= -shellsort -========= - -*shellsort.c* - -.. literalinclude:: ../../languages/cprogs/shellsort.c - :language: c - :tab-width: 2 - - - -.. seealso:: - - * :c-suggest-improve:`shellsort.c` - * :c-better-explain:`shellsort.rst` diff --git a/source/cprogramming/sizeof_various.rst b/source/cprogramming/sizeof_various.rst deleted file mode 100644 index 815b386e..00000000 --- a/source/cprogramming/sizeof_various.rst +++ /dev/null @@ -1,16 +0,0 @@ -============== -sizeof_various -============== - -*sizeof_various.c* - -.. literalinclude:: ../../languages/cprogs/sizeof_various.c - :language: c - :tab-width: 4 - - - -.. seealso:: - - * :c-suggest-improve:`sizeof_various.c` - * :c-better-explain:`sizeof_various.rst` diff --git a/source/cprogramming/sort.rst b/source/cprogramming/sort.rst deleted file mode 100644 index 34ada364..00000000 --- a/source/cprogramming/sort.rst +++ /dev/null @@ -1,16 +0,0 @@ -==== -sort -==== - -*sort.c* - -.. literalinclude:: ../../languages/cprogs/sort.c - :language: c - :tab-width: 4 - - - -.. seealso:: - - * :c-suggest-improve:`sort.c` - * :c-better-explain:`sort.rst` diff --git a/source/cprogramming/sortv2.rst b/source/cprogramming/sortv2.rst deleted file mode 100644 index a7bf19ee..00000000 --- a/source/cprogramming/sortv2.rst +++ /dev/null @@ -1,16 +0,0 @@ -====== -sortv2 -====== - -*sortv2.c* - -.. literalinclude:: ../../languages/cprogs/sortv2.c - :language: c - :tab-width: 4 - - - -.. seealso:: - - * :c-suggest-improve:`sortv2.c` - * :c-better-explain:`sortv2.rst` diff --git a/source/cprogramming/squeezesc.rst b/source/cprogramming/squeezesc.rst deleted file mode 100644 index f3f672c5..00000000 --- a/source/cprogramming/squeezesc.rst +++ /dev/null @@ -1,16 +0,0 @@ -========= -squeezesc -========= - -*squeezesc.c* - -.. literalinclude:: ../../languages/cprogs/squeezesc.c - :language: c - :tab-width: 4 - - - -.. seealso:: - - * :c-suggest-improve:`squeezesc.c` - * :c-better-explain:`squeezesc.rst` diff --git a/source/cprogramming/unescape.rst b/source/cprogramming/unescape.rst deleted file mode 100644 index eb895cb6..00000000 --- a/source/cprogramming/unescape.rst +++ /dev/null @@ -1,16 +0,0 @@ -======== -unescape -======== - -*unescape.c* - -.. literalinclude:: ../../languages/cprogs/unescape.c - :language: c - :tab-width: 4 - - - -.. seealso:: - - * :c-suggest-improve:`unescape.c` - * :c-better-explain:`unescape.rst` diff --git a/source/cprogramming/val_limits.rst b/source/cprogramming/val_limits.rst deleted file mode 100644 index e6ba8261..00000000 --- a/source/cprogramming/val_limits.rst +++ /dev/null @@ -1,16 +0,0 @@ -========== -val_limits -========== - -*val_limits.c* - -.. literalinclude:: ../../languages/cprogs/val_limits.c - :language: c - :tab-width: 4 - - - -.. seealso:: - - * :c-suggest-improve:`val_limits.c` - * :c-better-explain:`val_limits.rst` diff --git a/source/cprogramming/wumpus.rst b/source/cprogramming/wumpus.rst deleted file mode 100644 index 6b1d0d3a..00000000 --- a/source/cprogramming/wumpus.rst +++ /dev/null @@ -1,16 +0,0 @@ -====== -wumpus -====== - -*wumpus.c* - On 26 Jun,2011. - -.. literalinclude:: ../../languages/cprogs/wumpus.c - :language: c - :tab-width: 4 - - - -.. seealso:: - - * :c-suggest-improve:`wumpus.c` - * :c-better-explain:`wumpus.rst` diff --git a/source/index.rst b/source/index.rst index dffe549f..a5ee9335 100644 --- a/source/index.rst +++ b/source/index.rst @@ -1,7 +1,7 @@ Learn To Solve It ================= -This is a companinon website to learn C programming using K&R book. +This is a companion website to learn C programming using K&R book. It uses modern tools, and is designed to be used along with the book. I recommend https://exercism.org as the platform to learn Programming and @@ -14,14 +14,6 @@ practice with a dedicated community. C Programming ============= -.. toctree:: - :maxdepth: 3 - - ./cprogramming/index.rst - -Revision -======== - .. toctree:: :maxdepth: 3 @@ -29,3 +21,8 @@ Revision ./cprogramming/chapter2/index.rst ./cprogramming/chapter3/index.rst ./cprogramming/chapter4/index.rst + ./cprogramming/chapter5/index.rst + ./cprogramming/chapter6/index.rst + ./cprogramming/chapter7/index.rst + ./cprogramming/chapter8/index.rst + ./cprogramming/concepts/concepts.rst diff --git a/source/python/algorithm_binary_representation.rst b/source/python/algorithm_binary_representation.rst deleted file mode 100644 index a88bcc52..00000000 --- a/source/python/algorithm_binary_representation.rst +++ /dev/null @@ -1,33 +0,0 @@ -===================== -Binary Representation -===================== - -Question --------- - -Write a program to display the binary representation of various integers. - - -Solution --------- - -.. literalinclude:: ../../languages/python/algorithm_binary_representation.py - :language: python3 - :tab-width: 4 - -.. runcode:: ../../languages/python/algorithm_binary_representation.py - :language: python3 - :codesite: ideone - -Explanation -=========== - - - - - -.. seealso:: - - * :python-suggest-improve:`algorithm_binary_representation.py` - * :python-better-explain:`algorithm_binary_representation.rst` - diff --git a/source/python/algorithm_binary_search.rst b/source/python/algorithm_binary_search.rst deleted file mode 100644 index 7e1c11c1..00000000 --- a/source/python/algorithm_binary_search.rst +++ /dev/null @@ -1,33 +0,0 @@ -============= -Binary Search -============= - -Question --------- - -Implement and demonstrate the Binary search algorithm. - - -Solution --------- - -.. literalinclude:: ../../languages/python/algorithm_binary_search.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/algorithm_binary_search.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - -.. seealso:: - - * :python-suggest-improve:`algorithm_binary_search.py` - * :python-better-explain:`algorithm_binary_search.rst` - diff --git a/source/python/algorithm_cellauto.rst b/source/python/algorithm_cellauto.rst deleted file mode 100644 index dbad12a2..00000000 --- a/source/python/algorithm_cellauto.rst +++ /dev/null @@ -1,36 +0,0 @@ -================= -Cellular Automata -================= - -Question --------- - -This generates a beautiful cellular automata pattern, following the rules of cellular automata evolution. - - -..image:: https://lh4.googleusercontent.com/_ny1HYbb2lDw/Tazon5TsgXI/AAAAAAAAKgU/ud6v_XhcHB0/s288/bs.png - - -Solution --------- - -.. literalinclude:: ../../languages/python/algorithm_cellauto.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/algorithm_cellauto.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - -.. seealso:: - - * :python-suggest-improve:`algorithm_cellauto.py` - * :python-better-explain:`algorithm_cellauto.rst` - diff --git a/source/python/algorithm_checking_string_text_or_binary.rst b/source/python/algorithm_checking_string_text_or_binary.rst deleted file mode 100644 index ac920bbe..00000000 --- a/source/python/algorithm_checking_string_text_or_binary.rst +++ /dev/null @@ -1,33 +0,0 @@ -============================== -Checking String Text Or Binary -============================== - -Question --------- - -Program to verify if a given stream of continous bytes represent a valid text (Human readable) or is it a binary (like image / video / audio). - - -Solution --------- - -.. literalinclude:: ../../languages/python/algorithm_checking_string_text_or_binary.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/algorithm_checking_string_text_or_binary.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - -.. seealso:: - - * :python-suggest-improve:`algorithm_checking_string_text_or_binary.py` - * :python-better-explain:`algorithm_checking_string_text_or_binary.rst` - diff --git a/source/python/algorithm_eratosthenes.rst b/source/python/algorithm_eratosthenes.rst deleted file mode 100644 index 1ca5652b..00000000 --- a/source/python/algorithm_eratosthenes.rst +++ /dev/null @@ -1,32 +0,0 @@ -================================== -Eratosthenes method to find primes -================================== - -Question --------- - -Illustrate the sieve of eratosthenes method to find out prime numbers. - -Solution --------- - -.. literalinclude:: ../../languages/python/algorithm_eratosthenes.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/algorithm_eratosthenes.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - -.. seealso:: - - * :python-suggest-improve:`algorithm_eratosthenes.py` - * :python-better-explain:`algorithm_eratosthenes.rst` - diff --git a/source/python/algorithm_fact2.rst b/source/python/algorithm_fact2.rst deleted file mode 100644 index 0eb286d3..00000000 --- a/source/python/algorithm_fact2.rst +++ /dev/null @@ -1,32 +0,0 @@ -========================= -Factorial of a number - 2 -========================= - -Question --------- - -Find the factorial (n!) of a number n. - -Solution --------- - -.. literalinclude:: ../../languages/python/algorithm_fact2.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/algorithm_fact2.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - -.. seealso:: - - * :python-suggest-improve:`algorithm_fact2.py` - * :python-better-explain:`algorithm_fact2.rst` - diff --git a/source/python/algorithm_fibo.rst b/source/python/algorithm_fibo.rst deleted file mode 100644 index 87ca79cb..00000000 --- a/source/python/algorithm_fibo.rst +++ /dev/null @@ -1,33 +0,0 @@ -================ -Fibonacci Series -================ - -Question --------- - -Implement Fibonacci Series. - - -Solution --------- - -.. literalinclude:: ../../languages/python/algorithm_fibo.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/algorithm_fibo.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - -.. seealso:: - - * :python-suggest-improve:`algorithm_fibo.py` - * :python-better-explain:`algorithm_fibo.rst` - diff --git a/source/python/algorithm_graph.rst b/source/python/algorithm_graph.rst deleted file mode 100644 index 9ad22dfe..00000000 --- a/source/python/algorithm_graph.rst +++ /dev/null @@ -1,32 +0,0 @@ -==================== -Representing a Graph -==================== - -Question --------- - -Represent a Graph of V nodes and E edges in Python. - -Solution --------- - -.. literalinclude:: ../../languages/python/algorithm_graph.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/algorithm_graph.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - -.. seealso:: - - * :python-suggest-improve:`algorithm_graph.py` - * :python-better-explain:`algorithm_graph.rst` - diff --git a/source/python/algorithm_hanoi.rst b/source/python/algorithm_hanoi.rst deleted file mode 100644 index 0223ba14..00000000 --- a/source/python/algorithm_hanoi.rst +++ /dev/null @@ -1,40 +0,0 @@ -=============== -Towers of Hanoi -=============== - -Question --------- - -Implement the Towers of Hanoi program. - - -Solution --------- - -.. literalinclude:: ../../languages/python/algorithm_hanoi.py - :language: python - :tab-width: 4 - - -Visualize ---------- - - -.. raw:: html - - - -Execute -------- - -.. raw:: html - - - - - - -.. seealso:: - - * :python-suggest-improve:`algorithm_hanoi.py` - * :python-better-explain:`algorithm_hanoi.rst` diff --git a/source/python/algorithm_insertion.rst b/source/python/algorithm_insertion.rst deleted file mode 100644 index 88c2ba91..00000000 --- a/source/python/algorithm_insertion.rst +++ /dev/null @@ -1,32 +0,0 @@ -============== -Insertion Sort -============== - -Question --------- - -Write a program to demonstrate Insertion Sort. - -Solution --------- - -.. literalinclude:: ../../languages/python/algorithm_insertion.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/algorithm_insertion.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - -.. seealso:: - - * :python-suggest-improve:`algorithm_insertion.py` - * :python-better-explain:`algorithm_insertion.rst` - diff --git a/source/python/algorithm_int_to_roman.rst b/source/python/algorithm_int_to_roman.rst deleted file mode 100644 index 05abac4a..00000000 --- a/source/python/algorithm_int_to_roman.rst +++ /dev/null @@ -1,32 +0,0 @@ -================ -Integer to Roman -================ - -Question --------- - -Write a program which converts the given input integer to roman numeral. - -Solution --------- - -.. literalinclude:: ../../languages/python/algorithm_int_to_roman.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/algorithm_int_to_roman.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - -.. seealso:: - - * :python-suggest-improve:`algorithm_int_to_roman.py` - * :python-better-explain:`algorithm_int_to_roman.rst` - diff --git a/source/python/algorithm_locate.rst b/source/python/algorithm_locate.rst deleted file mode 100644 index 31bfc8b6..00000000 --- a/source/python/algorithm_locate.rst +++ /dev/null @@ -1,32 +0,0 @@ -====== -Locate -====== - -Question --------- - -Write a program to locate a given file in the file system. - -Solution --------- - -.. literalinclude:: ../../languages/python/algorithm_locate.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/algorithm_locate.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - -.. seealso:: - - * :python-suggest-improve:`algorithm_locate.py` - * :python-better-explain:`algorithm_locate.rst` - diff --git a/source/python/algorithm_maxsort.rst b/source/python/algorithm_maxsort.rst deleted file mode 100644 index b8f15ac1..00000000 --- a/source/python/algorithm_maxsort.rst +++ /dev/null @@ -1,33 +0,0 @@ -=================================== -Maxsort - Selection Sort in reverse -=================================== - -Question --------- - -Demonstrate selection sort, but sort using the max value. - - -Solution --------- - -.. literalinclude:: ../../languages/python/algorithm_maxsort.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/algorithm_maxsort.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - -.. seealso:: - - * :python-suggest-improve:`algorithm_maxsort.py` - * :python-better-explain:`algorithm_maxsort.rst` - diff --git a/source/python/algorithm_mergesort.rst b/source/python/algorithm_mergesort.rst deleted file mode 100644 index 4b8944a9..00000000 --- a/source/python/algorithm_mergesort.rst +++ /dev/null @@ -1,32 +0,0 @@ -========= -Mergesort -========= - -Question --------- - -Demonstrate the merge sort sorting algorithm in Python. - -Solution --------- - -.. literalinclude:: ../../languages/python/algorithm_mergesort.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/algorithm_mergesort.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - -.. seealso:: - - * :python-suggest-improve:`algorithm_mergesort.py` - * :python-better-explain:`algorithm_mergesort.rst` - diff --git a/source/python/algorithm_npuzzle.rst b/source/python/algorithm_npuzzle.rst deleted file mode 100644 index 4c23b9ac..00000000 --- a/source/python/algorithm_npuzzle.rst +++ /dev/null @@ -1,32 +0,0 @@ -======= -Npuzzle -======= - -Question --------- - -Implement an N-Puzzle solver in Python. - -Solution --------- - -.. literalinclude:: ../../languages/python/algorithm_npuzzle.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/algorithm_npuzzle.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - -.. seealso:: - - * :python-suggest-improve:`algorithm_npuzzle.py` - * :python-better-explain:`algorithm_npuzzle.rst` - diff --git a/source/python/algorithm_pyex2_multiprocessing.rst b/source/python/algorithm_pyex2_multiprocessing.rst deleted file mode 100644 index a6aa7ca4..00000000 --- a/source/python/algorithm_pyex2_multiprocessing.rst +++ /dev/null @@ -1,32 +0,0 @@ -===================== -Pyex2 Multiprocessing -===================== - -Question --------- - -Compute the factorial of number. Demonstrate the use of multiprocessing. - -Solution --------- - -.. literalinclude:: ../../languages/python/algorithm_pyex2_multiprocessing.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/algorithm_pyex2_multiprocessing.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - -.. seealso:: - - * :python-suggest-improve:`algorithm_pyex2_multiprocessing.py` - * :python-better-explain:`algorithm_pyex2_multiprocessing.rst` - diff --git a/source/python/algorithm_pyex_multiprocessing.rst b/source/python/algorithm_pyex_multiprocessing.rst deleted file mode 100644 index 3c266478..00000000 --- a/source/python/algorithm_pyex_multiprocessing.rst +++ /dev/null @@ -1,32 +0,0 @@ -==================== -Pyex Multiprocessing -==================== - -Question --------- - -Compute the factorial of a number. Demonstrate use of multiprocessing Pool. - -Solution --------- - -.. literalinclude:: ../../languages/python/algorithm_pyex_multiprocessing.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/algorithm_pyex_multiprocessing.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - -.. seealso:: - - * :python-suggest-improve:`algorithm_pyex_multiprocessing.py` - * :python-better-explain:`algorithm_pyex_multiprocessing.rst` - diff --git a/source/python/algorithm_scrmable.rst b/source/python/algorithm_scrmable.rst deleted file mode 100644 index 3fd7e4d4..00000000 --- a/source/python/algorithm_scrmable.rst +++ /dev/null @@ -1,34 +0,0 @@ -======== -Scrmable -======== - -Question --------- - -Scramble the words in the sentence. - -Solution --------- - -.. literalinclude:: ../../languages/python/algorithm_scrmable.py - -Usage ------ - -* Create a file (input.txt) with some text. -* Run `python algorithm_scrmable.py < input.txt` - - -Explanation -=========== - -In a lauangge failaimr to you, if you keep the fisrt and the lsat ctehaacrr of -ecah wrod in the stnecnee, yuor can elsaiy raed the seenncte. - -This is one of my esirleat praorgm taht smees to hvae sviuevrd and still gveis joy! - - -.. seealso:: - - * :python-suggest-improve:`algorithm_scrmable.py` - * :python-better-explain:`algorithm_scrmable.rst` diff --git a/source/python/algorithm_spelling.rst b/source/python/algorithm_spelling.rst deleted file mode 100644 index 584e1760..00000000 --- a/source/python/algorithm_spelling.rst +++ /dev/null @@ -1,32 +0,0 @@ -=============== -Spell Corrector -=============== - -Question --------- - -Spell Corrector in Python. - -Solution --------- - -.. literalinclude:: ../../languages/python/algorithm_spelling.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/algorithm_spelling.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - -.. seealso:: - - * :python-suggest-improve:`algorithm_spelling.py` - * :python-better-explain:`algorithm_spelling.rst` - diff --git a/source/python/algorithm_splitter.rst b/source/python/algorithm_splitter.rst deleted file mode 100644 index 2a503722..00000000 --- a/source/python/algorithm_splitter.rst +++ /dev/null @@ -1,33 +0,0 @@ -============= -File Splitter -============= - -Question --------- - -Split a Big file into propotional chunks. - - -Solution --------- - -.. literalinclude:: ../../languages/python/algorithm_splitter.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/algorithm_splitter.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - -.. seealso:: - - * :python-suggest-improve:`algorithm_splitter.py` - * :python-better-explain:`algorithm_splitter.rst` - diff --git a/source/python/algorithm_syllablecount.rst b/source/python/algorithm_syllablecount.rst deleted file mode 100644 index e3772ccb..00000000 --- a/source/python/algorithm_syllablecount.rst +++ /dev/null @@ -1,32 +0,0 @@ -============= -Syllablecount -============= - -Question --------- - -TODO: Change to correct program. - -Solution --------- - -.. literalinclude:: ../../languages/python/algorithm_spelling.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/algorithm_spelling.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - -.. seealso:: - - * :python-suggest-improve:`algorithm_syllablecount.py` - * :python-better-explain:`algorithm_syllablecount.rst` - diff --git a/source/python/algorithm_toss_coins.rst b/source/python/algorithm_toss_coins.rst deleted file mode 100644 index e15292c9..00000000 --- a/source/python/algorithm_toss_coins.rst +++ /dev/null @@ -1,32 +0,0 @@ -========== -Toss Coins -========== - -Question --------- - -Tossing a fair coin and looking the probability of HEADS and TAILS - -Solution --------- - -.. literalinclude:: ../../languages/python/algorithm_toss_coins.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/algorithm_toss_coins.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - -.. seealso:: - - * :python-suggest-improve:`algorithm_toss_coins.py` - * :python-better-explain:`algorithm_toss_coins.rst` - diff --git a/source/python/algorithm_traversal.rst b/source/python/algorithm_traversal.rst deleted file mode 100644 index 5d3412d6..00000000 --- a/source/python/algorithm_traversal.rst +++ /dev/null @@ -1,33 +0,0 @@ -========= -Traversal -========= - -Question --------- - -Demonstrate Graph Traversal Algorithms. - - -Solution --------- - -.. literalinclude:: ../../languages/python/algorithm_traversal.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/algorithm_traversal.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - -.. seealso:: - - * :python-suggest-improve:`algorithm_traversal.py` - * :python-better-explain:`algorithm_traversal.rst` - diff --git a/source/python/algorithm_tree2.rst b/source/python/algorithm_tree2.rst deleted file mode 100644 index 764504b2..00000000 --- a/source/python/algorithm_tree2.rst +++ /dev/null @@ -1,32 +0,0 @@ -============== -Tree Traversal -============== - -Question --------- - -Demonstrate In-order, Pre-order and Post-order Tree traversal. - -Solution --------- - -.. literalinclude:: ../../languages/python/algorithm_tree2.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/algorithm_tree2.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - -.. seealso:: - - * :python-suggest-improve:`algorithm_tree2.py` - * :python-better-explain:`algorithm_tree2.rst` - diff --git a/source/python/design_args_kwargs.rst b/source/python/design_args_kwargs.rst deleted file mode 100644 index dd13ed69..00000000 --- a/source/python/design_args_kwargs.rst +++ /dev/null @@ -1,35 +0,0 @@ -=========== -Args Kwargs -=========== - -Question --------- - -Show the use of `*args` and `**kwargs` in a Python program. - - -Solution --------- - -.. literalinclude:: ../../languages/python/design_args_kwargs.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/design_args_kwargs.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`design_args_kwargs.py` - * :python-better-explain:`design_args_kwargs.rst` - diff --git a/source/python/design_ast_example1.rst b/source/python/design_ast_example1.rst deleted file mode 100644 index 8b8ce3bc..00000000 --- a/source/python/design_ast_example1.rst +++ /dev/null @@ -1,35 +0,0 @@ -============ -Ast Example1 -============ - -Question --------- - -Example of the Abstract Syntax Tree representation. - - -Solution --------- - -.. literalinclude:: ../../languages/python/design_ast_example1.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/design_ast_example1.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`design_ast_example1 .py` - * :python-better-explain:`design_ast_example1 .rst` - diff --git a/source/python/design_atexit_1.rst b/source/python/design_atexit_1.rst deleted file mode 100644 index 7ba0971a..00000000 --- a/source/python/design_atexit_1.rst +++ /dev/null @@ -1,34 +0,0 @@ -====== -Atexit -====== - -Question --------- - -Demonstrate *atexit* call using an example. - -Solution --------- - -.. literalinclude:: ../../languages/python/design_atexit_1.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/design_atexit_1.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`design_atexit_1.py` - * :python-better-explain:`design_atexit_1.rst` - diff --git a/source/python/design_caseinsensitivedict.rst b/source/python/design_caseinsensitivedict.rst deleted file mode 100644 index 1fc7382b..00000000 --- a/source/python/design_caseinsensitivedict.rst +++ /dev/null @@ -1,35 +0,0 @@ -=================== -caseinsensitivedict -=================== - -Question --------- - -Example of a case insensitive dictionary in Python. - - -Solution --------- - -.. literalinclude:: ../../languages/python/design_caseinsensitivedict.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/design_caseinsensitivedict.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`design_caseinsensitivedict.py` - * :python-better-explain:`design_caseinsensitivedict.rst` - diff --git a/source/python/design_closure1.rst b/source/python/design_closure1.rst deleted file mode 100644 index 6757b992..00000000 --- a/source/python/design_closure1.rst +++ /dev/null @@ -1,34 +0,0 @@ -======== -Closure1 -======== - -Question --------- - -Show an example of using closure using Python. - -Solution --------- - -.. literalinclude:: ../../languages/python/design_closure1.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/design_closure1.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`design_closure1.py` - * :python-better-explain:`design_closure1.rst` - diff --git a/source/python/design_closure_example1.rst b/source/python/design_closure_example1.rst deleted file mode 100644 index ec50f7da..00000000 --- a/source/python/design_closure_example1.rst +++ /dev/null @@ -1,34 +0,0 @@ -================= -Closure Example 1 -================= - -Question --------- - -Example of closure in Python. - -Solution --------- - -.. literalinclude:: ../../languages/python/design_closure_example1.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/design_closure_example1.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`design_closure_example1.py` - * :python-better-explain:`design_closure_example1.rst` - diff --git a/source/python/design_context_2.rst b/source/python/design_context_2.rst deleted file mode 100644 index 578638ff..00000000 --- a/source/python/design_context_2.rst +++ /dev/null @@ -1,35 +0,0 @@ -=============== -Context Manager -=============== - -Question --------- - -Using context manager - - -Solution --------- - -.. literalinclude:: ../../languages/python/design_context_2.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/design_context_2.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`design_context_2.py` - * :python-better-explain:`design_context_2.rst` - diff --git a/source/python/design_contextmanager.rst b/source/python/design_contextmanager.rst deleted file mode 100644 index b775c12a..00000000 --- a/source/python/design_contextmanager.rst +++ /dev/null @@ -1,35 +0,0 @@ -============== -contextmanager -============== - -Question --------- - -Example of a context manager. - - -Solution --------- - -.. literalinclude:: ../../languages/python/design_contextmanager.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/design_contextmanager.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`design_contextmanager.py` - * :python-better-explain:`design_contextmanager.rst` - diff --git a/source/python/design_contextmanager_ex.rst b/source/python/design_contextmanager_ex.rst deleted file mode 100644 index 48e2f6ab..00000000 --- a/source/python/design_contextmanager_ex.rst +++ /dev/null @@ -1,34 +0,0 @@ -================= -Contextmanager ex -================= - -Question --------- - -Making file open function as a context manager. - -Solution --------- - -.. literalinclude:: ../../languages/python/design_contextmanager_ex.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/design_contextmanager_ex.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`design_contextmanager_ex.py` - * :python-better-explain:`design_contextmanager_ex.rst` - diff --git a/source/python/design_decorator3.rst b/source/python/design_decorator3.rst deleted file mode 100644 index 9f994537..00000000 --- a/source/python/design_decorator3.rst +++ /dev/null @@ -1,32 +0,0 @@ -========= -Decorator -========= - - -Question --------- - -Decorator Example - -Solution --------- - -.. literalinclude:: ../../languages/python/design_decorator3.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/design_decorator3.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - -.. seealso:: - - * :python-suggest-improve:`design_decorator3.py` - * :python-better-explain:`design_decorator3.rst` diff --git a/source/python/design_ex_iterable27.rst b/source/python/design_ex_iterable27.rst deleted file mode 100644 index baca4a6d..00000000 --- a/source/python/design_ex_iterable27.rst +++ /dev/null @@ -1,34 +0,0 @@ -================ -Example Iterable -================ - -Question --------- - -Creating an Iterable in Python. - -Solution --------- - -.. literalinclude:: ../../languages/python/design_ex_iterable27.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/design_ex_iterable27.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`design_ex_iterable27.py` - * :python-better-explain:`design_ex_iterable27.rst` - diff --git a/source/python/design_func_args.rst b/source/python/design_func_args.rst deleted file mode 100644 index 770c9c47..00000000 --- a/source/python/design_func_args.rst +++ /dev/null @@ -1,34 +0,0 @@ -========= -Func Args -========= - -Question --------- - -Ways to send arguments to functions. - -Solution --------- - -.. literalinclude:: ../../languages/python/design_func_args.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/design_func_args.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`design_func_args.py` - * :python-better-explain:`design_func_args.rst` - diff --git a/source/python/design_generator.rst b/source/python/design_generator.rst deleted file mode 100644 index 5d0d78bb..00000000 --- a/source/python/design_generator.rst +++ /dev/null @@ -1,34 +0,0 @@ -============================ -Sending value to a Generator -============================ - -Question --------- - -Sending value to a generator. - -Solution --------- - -.. literalinclude:: ../../languages/python/design_generator.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/design_generator.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`design_generator.py` - * :python-better-explain:`design_generator.rst` - diff --git a/source/python/design_getattribute_example1.rst b/source/python/design_getattribute_example1.rst deleted file mode 100644 index b59c30dd..00000000 --- a/source/python/design_getattribute_example1.rst +++ /dev/null @@ -1,34 +0,0 @@ -==================== -Getattribute Example -==================== - -Question --------- - -Demonstrate `__getattribute__` function. - -Solution --------- - -.. literalinclude:: ../../languages/python/design_getattribute_example1.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/design_getattribute_example1.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`design_getattribute_example1.py` - * :python-better-explain:`design_getattribute_example1.rst` - diff --git a/source/python/design_getattribute_example2.rst b/source/python/design_getattribute_example2.rst deleted file mode 100644 index 878ac84e..00000000 --- a/source/python/design_getattribute_example2.rst +++ /dev/null @@ -1,36 +0,0 @@ -==================================================== -Getattribute Example - Override access one attribute -==================================================== - -Question --------- - -Override access to one of the attribute of the object and return -all other attributes from Super class. - - -Solution --------- - -.. literalinclude:: ../../languages/python/design_getattribute_example2.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/design_getattribute_example2.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`design_getattribute_example2.py` - * :python-better-explain:`design_getattribute_example2.rst` - diff --git a/source/python/design_hextobin.rst b/source/python/design_hextobin.rst deleted file mode 100644 index c48947af..00000000 --- a/source/python/design_hextobin.rst +++ /dev/null @@ -1,34 +0,0 @@ -=========================== -Partial function - Hextobin -=========================== - -Question --------- - -Hexadecimal to Binary - using a partial function. - -Solution --------- - -.. literalinclude:: ../../languages/python/design_hextobin.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/design_hextobin.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`design_hextobin.py` - * :python-better-explain:`design_hextobin.rst` - diff --git a/source/python/design_inheritance.rst b/source/python/design_inheritance.rst deleted file mode 100644 index 532c2fdc..00000000 --- a/source/python/design_inheritance.rst +++ /dev/null @@ -1,34 +0,0 @@ -=========== -Inheritance -=========== - -Question --------- - -Demonstrating Inheritance in Python. - -Solution --------- - -.. literalinclude:: ../../languages/python/design_inheritance.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/design_inheritance.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`design_inheritance.py` - * :python-better-explain:`design_inheritance.rst` - diff --git a/source/python/design_iterator_ex2.rst b/source/python/design_iterator_ex2.rst deleted file mode 100644 index b84cd6f1..00000000 --- a/source/python/design_iterator_ex2.rst +++ /dev/null @@ -1,34 +0,0 @@ -===================== -Iterator - Dictionary -===================== - -Question --------- - -Iterate over a dictionary - -Solution --------- - -.. literalinclude:: ../../languages/python/design_iterator_ex2.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/design_iterator_ex2.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`design_iterator_ex2.py` - * :python-better-explain:`design_iterator_ex2.rst` - diff --git a/source/python/design_object_size.rst b/source/python/design_object_size.rst deleted file mode 100644 index f7605ff4..00000000 --- a/source/python/design_object_size.rst +++ /dev/null @@ -1,34 +0,0 @@ -=========== -Object Size -=========== - -Question --------- - -Function to determine the size of an object. - -Solution --------- - -.. literalinclude:: ../../languages/python/design_object_size.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/design_object_size.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`design_object_size.py` - * :python-better-explain:`design_object_size.rst` - diff --git a/source/python/design_python3_meta_ex1.rst b/source/python/design_python3_meta_ex1.rst deleted file mode 100644 index 4d07efad..00000000 --- a/source/python/design_python3_meta_ex1.rst +++ /dev/null @@ -1,34 +0,0 @@ -================= -Python3 metaclass -================= - -Question --------- - -Python3 metaclass example. - -Solution --------- - -.. literalinclude:: ../../languages/python/design_python3_meta_ex1.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/design_python3_meta_ex1.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`design_python3_meta_ex1.py` - * :python-better-explain:`design_python3_meta_ex1.rst` - diff --git a/source/python/design_python_objects_type.rst b/source/python/design_python_objects_type.rst deleted file mode 100644 index 9faf89d0..00000000 --- a/source/python/design_python_objects_type.rst +++ /dev/null @@ -1,34 +0,0 @@ -================================== -Difference between type and object -================================== - -Question --------- - -Difference between type and an object in python using isinstance and issubclass - -Solution --------- - -.. literalinclude:: ../../languages/python/design_python_objects_type.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/design_python_objects_type.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`design_python_objects_type.py` - * :python-better-explain:`design_python_objects_type.rst` - diff --git a/source/python/design_restricter_class.rst b/source/python/design_restricter_class.rst deleted file mode 100644 index c6ab5107..00000000 --- a/source/python/design_restricter_class.rst +++ /dev/null @@ -1,34 +0,0 @@ -============================ -Restrict an attribute access -============================ - -Question --------- - -Restrict the access to an attribute in a class. - -Solution --------- - -.. literalinclude:: ../../languages/python/design_restricter_class.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/design_restricter_class.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`design_restricter_class.py` - * :python-better-explain:`design_restricter_class.rst` - diff --git a/source/python/design_simple_closure.rst b/source/python/design_simple_closure.rst deleted file mode 100644 index 38bcbe97..00000000 --- a/source/python/design_simple_closure.rst +++ /dev/null @@ -1,35 +0,0 @@ -============== -Simple Closure -============== - -Question --------- - -Simple closure function in python. - - -Solution --------- - -.. literalinclude:: ../../languages/python/design_simple_closure.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/design_simple_closure.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`design_simple_closure.py` - * :python-better-explain:`design_simple_closure.rst` - diff --git a/source/python/design_slice_ellipses.rst b/source/python/design_slice_ellipses.rst deleted file mode 100644 index 6d24a49e..00000000 --- a/source/python/design_slice_ellipses.rst +++ /dev/null @@ -1,34 +0,0 @@ -================== -Ellipses in Python -================== - -Question --------- - -Use of Ellipses in Python. - -Solution --------- - -.. literalinclude:: ../../languages/python/design_slice_ellipses.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/design_slice_ellipses.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`design_slice_ellipses.py` - * :python-better-explain:`design_slice_ellipses.rst` - diff --git a/source/python/design_sorted_loop.rst b/source/python/design_sorted_loop.rst deleted file mode 100644 index bd10cae3..00000000 --- a/source/python/design_sorted_loop.rst +++ /dev/null @@ -1,34 +0,0 @@ -=========== -Sorted Loop -=========== - -Question --------- - -Measure the sorted builtin function performance. - -Solution --------- - -.. literalinclude:: ../../languages/python/design_sorted_loop.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/design_sorted_loop.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`design_sorted_loop.py` - * :python-better-explain:`design_sorted_loop.rst` - diff --git a/source/python/design_stackinspection.rst b/source/python/design_stackinspection.rst deleted file mode 100644 index 72dad62f..00000000 --- a/source/python/design_stackinspection.rst +++ /dev/null @@ -1,34 +0,0 @@ -================ -Stack Inspection -================ - -Question --------- - -Inspecting the Stack in Python. - -Solution --------- - -.. literalinclude:: ../../languages/python/design_stackinspection.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/design_stackinspection.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`design_stackinspection.py` - * :python-better-explain:`design_stackinspection.rst` - diff --git a/source/python/design_struct_example.rst b/source/python/design_struct_example.rst deleted file mode 100644 index 50d1b5dc..00000000 --- a/source/python/design_struct_example.rst +++ /dev/null @@ -1,34 +0,0 @@ -============== -Struct Example -============== - -Question --------- - -Using the structure module in python for serialization and deserialization. - -Solution --------- - -.. literalinclude:: ../../languages/python/design_struct_example.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/design_struct_example.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`design_struct_example.py` - * :python-better-explain:`design_struct_example.rst` - diff --git a/source/python/design_total_ordering.rst b/source/python/design_total_ordering.rst deleted file mode 100644 index 9160751b..00000000 --- a/source/python/design_total_ordering.rst +++ /dev/null @@ -1,34 +0,0 @@ -============== -Total Ordering -============== - -Question --------- - -Demonstrate the use of functools.total_ordering in Python. - -Solution --------- - -.. literalinclude:: ../../languages/python/design_total_ordering.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/design_total_ordering.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`design_total_ordering.py` - * :python-better-explain:`design_total_ordering.rst` - diff --git a/source/python/design_traceit.rst b/source/python/design_traceit.rst deleted file mode 100644 index cdf901e0..00000000 --- a/source/python/design_traceit.rst +++ /dev/null @@ -1,34 +0,0 @@ -======= -Traceit -======= - -Question --------- - -Trace the execution of a python program. - -Solution --------- - -.. literalinclude:: ../../languages/python/design_traceit.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/design_traceit.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`design_traceit.py` - * :python-better-explain:`design_traceit.rst` - diff --git a/source/python/files_count_lines_large_file.rst b/source/python/files_count_lines_large_file.rst deleted file mode 100644 index 78a9f399..00000000 --- a/source/python/files_count_lines_large_file.rst +++ /dev/null @@ -1,37 +0,0 @@ -=========================== -Count Lines in a Large File -=========================== - -Question --------- - -How to count lines in a huge file. - - -Solution --------- - -.. literalinclude:: ../../languages/python/files_count_lines_large_file.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/files_count_lines_large_file.py - :language: python - :codesite: ideone - -Explanation -=========== - -This loads the file in 'rb' (read binary) mode, in chunks and then counts the newline '\n' -characters. Loading in chunks takes care of reading a huge file part. - - - - - - -.. seealso:: - - * :python-suggest-improve:`files_count_lines_large_file.py` - * :python-better-explain:`files_count_lines_large_file.rst` - diff --git a/source/python/files_processing_every_word.rst b/source/python/files_processing_every_word.rst deleted file mode 100644 index 57ea8a2e..00000000 --- a/source/python/files_processing_every_word.rst +++ /dev/null @@ -1,83 +0,0 @@ -=============================== -Process each word in a sentence -=============================== - -Question --------- - -Find words in the sentence and process each word. - -Solution --------- - -.. literalinclude:: ../../languages/python/files_processing_every_word.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/files_processing_every_word.py - :language: python - :codesite: ideone - -Explanation -=========== - -The program creates a REGEX for matching words and uses regex.finditer(line) -to find all the words matching the regular expression in a line. - -Running the program over itself produces the output like this. - -:: - - import - re - WORD_REGEX - re - compile - r - w'- - def - do_something_with_word - word - print - word - def - words_in_file - file_name - with - open - file_name - as - fh - for - line - in - fh - for - word - in - WORD_REGEX - finditer - line - do_something_with_word - word - group - 0 - def - main - words_in_file - ' - files_processing_every_word - py' - if - __name__ - '__main__' - main - - - - -.. seealso:: - - * :python-suggest-improve:`files_processing_every_word.py` - * :python-better-explain:`files_processing_every_word.rst` - diff --git a/source/python/files_random_access_input_output.rst b/source/python/files_random_access_input_output.rst deleted file mode 100644 index e02a6fab..00000000 --- a/source/python/files_random_access_input_output.rst +++ /dev/null @@ -1,35 +0,0 @@ -================================ -Using Random Access Input Output -================================ - -Question --------- - -Read a particular record from somewhere inside a large file of fixed-length -records. - -Solution --------- - -.. literalinclude:: ../../languages/python/files_random_access_input_output.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/files_random_access_input_output.py - :language: python - :codesite: ideone - -Explanation -=========== - -The file seek call, seeks to a particular position in the file. The read -method then reads the block of text. - - - - -.. seealso:: - - * :python-suggest-improve:`files_random_access_input_output.py` - * :python-better-explain:`files_random_access_input_output.rst` - diff --git a/source/python/files_read_specific_line.rst b/source/python/files_read_specific_line.rst deleted file mode 100644 index df70ee98..00000000 --- a/source/python/files_read_specific_line.rst +++ /dev/null @@ -1,34 +0,0 @@ -=================================== -Reading a Specific Line From a File -=================================== - -Question --------- - -Read a specified line number from a file. - -Solution --------- - -.. literalinclude:: ../../languages/python/files_read_specific_line.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/files_read_specific_line.py - :language: python - :codesite: ideone - -Explanation -=========== - -This introduces a linecache module from the standard library which provides an -api to read a line number directly. - - - - -.. seealso:: - - * :python-suggest-improve:`files_read_specific_line.py.py` - * :python-better-explain:`files_read_specific_line.py.rst` - diff --git a/source/python/files_reading_zipfile.rst b/source/python/files_reading_zipfile.rst deleted file mode 100644 index a27aa7f6..00000000 --- a/source/python/files_reading_zipfile.rst +++ /dev/null @@ -1,49 +0,0 @@ -========================== -Reading Data from Zip File -========================== - -Question --------- - -Reading the content from a zip file. - - -Solution --------- - -.. literalinclude:: ../../languages/python/files_reading_zipfile.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/files_reading_zipfile.py - :language: python - :codesite: ideone - -Explanation -=========== - -We read the file with "r" permission instead of "rb", as Python cookbook -advises that it is more deterministic when running in Windows OS. - -You can list the contents of the zipfile and then read few bytes of them as -show in the example. - -Here is a sample run of this program. - -:: - - $zip -c sample.zip files_reading_zipfile.py - - $ python files_reading_zipfile.py - File: files_reading_zipfile.py - has 406 bytes - - - - - -.. seealso:: - - * :python-suggest-improve:`files_reading_zipfile.py` - * :python-better-explain:`files_reading_zipfile.rst` - diff --git a/source/python/index.rst b/source/python/index.rst deleted file mode 100644 index aa2425d6..00000000 --- a/source/python/index.rst +++ /dev/null @@ -1,151 +0,0 @@ -================== -Python Programming -================== - -This is Uthcode's python programming section, which illustrates how to do -various programing tasks using python. - -Algorithm -========= -This is an implementation of a well known CS algorithm. - -.. toctree:: - :maxdepth: 1 - - algorithm_binary_representation - algorithm_binary_search - algorithm_cellauto - algorithm_checking_string_text_or_binary - algorithm_eratosthenes - algorithm_fibo - algorithm_fact2 - algorithm_graph - algorithm_hanoi - algorithm_insertion - algorithm_int_to_roman - algorithm_locate - algorithm_maxsort - algorithm_mergesort - algorithm_npuzzle - algorithm_pyex_multiprocessing - algorithm_pyex2_multiprocessing - algorithm_scrmable - algorithm_spelling - algorithm_splitter - algorithm_syllablecount - algorithm_toss_coins - algorithm_traversal - algorithm_tree2 - trie - -Design -====== - -These programs demonstrate software design ascepts. These can be pretty -deep as, "why" it is done so is not obvious, but the program usually -demonstrates how it is done. - -.. toctree:: - :maxdepth: 1 - - design_args_kwargs - design_ast_example1 - design_atexit_1 - design_caseinsensitivedict - design_closure_example1 - design_closure1 - design_context_2 - design_contextmanager - design_contextmanager_ex - design_decorator3 - design_ex_iterable27 - design_func_args - design_generator - design_getattribute_example1 - design_getattribute_example2 - design_hextobin - design_inheritance - design_iterator_ex2 - design_object_size - design_python_objects_type - design_python3_meta_ex1 - design_restricter_class - design_simple_closure - design_slice_ellipses - design_sorted_loop - design_stackinspection - design_struct_example - design_total_ordering - design_traceit - - -Software_engineering -==================== - -This is how software is built in real world. If your software needs to -make money, you will need to take care of these aspects. - -.. toctree:: - :maxdepth: 1 - - software_engineering_copy_files_unicode - software_engineering_createtempfiles - software_engineering_doctest_example - software_engineering_encoding_unicode_xml_html - software_engineering_exceptions_testing - software_engineering_fcntl_1 - software_engineering_fctrl2 - software_engineering_fortune_card - software_engineering_htmlformatter - software_engineering_htmlwriter - software_engineering_ideone_post - software_engineering_logging1 - software_engineering_logging2 - software_engineering_logging3 - software_engineering_logging4 - software_engineering_logging5 - software_engineering_multiprocessing_1 - software_engineering_os_exec1 - software_engineering_provide_warnings - software_engineering_ptags - software_engineering_run_under_strace - software_engineering_runningtime - software_engineering_runningtime_intaddition - software_engineering_runningtime_intvsfloat - software_engineering_simple_subprocess - software_engineering_simple_threading1 - software_engineering_sqlite3 - software_engineering_stringio - software_engineering_subprocess1 - software_engineering_subprocess2 - software_engineering_subprocess3 - software_engineering_subprocess4 - software_engineering_subprocess5 - software_engineering_test_codec01 - software_engineering_test_codec02 - software_engineering_test_codec03 - software_engineering_test_dedent - software_engineering_threading2 - software_engineering_time_converter - software_engineering_tkintertimer - software_engineering_twitter_phidget - software_engineering_xmlrpcclient - software_engineering_xmlrpcserver - files_read_specific_line - files_count_lines_large_file - files_processing_every_word - files_random_access_input_output - files_reading_zipfile - min_cost_path - -Text Manipulation -================= - -This category demonstrates text manipulation. It reads input and applies simple -text manipulation and provides the output. Many programs fall into this -category. - -.. toctree:: - :maxdepth: 1 - - text_manipulation_argparse1 diff --git a/source/python/min_cost_path.rst b/source/python/min_cost_path.rst deleted file mode 100644 index 4bc730ce..00000000 --- a/source/python/min_cost_path.rst +++ /dev/null @@ -1,46 +0,0 @@ -============= -Min Cost Path -============= - -Question --------- - -Given a m x n grid filled with non-negative numbers, find a path from top left -to bottom right which minimizes the sum of all numbers along its path. - -Note: You can only move either down or right at any point in time. - -Problem Source: https://leetcode.com/problems/minimum-path-sum/ - -Solution --------- - -.. literalinclude:: ../../languages/python/min_cost_path.py - :language: python - :tab-width: 4 - - -Explanation ------------ - -.. youtube:: lBRtnuxg-gU - - -Visualize ---------- - -* `Visualize Min Cost Path in PythonTutor`_ - - -.. _Visualize Min Cost Path in PythonTutor: http://www.pythontutor.com/live.html#code=from%20typing%20import%20List%0A%0A%23%20Video%3A%20https%3A//www.youtube.com/watch%3Fv%3DlBRtnuxg-gU%0A%0A%0Aclass%20Solution%3A%0A%0A%20%20%20%20def%20minPathSum%28self,%20grid%3A%20List%5BList%5Bint%5D%5D%29%20-%3E%20int%3A%0A%20%20%20%20%20%20%20%20m%20%3D%20len%28grid%29%0A%20%20%20%20%20%20%20%20n%20%3D%20len%28grid%5B0%5D%29%0A%20%20%20%20%20%20%20%20T%20%3D%20%5B%5B0%5D%20*%20n%20for%20_%20in%20range%28m%29%5D%0A%20%20%20%20%20%20%20%20%23%20First%20left%20top%20corner%20cost%20is%20same.%0A%20%20%20%20%20%20%20%20T%5B0%5D%5B0%5D%20%3D%20grid%5B0%5D%5B0%5D%0A%0A%20%20%20%20%20%20%20%20%23%20First%20row%20in%20T%0A%20%20%20%20%20%20%20%20for%20first_row_idx%20in%20range%281,%20n%29%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20T%5B0%5D%5Bfirst_row_idx%5D%20%3D%20T%5B0%5D%5Bfirst_row_idx-1%5D%20%2B%20grid%5B0%5D%5Bfirst_row_idx%5D%0A%0A%20%20%20%20%20%20%20%20%23%20First%20col%20in%20T%0A%20%20%20%20%20%20%20%20for%20first_col_idx%20in%20range%281,%20m%29%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20T%5Bfirst_col_idx%5D%5B0%5D%20%3D%20T%5Bfirst_col_idx-1%5D%5B0%5D%20%2B%20grid%5Bfirst_col_idx%5D%5B0%5D%0A%0A%20%20%20%20%20%20%20%20%23%20Fill%20in%20the%20rest%20of%20the%202D%20matrix%20for%20T.%0A%20%20%20%20%20%20%20%20for%20i%20in%20range%281,%20m%29%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20for%20j%20in%20range%281,%20n%29%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20T%5Bi%5D%5Bj%5D%20%3D%20grid%5Bi%5D%5Bj%5D%20%2B%20min%28T%5Bi-1%5D%5Bj%5D,%20T%5Bi%5D%5Bj-1%5D%29%20%20%0A%0A%20%20%20%20%20%20%20%20%23%20value%20to%20reach%20the%20right%20most%20end%0A%20%20%20%20%20%20%20%20return%20T%5B-1%5D%5B-1%5D%0A%0As%20%3D%20Solution%28%29%0Amat%20%3D%20%5B%0A%20%20%20%20%20%20%20%20%5B1,3,1%5D,%0A%20%20%20%20%20%20%20%20%5B1,5,1%5D,%0A%20%20%20%20%20%20%20%20%5B4,2,1%5D%0A%20%20%20%20%5D%0Aprint%28s.minPathSum%28mat%29%29&cumulative=false&heapPrimitives=false&mode=display&origin=opt-live.js&py=3&rawInputLstJSON=%5B%5D&textReferences=true - - - -.. git_changelog:: - - -.. seealso:: - - * :python-suggest-improve:`min_cost_path.py` - * :python-better-explain:`min_cost_path.rst` - diff --git a/source/python/software_engineering_copy_files_unicode.rst b/source/python/software_engineering_copy_files_unicode.rst deleted file mode 100644 index f72e4805..00000000 --- a/source/python/software_engineering_copy_files_unicode.rst +++ /dev/null @@ -1,34 +0,0 @@ -================== -Copy Files Unicode -================== - -Question --------- - -ADDQUESTION - -Solution --------- - -.. literalinclude:: ../../languages/python/software_engineering_copy_files_unicode.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/software_engineering_copy_files_unicode.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`software_engineering_copy_files_unicode.py` - * :python-better-explain:`software_engineering_copy_files_unicode.rst` - diff --git a/source/python/software_engineering_createtempfiles.rst b/source/python/software_engineering_createtempfiles.rst deleted file mode 100644 index 329acc5d..00000000 --- a/source/python/software_engineering_createtempfiles.rst +++ /dev/null @@ -1,36 +0,0 @@ -=============== -Createtempfiles -=============== - -Question --------- - -Example program that creates temporary files with content in them. This serves as -useful utility if you want to fill a directory full of temporary files with -some content. The content is Zen of Python. - -Solution --------- - -.. literalinclude:: ../../languages/python/software_engineering_createtempfiles.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/software_engineering_createtempfiles.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`software_engineering_createtempfiles.py` - * :python-better-explain:`software_engineering_createtempfiles.rst` - diff --git a/source/python/software_engineering_doctest_example.rst b/source/python/software_engineering_doctest_example.rst deleted file mode 100644 index 696d91b5..00000000 --- a/source/python/software_engineering_doctest_example.rst +++ /dev/null @@ -1,34 +0,0 @@ -=============== -Doctest Example -=============== - -Question --------- - -ADDQUESTION - -Solution --------- - -.. literalinclude:: ../../languages/python/software_engineering_doctest_example.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/software_engineering_doctest_example.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`software_engineering_doctest_example.py` - * :python-better-explain:`software_engineering_doctest_example.rst` - diff --git a/source/python/software_engineering_encoding_unicode_xml_html.rst b/source/python/software_engineering_encoding_unicode_xml_html.rst deleted file mode 100644 index ab6c1ba3..00000000 --- a/source/python/software_engineering_encoding_unicode_xml_html.rst +++ /dev/null @@ -1,34 +0,0 @@ -========================= -Encoding Unicode XML HTML -========================= - -Question --------- - -ADDQUESTION - -Solution --------- - -.. literalinclude:: ../../languages/python/software_engineering_encoding_unicode_xml_html.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/software_engineering_encoding_unicode_xml_html.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`software_engineering_encoding_unicode_xml_html.py` - * :python-better-explain:`software_engineering_encoding_unicode_xml_html.rst` - diff --git a/source/python/software_engineering_exceptions_testing.rst b/source/python/software_engineering_exceptions_testing.rst deleted file mode 100644 index 21ee97f5..00000000 --- a/source/python/software_engineering_exceptions_testing.rst +++ /dev/null @@ -1,34 +0,0 @@ -================== -Exceptions Testing -================== - -Question --------- - -ADDQUESTION - -Solution --------- - -.. literalinclude:: ../../languages/python/software_engineering_exceptions_testing.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/software_engineering_exceptions_testing.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`software_engineering_exceptions_testing.py` - * :python-better-explain:`software_engineering_exceptions_testing.rst` - diff --git a/source/python/software_engineering_fcntl_1.rst b/source/python/software_engineering_fcntl_1.rst deleted file mode 100644 index 292dfb73..00000000 --- a/source/python/software_engineering_fcntl_1.rst +++ /dev/null @@ -1,34 +0,0 @@ -======= -Fcntl 1 -======= - -Question --------- - -ADDQUESTION - -Solution --------- - -.. literalinclude:: ../../languages/python/software_engineering_fcntl_1.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/software_engineering_fcntl_1.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`software_engineering_fcntl_1.py` - * :python-better-explain:`software_engineering_fcntl_1.rst` - diff --git a/source/python/software_engineering_fctrl2.rst b/source/python/software_engineering_fctrl2.rst deleted file mode 100644 index e6c7bb7b..00000000 --- a/source/python/software_engineering_fctrl2.rst +++ /dev/null @@ -1,34 +0,0 @@ -====== -Fctrl2 -====== - -Question --------- - -ADDQUESTION - -Solution --------- - -.. literalinclude:: ../../languages/python/software_engineering_fctrl2.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/software_engineering_fctrl2.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`software_engineering_fctrl2.py` - * :python-better-explain:`software_engineering_fctrl2.rst` - diff --git a/source/python/software_engineering_fortune_card.rst b/source/python/software_engineering_fortune_card.rst deleted file mode 100644 index 19fcc0a4..00000000 --- a/source/python/software_engineering_fortune_card.rst +++ /dev/null @@ -1,34 +0,0 @@ -============ -Fortune Card -============ - -Question --------- - -ADDQUESTION - -Solution --------- - -.. literalinclude:: ../../languages/python/software_engineering_fortune_card.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/software_engineering_fortune_card.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`software_engineering_fortune_card.py` - * :python-better-explain:`software_engineering_fortune_card.rst` - diff --git a/source/python/software_engineering_htmlformatter.rst b/source/python/software_engineering_htmlformatter.rst deleted file mode 100644 index 1218d6e1..00000000 --- a/source/python/software_engineering_htmlformatter.rst +++ /dev/null @@ -1,34 +0,0 @@ -============== -Html Formatter -============== - -Question --------- - -ADDQUESTION - -Solution --------- - -.. literalinclude:: ../../languages/python/software_engineering_htmlformatter.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/software_engineering_htmlformatter.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`software_engineering_htmlformatter.py` - * :python-better-explain:`software_engineering_htmlformatter.rst` - diff --git a/source/python/software_engineering_htmlwriter.rst b/source/python/software_engineering_htmlwriter.rst deleted file mode 100644 index 3b1ad7c3..00000000 --- a/source/python/software_engineering_htmlwriter.rst +++ /dev/null @@ -1,34 +0,0 @@ -=========== -Html Writer -=========== - -Question --------- - -ADDQUESTION - -Solution --------- - -.. literalinclude:: ../../languages/python/software_engineering_htmlwriter.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/software_engineering_htmlwriter.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`software_engineering_htmlwriter.py` - * :python-better-explain:`software_engineering_htmlwriter.rst` - diff --git a/source/python/software_engineering_ideone_post.rst b/source/python/software_engineering_ideone_post.rst deleted file mode 100644 index b998dd93..00000000 --- a/source/python/software_engineering_ideone_post.rst +++ /dev/null @@ -1,34 +0,0 @@ -=========== -Ideone Post -=========== - -Question --------- - -ADDQUESTION - -Solution --------- - -.. literalinclude:: ../../languages/python/software_engineering_ideone_post.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/software_engineering_ideone_post.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`software_engineering_ideone_post.py` - * :python-better-explain:`software_engineering_ideone_post.rst` - diff --git a/source/python/software_engineering_logging1.rst b/source/python/software_engineering_logging1.rst deleted file mode 100644 index 3af65398..00000000 --- a/source/python/software_engineering_logging1.rst +++ /dev/null @@ -1,34 +0,0 @@ -======== -Logging1 -======== - -Question --------- - -ADDQUESTION - -Solution --------- - -.. literalinclude:: ../../languages/python/software_engineering_logging1.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/software_engineering_logging1.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`software_engineering_logging1.py` - * :python-better-explain:`software_engineering_logging1.rst` - diff --git a/source/python/software_engineering_logging2.rst b/source/python/software_engineering_logging2.rst deleted file mode 100644 index 20e86a3b..00000000 --- a/source/python/software_engineering_logging2.rst +++ /dev/null @@ -1,34 +0,0 @@ -======== -Logging2 -======== - -Question --------- - -ADDQUESTION - -Solution --------- - -.. literalinclude:: ../../languages/python/software_engineering_logging2.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/software_engineering_logging2.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`software_engineering_logging2.py` - * :python-better-explain:`software_engineering_logging2.rst` - diff --git a/source/python/software_engineering_logging3.rst b/source/python/software_engineering_logging3.rst deleted file mode 100644 index 308bd288..00000000 --- a/source/python/software_engineering_logging3.rst +++ /dev/null @@ -1,34 +0,0 @@ -======== -Logging3 -======== - -Question --------- - -ADDQUESTION - -Solution --------- - -.. literalinclude:: ../../languages/python/software_engineering_logging3.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/software_engineering_logging3.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`software_engineering_logging3.py` - * :python-better-explain:`software_engineering_logging3.rst` - diff --git a/source/python/software_engineering_logging4.rst b/source/python/software_engineering_logging4.rst deleted file mode 100644 index b2965c52..00000000 --- a/source/python/software_engineering_logging4.rst +++ /dev/null @@ -1,34 +0,0 @@ -======== -Logging4 -======== - -Question --------- - -ADDQUESTION - -Solution --------- - -.. literalinclude:: ../../languages/python/software_engineering_logging4.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/software_engineering_logging4.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`software_engineering_logging4.py` - * :python-better-explain:`software_engineering_logging4.rst` - diff --git a/source/python/software_engineering_logging5.rst b/source/python/software_engineering_logging5.rst deleted file mode 100644 index ad9404f7..00000000 --- a/source/python/software_engineering_logging5.rst +++ /dev/null @@ -1,34 +0,0 @@ -======== -Logging5 -======== - -Question --------- - -ADDQUESTION - -Solution --------- - -.. literalinclude:: ../../languages/python/software_engineering_logging5.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/software_engineering_logging5.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`software_engineering_logging5.py` - * :python-better-explain:`software_engineering_logging5.rst` - diff --git a/source/python/software_engineering_multiprocessing_1.rst b/source/python/software_engineering_multiprocessing_1.rst deleted file mode 100644 index 14ac158a..00000000 --- a/source/python/software_engineering_multiprocessing_1.rst +++ /dev/null @@ -1,34 +0,0 @@ -=============== -Multiprocessing -=============== - -Question --------- - -ADDQUESTION - -Solution --------- - -.. literalinclude:: ../../languages/python/software_engineering_multiprocessing_1.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/software_engineering_multiprocessing_1.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`software_engineering_multiprocessing_1.py` - * :python-better-explain:`software_engineering_multiprocessing_1.rst` - diff --git a/source/python/software_engineering_os_exec1.rst b/source/python/software_engineering_os_exec1.rst deleted file mode 100644 index 1915ae23..00000000 --- a/source/python/software_engineering_os_exec1.rst +++ /dev/null @@ -1,34 +0,0 @@ -============= -OS Exercise 1 -============= - -Question --------- - -ADDQUESTION - -Solution --------- - -.. literalinclude:: ../../languages/python/software_engineering_os_exec1.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/software_engineering_os_exec1.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`software_engineering_os_exec1.py` - * :python-better-explain:`software_engineering_os_exec1.rst` - diff --git a/source/python/software_engineering_provide_warnings.rst b/source/python/software_engineering_provide_warnings.rst deleted file mode 100644 index a301c397..00000000 --- a/source/python/software_engineering_provide_warnings.rst +++ /dev/null @@ -1,34 +0,0 @@ -================ -Provide Warnings -================ - -Question --------- - -ADDQUESTION - -Solution --------- - -.. literalinclude:: ../../languages/python/software_engineering_provide_warnings.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/software_engineering_provide_warnings.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`software_engineering_provide_warnings.py` - * :python-better-explain:`software_engineering_provide_warnings.rst` - diff --git a/source/python/software_engineering_ptags.rst b/source/python/software_engineering_ptags.rst deleted file mode 100644 index 08800538..00000000 --- a/source/python/software_engineering_ptags.rst +++ /dev/null @@ -1,34 +0,0 @@ -===== -Ptags -===== - -Question --------- - -ADDQUESTION - -Solution --------- - -.. literalinclude:: ../../languages/python/software_engineering_ptags.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/software_engineering_ptags.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`software_engineering_ptags.py` - * :python-better-explain:`software_engineering_ptags.rst` - diff --git a/source/python/software_engineering_run_under_strace.rst b/source/python/software_engineering_run_under_strace.rst deleted file mode 100644 index 6117d688..00000000 --- a/source/python/software_engineering_run_under_strace.rst +++ /dev/null @@ -1,34 +0,0 @@ -================ -Run Under Strace -================ - -Question --------- - -ADDQUESTION - -Solution --------- - -.. literalinclude:: ../../languages/python/software_engineering_run_under_strace.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/software_engineering_run_under_strace.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`software_engineering_run_under_strace.py` - * :python-better-explain:`software_engineering_run_under_strace.rst` - diff --git a/source/python/software_engineering_runningtime.rst b/source/python/software_engineering_runningtime.rst deleted file mode 100644 index caab523c..00000000 --- a/source/python/software_engineering_runningtime.rst +++ /dev/null @@ -1,34 +0,0 @@ -=========== -Runningtime -=========== - -Question --------- - -ADDQUESTION - -Solution --------- - -.. literalinclude:: ../../languages/python/software_engineering_runningtime.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/software_engineering_runningtime.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`software_engineering_runningtime.py` - * :python-better-explain:`software_engineering_runningtime.rst` - diff --git a/source/python/software_engineering_runningtime_intaddition.rst b/source/python/software_engineering_runningtime_intaddition.rst deleted file mode 100644 index 1ffc95ff..00000000 --- a/source/python/software_engineering_runningtime_intaddition.rst +++ /dev/null @@ -1,34 +0,0 @@ -======================= -Runningtime Intaddition -======================= - -Question --------- - -ADDQUESTION - -Solution --------- - -.. literalinclude:: ../../languages/python/software_engineering_runningtime.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/software_engineering_runningtime.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`software_engineering_runningtime.py` - * :python-better-explain:`software_engineering_runningtime.rst` - diff --git a/source/python/software_engineering_runningtime_intvsfloat.rst b/source/python/software_engineering_runningtime_intvsfloat.rst deleted file mode 100644 index 06be132d..00000000 --- a/source/python/software_engineering_runningtime_intvsfloat.rst +++ /dev/null @@ -1,34 +0,0 @@ -====================== -Runningtime Intvsfloat -====================== - -Question --------- - -ADDQUESTION - -Solution --------- - -.. literalinclude:: ../../languages/python/software_engineering_runningtime_intvsfloat.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/software_engineering_runningtime_intvsfloat.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`software_engineering_runningtime_intvsfloat.py` - * :python-better-explain:`software_engineering_runningtime_intvsfloat.rst` - diff --git a/source/python/software_engineering_simple_subprocess.rst b/source/python/software_engineering_simple_subprocess.rst deleted file mode 100644 index 5cbdfda7..00000000 --- a/source/python/software_engineering_simple_subprocess.rst +++ /dev/null @@ -1,34 +0,0 @@ -================= -Simple Subprocess -================= - -Question --------- - -ADDQUESTION - -Solution --------- - -.. literalinclude:: ../../languages/python/software_engineering_simple_subprocess.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/software_engineering_simple_subprocess.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`software_engineering_simple_subprocess.py` - * :python-better-explain:`software_engineering_simple_subprocess.rst` - diff --git a/source/python/software_engineering_simple_threading1.rst b/source/python/software_engineering_simple_threading1.rst deleted file mode 100644 index 015a6547..00000000 --- a/source/python/software_engineering_simple_threading1.rst +++ /dev/null @@ -1,34 +0,0 @@ -================= -Simple Threading1 -================= - -Question --------- - -ADDQUESTION - -Solution --------- - -.. literalinclude:: ../../languages/python/software_engineering_simple_threading1.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/software_engineering_simple_threading1.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`software_engineering_simple_threading1.py` - * :python-better-explain:`software_engineering_simple_threading1.rst` - diff --git a/source/python/software_engineering_sqlite3.rst b/source/python/software_engineering_sqlite3.rst deleted file mode 100644 index a2f7f05b..00000000 --- a/source/python/software_engineering_sqlite3.rst +++ /dev/null @@ -1,34 +0,0 @@ -======= -Sqlite3 -======= - -Question --------- - -ADDQUESTION - -Solution --------- - -.. literalinclude:: ../../languages/python/software_engineering_sqlite3.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/software_engineering_sqlite3.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`software_engineering_sqlite3.py` - * :python-better-explain:`software_engineering_sqlite3.rst` - diff --git a/source/python/software_engineering_stringio.rst b/source/python/software_engineering_stringio.rst deleted file mode 100644 index 0d91363f..00000000 --- a/source/python/software_engineering_stringio.rst +++ /dev/null @@ -1,34 +0,0 @@ -======== -Stringio -======== - -Question --------- - -ADDQUESTION - -Solution --------- - -.. literalinclude:: ../../languages/python/software_engineering_stringio.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/software_engineering_stringio.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`software_engineering_stringio.py` - * :python-better-explain:`software_engineering_stringio.rst` - diff --git a/source/python/software_engineering_subprocess1.rst b/source/python/software_engineering_subprocess1.rst deleted file mode 100644 index 3cbf68c5..00000000 --- a/source/python/software_engineering_subprocess1.rst +++ /dev/null @@ -1,34 +0,0 @@ -=========== -Subprocess1 -=========== - -Question --------- - -ADDQUESTION - -Solution --------- - -.. literalinclude:: ../../languages/python/software_engineering_subprocess1.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/software_engineering_subprocess1.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`software_engineering_subprocess1.py` - * :python-better-explain:`software_engineering_subprocess1.rst` - diff --git a/source/python/software_engineering_subprocess2.rst b/source/python/software_engineering_subprocess2.rst deleted file mode 100644 index abd1643e..00000000 --- a/source/python/software_engineering_subprocess2.rst +++ /dev/null @@ -1,34 +0,0 @@ -=========== -Subprocess2 -=========== - -Question --------- - -ADDQUESTION - -Solution --------- - -.. literalinclude:: ../../languages/python/software_engineering_subprocess2.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/software_engineering_subprocess2.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`software_engineering_subprocess2.py` - * :python-better-explain:`software_engineering_subprocess2.rst` - diff --git a/source/python/software_engineering_subprocess3.rst b/source/python/software_engineering_subprocess3.rst deleted file mode 100644 index 67087f0c..00000000 --- a/source/python/software_engineering_subprocess3.rst +++ /dev/null @@ -1,34 +0,0 @@ -=========== -Subprocess3 -=========== - -Question --------- - -ADDQUESTION - -Solution --------- - -.. literalinclude:: ../../languages/python/software_engineering_subprocess3.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/software_engineering_subprocess3.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`software_engineering_subprocess3.py` - * :python-better-explain:`software_engineering_subprocess3.rst` - diff --git a/source/python/software_engineering_subprocess4.rst b/source/python/software_engineering_subprocess4.rst deleted file mode 100644 index 44886f96..00000000 --- a/source/python/software_engineering_subprocess4.rst +++ /dev/null @@ -1,34 +0,0 @@ -=========== -Subprocess4 -=========== - -Question --------- - -ADDQUESTION - -Solution --------- - -.. literalinclude:: ../../languages/python/software_engineering_subprocess4.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/software_engineering_subprocess4.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`software_engineering_subprocess4.py` - * :python-better-explain:`software_engineering_subprocess4.rst` - diff --git a/source/python/software_engineering_subprocess5.rst b/source/python/software_engineering_subprocess5.rst deleted file mode 100644 index 1304f4c6..00000000 --- a/source/python/software_engineering_subprocess5.rst +++ /dev/null @@ -1,34 +0,0 @@ -=========== -Subprocess5 -=========== - -Question --------- - -ADDQUESTION - -Solution --------- - -.. literalinclude:: ../../languages/python/software_engineering_subprocess5.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/software_engineering_subprocess5.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`software_engineering_subprocess5.py` - * :python-better-explain:`software_engineering_subprocess5.rst` - diff --git a/source/python/software_engineering_test_codec01.rst b/source/python/software_engineering_test_codec01.rst deleted file mode 100644 index b344e2e0..00000000 --- a/source/python/software_engineering_test_codec01.rst +++ /dev/null @@ -1,34 +0,0 @@ -============ -Test Codec01 -============ - -Question --------- - -ADDQUESTION - -Solution --------- - -.. literalinclude:: ../../languages/python/software_engineering_test_codec01.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/software_engineering_test_codec01.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`software_engineering_test_codec01.py` - * :python-better-explain:`software_engineering_test_codec01.rst` - diff --git a/source/python/software_engineering_test_codec02.rst b/source/python/software_engineering_test_codec02.rst deleted file mode 100644 index 984acd2d..00000000 --- a/source/python/software_engineering_test_codec02.rst +++ /dev/null @@ -1,34 +0,0 @@ -============ -Test Codec02 -============ - -Question --------- - -ADDQUESTION - -Solution --------- - -.. literalinclude:: ../../languages/python/software_engineering_test_codec02.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/software_engineering_test_codec02.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`software_engineering_test_codec02.py` - * :python-better-explain:`software_engineering_test_codec02.rst` - diff --git a/source/python/software_engineering_test_codec03.rst b/source/python/software_engineering_test_codec03.rst deleted file mode 100644 index 701b29a5..00000000 --- a/source/python/software_engineering_test_codec03.rst +++ /dev/null @@ -1,34 +0,0 @@ -============ -Test Codec03 -============ - -Question --------- - -ADDQUESTION - -Solution --------- - -.. literalinclude:: ../../languages/python/software_engineering_test_codec03.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/software_engineering_test_codec03.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`software_engineering_test_codec03.py` - * :python-better-explain:`software_engineering_test_codec03.rst` - diff --git a/source/python/software_engineering_test_dedent.rst b/source/python/software_engineering_test_dedent.rst deleted file mode 100644 index f6ede764..00000000 --- a/source/python/software_engineering_test_dedent.rst +++ /dev/null @@ -1,34 +0,0 @@ -=========== -Test Dedent -=========== - -Question --------- - -ADDQUESTION - -Solution --------- - -.. literalinclude:: ../../languages/python/software_engineering_test_dedent.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/software_engineering_test_dedent.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`software_engineering_test_dedent.py` - * :python-better-explain:`software_engineering_test_dedent.rst` - diff --git a/source/python/software_engineering_threading2.rst b/source/python/software_engineering_threading2.rst deleted file mode 100644 index 7eecf409..00000000 --- a/source/python/software_engineering_threading2.rst +++ /dev/null @@ -1,34 +0,0 @@ -========== -Threading2 -========== - -Question --------- - -ADDQUESTION - -Solution --------- - -.. literalinclude:: ../../languages/python/software_engineering_threading2.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/software_engineering_threading2.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`software_engineering_threading2.py` - * :python-better-explain:`software_engineering_threading2.rst` - diff --git a/source/python/software_engineering_time_converter.rst b/source/python/software_engineering_time_converter.rst deleted file mode 100644 index 32688c86..00000000 --- a/source/python/software_engineering_time_converter.rst +++ /dev/null @@ -1,34 +0,0 @@ -============== -Time Converter -============== - -Question --------- - -ADDQUESTION - -Solution --------- - -.. literalinclude:: ../../languages/python/software_engineering_time_converter.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/software_engineering_time_converter.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`software_engineering_time_converter.py` - * :python-better-explain:`software_engineering_time_converter.rst` - diff --git a/source/python/software_engineering_tkintertimer.rst b/source/python/software_engineering_tkintertimer.rst deleted file mode 100644 index 2e478c35..00000000 --- a/source/python/software_engineering_tkintertimer.rst +++ /dev/null @@ -1,34 +0,0 @@ -============ -Tkintertimer -============ - -Question --------- - -ADDQUESTION - -Solution --------- - -.. literalinclude:: ../../languages/python/software_engineering_tkintertimer.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/software_engineering_tkintertimer.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`software_engineering_tkintertimer.py` - * :python-better-explain:`software_engineering_tkintertimer.rst` - diff --git a/source/python/software_engineering_twitter_phidget.rst b/source/python/software_engineering_twitter_phidget.rst deleted file mode 100644 index 84303135..00000000 --- a/source/python/software_engineering_twitter_phidget.rst +++ /dev/null @@ -1,34 +0,0 @@ -=============== -Twitter Phidget -=============== - -Question --------- - -ADDQUESTION - -Solution --------- - -.. literalinclude:: ../../languages/python/software_engineering_twitter_phidget.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/software_engineering_twitter_phidget.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`software_engineering_twitter_phidget.py` - * :python-better-explain:`software_engineering_twitter_phidget.rst` - diff --git a/source/python/software_engineering_xmlrpcclient.rst b/source/python/software_engineering_xmlrpcclient.rst deleted file mode 100644 index 4a401684..00000000 --- a/source/python/software_engineering_xmlrpcclient.rst +++ /dev/null @@ -1,34 +0,0 @@ -============== -Xmlr Pc Client -============== - -Question --------- - -ADDQUESTION - -Solution --------- - -.. literalinclude:: ../../languages/python/software_engineering_xmlrpcclient.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/software_engineering_xmlrpcclient.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`software_engineering_xmlrpcclient.py` - * :python-better-explain:`software_engineering_xmlrpcclient.rst` - diff --git a/source/python/software_engineering_xmlrpcserver.rst b/source/python/software_engineering_xmlrpcserver.rst deleted file mode 100644 index 7bbfff37..00000000 --- a/source/python/software_engineering_xmlrpcserver.rst +++ /dev/null @@ -1,34 +0,0 @@ -============== -Xmlr Pc Server -============== - -Question --------- - -ADDQUESTION - -Solution --------- - -.. literalinclude:: ../../languages/python/software_engineering_xmlrpcserver.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/software_engineering_xmlrpcserver.py - :language: python - :codesite: ideone - -Explanation -=========== - - - - - - - -.. seealso:: - - * :python-suggest-improve:`software_engineering_xmlrpcserver.py` - * :python-better-explain:`software_engineering_xmlrpcserver.rst` - diff --git a/source/python/text_manipulation_argparse1.rst b/source/python/text_manipulation_argparse1.rst deleted file mode 100644 index 13601ef0..00000000 --- a/source/python/text_manipulation_argparse1.rst +++ /dev/null @@ -1,26 +0,0 @@ -==================== -Argparse - Program 1 -==================== - -Question -======== - -.. literalinclude:: ../../languages/python/text_manipulation_argparse1.py - :language: python - :tab-width: 4 - -.. runcode:: ../../languages/python/text_manipulation_argparse1.py - :language: python - :codesite: ideone - -Explanation -============ - - - -.. seealso:: - - * :python-suggest-improve:`text_manipulation_argparse1.py` - * :python-better-explain:`text_manipulation_argparse1.rst` - - diff --git a/source/python/trie.rst b/source/python/trie.rst deleted file mode 100644 index 2969ff89..00000000 --- a/source/python/trie.rst +++ /dev/null @@ -1,68 +0,0 @@ -==== -Trie -==== - -Question --------- - -This is simple implementation of Trie data structure. - - -Solution --------- - -.. literalinclude:: ../../languages/python/trie.py - :language: python - :tab-width: 4 - - -Explanation -=========== - -Trie is implemented as a nested dictionary. The printed output shows that fact. -Every insert a new temp dictionary is created for nesting. - -The output of this program will be. - -:: - - { - "h": { - "e": { - "l": { - "l": { - "o": { - "*": "*" - } - }, - "p": { - "*": "*" - } - } - }, - "i": { - "*": "*" - } - } - } - True - False - True - - -Here is a visualization code for `make_trie` to see how the trie builds up over time. - -.. raw:: html - - - - - -.. git_changelog:: - - -.. seealso:: - - * :python-suggest-improve:`trie.py` - * :python-better-explain:`trie.rst` - diff --git a/static/uthcode-logo-transparent.png b/static/uthcode-logo-transparent.png new file mode 100644 index 00000000..9e3c6402 Binary files /dev/null and b/static/uthcode-logo-transparent.png differ diff --git a/utils/analytics.txt b/utils/analytics.txt new file mode 100644 index 00000000..1623eecc --- /dev/null +++ b/utils/analytics.txt @@ -0,0 +1,4 @@ +# Analytics + +https://analytics.eu.umami.is/websites/2df1f153-8058-48a6-bd46-c623df582814/realtime + diff --git a/utils/bin/__init__.py b/utils/bin/__init__.py deleted file mode 100644 index 838a3f27..00000000 --- a/utils/bin/__init__.py +++ /dev/null @@ -1 +0,0 @@ -__author__ = 'skumaran' diff --git a/utils/bin/add_program.py b/utils/bin/add_program.py deleted file mode 100755 index 70425b48..00000000 --- a/utils/bin/add_program.py +++ /dev/null @@ -1,136 +0,0 @@ -#!/usr/bin/python - -""" -BUGS: - 1. make cprogramming and cprogs dir into a single dir name. - -""" - -import os -import sys -import time - -LANGUAGE_PATH = '../../languages/' -NOW_FORMAT = '%d-%m-%Y %H:%M' -PROGRAM_NAME_TEMPLATE = 'PROGRAMNAME' -SOURCE_PATH = '../../source/' -TEMPLATE_FORMAT = '../{0}_template.rst' -INVALID_EXIT = -1 -PROGRAM_DIR = os.path.abspath(os.path.dirname(__file__)) - -USAGE = """ -add_program.py program_name - -program_name should follow pattern generic_specific.extension -""" - -def _now(): - return time.strftime(NOW_FORMAT, time.localtime(time.time())) - -def _comment_type(ext): - return { - 'c': '//', - 'py': '#', - 'rb': '#', - 'java': '//', - 'scala': '//'}.get(ext, '#') - -def _source_folder_name(language): - return { - 'c': 'cprogramming', - 'py': 'python', - 'rb': 'ruby', - 'scala': 'scala', - 'java': 'java'}.get(language, '') - -def _program_folder_name(language): - return { - 'c': 'cprogs', - 'py': 'python', - 'rb': 'ruby', - 'scala': 'scala', - 'java': 'java'}.get(language, '') - -def get_language_dir(language): - return os.path.abspath( - os.path.join( - PROGRAM_DIR, - LANGUAGE_PATH, - _program_folder_name(language))) - -def get_source_dir(language): - return os.path.abspath( - os.path.join( - PROGRAM_DIR, - SOURCE_PATH, - _source_folder_name(language))) - -def get_template_file(language): - template_path = TEMPLATE_FORMAT.format(_source_folder_name(language)) - return os.path.abspath(os.path.join(PROGRAM_DIR, template_path)) - -def create_program(filename): - ext = filename.split('.')[1] - with open(filename, 'w') as fh: - fh.write('{0} {1} - {2}'.format( - _comment_type(ext), - os.path.basename(filename), - _now())) - -def _program_name(program): - return program.split('.')[0] - -def _rst_filename(program): - return _program_name(program) + '.rst' - -def create_source(template, filename, program): - with open(template) as template_file: - with open(filename, 'w') as source_file: - for line in template_file: - source_file.write( - line.replace(PROGRAM_NAME_TEMPLATE, program)) - -def update_index_file(filename, program): - with open(filename, 'a') as f: - f.write(' %s\n\n' % program) - -def get_index_file(language): - return os.path.abspath(os.path.join(get_source_dir(language), 'index.rst')) - -def exit_if_not_exists(path): - if not os.path.exists(path): - print("{0} does not exists".format(path)) - sys.exit(-1) - -def main(args): - try: - program, = args - except ValueError: - print(USAGE) - sys.exit(-1) - - program_name, language = program.split('.') - - path = get_language_dir(language) - exit_if_not_exists(path) - program_file = os.path.abspath(os.path.join(path, program)) - create_program(program_file) - print('Created {0}'.format(program_file)) - - path = get_source_dir(language) - exit_if_not_exists(path) - source_file = os.path.abspath(os.path.join(path, _rst_filename(program))) - create_source( - get_template_file(language), - source_file, - _program_name(program)) - - print('Created {0}'.format(source_file)) - - filename = get_index_file(language) - exit_if_not_exists(filename) - update_index_file(filename, _program_name(program)) - print('Updated {0}'.format(filename)) - -if __name__ == '__main__': - main(sys.argv[1:]) diff --git a/utils/cprogramming_template.rst b/utils/cprogramming_template.rst deleted file mode 100644 index a0c0019f..00000000 --- a/utils/cprogramming_template.rst +++ /dev/null @@ -1,28 +0,0 @@ -======================= -Exercise NUMBER - TITLE -======================= - -Question -======== - -ADDQUESTION - - -.. literalinclude:: ../../languages/cprogs/PROGRAMNAME.c - :language: c - :tab-width: 4 - -.. runcode:: ../../languages/cprogs/PROGRAMNAME.c - :language: c - :codesite: ideone - -Explanation -=========== - -.. git_changelog:: - - -.. seealso:: - - * :c-suggest-improve:`PROGRAMNAME.c` - * :c-better-explain:`PROGRAMNAME.rst` diff --git a/utils/requirements.txt b/utils/requirements.txt deleted file mode 100644 index 10b1c6c1..00000000 --- a/utils/requirements.txt +++ /dev/null @@ -1,2 +0,0 @@ -https://dl.dropbox.com/s/u66xbjsfi1o7yw7/sphinxcontrib-runcode-0.2.1.tar.gz -https://dl.dropbox.com/s/81rheg9ba3w55cx/sphinx-bootstrap-theme-0.4.2.tar.gz